babylon.viewer.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. if(typeof exports === 'object' && typeof module === 'object') {
  4. module.exports = factory();
  5. } else if(typeof define === 'function' && define.amd) {
  6. define("babylonjs-viewer", amdDependencies, factory);
  7. } else if(typeof exports === 'object') {
  8. exports["babylonjs-viewer"] = factory();
  9. } else {
  10. root["BabylonViewer"] = factory();
  11. }
  12. })(this, function() {
  13. var BabylonViewer =
  14. /******/ (function(modules) { // webpackBootstrap
  15. /******/ // The module cache
  16. /******/ var installedModules = {};
  17. /******/
  18. /******/ // The require function
  19. /******/ function __webpack_require__(moduleId) {
  20. /******/
  21. /******/ // Check if module is in cache
  22. /******/ if(installedModules[moduleId]) {
  23. /******/ return installedModules[moduleId].exports;
  24. /******/ }
  25. /******/ // Create a new module (and put it into the cache)
  26. /******/ var module = installedModules[moduleId] = {
  27. /******/ i: moduleId,
  28. /******/ l: false,
  29. /******/ exports: {}
  30. /******/ };
  31. /******/
  32. /******/ // Execute the module function
  33. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  34. /******/
  35. /******/ // Flag the module as loaded
  36. /******/ module.l = true;
  37. /******/
  38. /******/ // Return the exports of the module
  39. /******/ return module.exports;
  40. /******/ }
  41. /******/
  42. /******/
  43. /******/ // expose the modules object (__webpack_modules__)
  44. /******/ __webpack_require__.m = modules;
  45. /******/
  46. /******/ // expose the module cache
  47. /******/ __webpack_require__.c = installedModules;
  48. /******/
  49. /******/ // define getter function for harmony exports
  50. /******/ __webpack_require__.d = function(exports, name, getter) {
  51. /******/ if(!__webpack_require__.o(exports, name)) {
  52. /******/ Object.defineProperty(exports, name, {
  53. /******/ configurable: false,
  54. /******/ enumerable: true,
  55. /******/ get: getter
  56. /******/ });
  57. /******/ }
  58. /******/ };
  59. /******/
  60. /******/ // getDefaultExport function for compatibility with non-harmony modules
  61. /******/ __webpack_require__.n = function(module) {
  62. /******/ var getter = module && module.__esModule ?
  63. /******/ function getDefault() { return module['default']; } :
  64. /******/ function getModuleExports() { return module; };
  65. /******/ __webpack_require__.d(getter, 'a', getter);
  66. /******/ return getter;
  67. /******/ };
  68. /******/
  69. /******/ // Object.prototype.hasOwnProperty.call
  70. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  71. /******/
  72. /******/ // __webpack_public_path__
  73. /******/ __webpack_require__.p = "";
  74. /******/
  75. /******/ // Load entry module and return exports
  76. /******/ return __webpack_require__(__webpack_require__.s = 21);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {
  83. (function universalModuleDefinition(root, factory) {
  84. var amdDependencies = [];
  85. var CANNON = root.CANNON || this.CANNON;
  86. var OIMO = root.OIMO || this.OIMO;
  87. var earcut = root.earcut || this.earcut;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(23); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(24); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(25); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. effect._bonesComputationForcedToCPU = true;
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else if (otherMesh.subMeshes) {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. /** @hidden */
  272. this._bonesComputationForcedToCPU = false;
  273. this._uniformBuffersNames = {};
  274. this._isReady = false;
  275. this._compilationError = "";
  276. this.name = baseName;
  277. if (attributesNamesOrOptions.attributes) {
  278. var options = attributesNamesOrOptions;
  279. this._engine = uniformsNamesOrEngine;
  280. this._attributesNames = options.attributes;
  281. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  282. this._samplers = options.samplers.slice();
  283. this.defines = options.defines;
  284. this.onError = options.onError;
  285. this.onCompiled = options.onCompiled;
  286. this._fallbacks = options.fallbacks;
  287. this._indexParameters = options.indexParameters;
  288. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  289. if (options.uniformBuffersNames) {
  290. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  291. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  292. }
  293. }
  294. }
  295. else {
  296. this._engine = engine;
  297. this.defines = defines;
  298. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  299. this._samplers = samplers ? samplers.slice() : [];
  300. this._attributesNames = attributesNamesOrOptions;
  301. this.onError = onError;
  302. this.onCompiled = onCompiled;
  303. this._indexParameters = indexParameters;
  304. this._fallbacks = fallbacks;
  305. }
  306. this.uniqueId = Effect._uniqueIdSeed++;
  307. var vertexSource;
  308. var fragmentSource;
  309. if (baseName.vertexElement) {
  310. vertexSource = document.getElementById(baseName.vertexElement);
  311. if (!vertexSource) {
  312. vertexSource = baseName.vertexElement;
  313. }
  314. }
  315. else {
  316. vertexSource = baseName.vertex || baseName;
  317. }
  318. if (baseName.fragmentElement) {
  319. fragmentSource = document.getElementById(baseName.fragmentElement);
  320. if (!fragmentSource) {
  321. fragmentSource = baseName.fragmentElement;
  322. }
  323. }
  324. else {
  325. fragmentSource = baseName.fragment || baseName;
  326. }
  327. this._loadVertexShader(vertexSource, function (vertexCode) {
  328. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  329. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  330. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  331. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  332. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  333. if (baseName) {
  334. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  335. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  336. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  337. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  338. }
  339. else {
  340. _this._vertexSourceCode = migratedVertexCode;
  341. _this._fragmentSourceCode = migratedFragmentCode;
  342. }
  343. _this._prepareEffect();
  344. });
  345. });
  346. });
  347. });
  348. });
  349. });
  350. }
  351. Object.defineProperty(Effect.prototype, "key", {
  352. /**
  353. * Unique key for this effect
  354. */
  355. get: function () {
  356. return this._key;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. /**
  362. * If the effect has been compiled and prepared.
  363. * @returns if the effect is compiled and prepared.
  364. */
  365. Effect.prototype.isReady = function () {
  366. return this._isReady;
  367. };
  368. /**
  369. * The engine the effect was initialized with.
  370. * @returns the engine.
  371. */
  372. Effect.prototype.getEngine = function () {
  373. return this._engine;
  374. };
  375. /**
  376. * The compiled webGL program for the effect
  377. * @returns the webGL program.
  378. */
  379. Effect.prototype.getProgram = function () {
  380. return this._program;
  381. };
  382. /**
  383. * The set of names of attribute variables for the shader.
  384. * @returns An array of attribute names.
  385. */
  386. Effect.prototype.getAttributesNames = function () {
  387. return this._attributesNames;
  388. };
  389. /**
  390. * Returns the attribute at the given index.
  391. * @param index The index of the attribute.
  392. * @returns The location of the attribute.
  393. */
  394. Effect.prototype.getAttributeLocation = function (index) {
  395. return this._attributes[index];
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param name of the attribute to look up.
  400. * @returns the attribute location.
  401. */
  402. Effect.prototype.getAttributeLocationByName = function (name) {
  403. var index = this._attributesNames.indexOf(name);
  404. return this._attributes[index];
  405. };
  406. /**
  407. * The number of attributes.
  408. * @returns the numnber of attributes.
  409. */
  410. Effect.prototype.getAttributesCount = function () {
  411. return this._attributes.length;
  412. };
  413. /**
  414. * Gets the index of a uniform variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the index.
  417. */
  418. Effect.prototype.getUniformIndex = function (uniformName) {
  419. return this._uniformsNames.indexOf(uniformName);
  420. };
  421. /**
  422. * Returns the attribute based on the name of the variable.
  423. * @param uniformName of the uniform to look up.
  424. * @returns the location of the uniform.
  425. */
  426. Effect.prototype.getUniform = function (uniformName) {
  427. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  428. };
  429. /**
  430. * Returns an array of sampler variable names
  431. * @returns The array of sampler variable neames.
  432. */
  433. Effect.prototype.getSamplers = function () {
  434. return this._samplers;
  435. };
  436. /**
  437. * The error from the last compilation.
  438. * @returns the error string.
  439. */
  440. Effect.prototype.getCompilationError = function () {
  441. return this._compilationError;
  442. };
  443. /**
  444. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  445. * @param func The callback to be used.
  446. */
  447. Effect.prototype.executeWhenCompiled = function (func) {
  448. if (this.isReady()) {
  449. func(this);
  450. return;
  451. }
  452. this.onCompileObservable.add(function (effect) {
  453. func(effect);
  454. });
  455. };
  456. /** @hidden */
  457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  458. if (BABYLON.Tools.IsWindowObjectExist()) {
  459. // DOM element ?
  460. if (vertex instanceof HTMLElement) {
  461. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  462. callback(vertexCode);
  463. return;
  464. }
  465. }
  466. // Base64 encoded ?
  467. if (vertex.substr(0, 7) === "base64:") {
  468. var vertexBinary = window.atob(vertex.substr(7));
  469. callback(vertexBinary);
  470. return;
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  474. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  475. return;
  476. }
  477. var vertexShaderUrl;
  478. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  479. vertexShaderUrl = vertex;
  480. }
  481. else {
  482. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  483. }
  484. // Vertex shader
  485. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  486. };
  487. /** @hidden */
  488. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  489. if (BABYLON.Tools.IsWindowObjectExist()) {
  490. // DOM element ?
  491. if (fragment instanceof HTMLElement) {
  492. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  493. callback(fragmentCode);
  494. return;
  495. }
  496. }
  497. // Base64 encoded ?
  498. if (fragment.substr(0, 7) === "base64:") {
  499. var fragmentBinary = window.atob(fragment.substr(7));
  500. callback(fragmentBinary);
  501. return;
  502. }
  503. // Is in local store ?
  504. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  505. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  506. return;
  507. }
  508. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  509. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  510. return;
  511. }
  512. var fragmentShaderUrl;
  513. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  514. fragmentShaderUrl = fragment;
  515. }
  516. else {
  517. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  518. }
  519. // Fragment shader
  520. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  521. };
  522. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  523. // Rebuild shaders source code
  524. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  525. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  526. vertexCode = prefix + vertexCode;
  527. fragmentCode = prefix + fragmentCode;
  528. // Number lines of shaders source code
  529. var i = 2;
  530. var regex = /\n/gm;
  531. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. i = 2;
  533. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  534. // Dump shaders name and formatted source code
  535. if (this.name.vertexElement) {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  538. }
  539. else if (this.name.vertex) {
  540. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  541. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  542. }
  543. else {
  544. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  545. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  546. }
  547. };
  548. ;
  549. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  550. var preparedSourceCode = this._processPrecision(sourceCode);
  551. if (this._engine.webGLVersion == 1) {
  552. callback(preparedSourceCode);
  553. return;
  554. }
  555. // Already converted
  556. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  557. callback(preparedSourceCode.replace("#version 300 es", ""));
  558. return;
  559. }
  560. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  561. // Remove extensions
  562. // #extension GL_OES_standard_derivatives : enable
  563. // #extension GL_EXT_shader_texture_lod : enable
  564. // #extension GL_EXT_frag_depth : enable
  565. // #extension GL_EXT_draw_buffers : require
  566. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  567. var result = preparedSourceCode.replace(regex, "");
  568. // Migrate to GLSL v300
  569. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  570. result = result.replace(/attribute[ \t]/g, "in ");
  571. result = result.replace(/[ \t]attribute/g, " in");
  572. if (isFragment) {
  573. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  574. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/texture2D\s*\(/g, "texture(");
  576. result = result.replace(/textureCube\s*\(/g, "texture(");
  577. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  578. result = result.replace(/gl_FragColor/g, "glFragColor");
  579. result = result.replace(/gl_FragData/g, "glFragData");
  580. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  581. }
  582. callback(result);
  583. };
  584. Effect.prototype._processIncludes = function (sourceCode, callback) {
  585. var _this = this;
  586. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  587. var match = regex.exec(sourceCode);
  588. var returnValue = new String(sourceCode);
  589. while (match != null) {
  590. var includeFile = match[1];
  591. // Uniform declaration
  592. if (includeFile.indexOf("__decl__") !== -1) {
  593. includeFile = includeFile.replace(/__decl__/, "");
  594. if (this._engine.supportsUniformBuffers) {
  595. includeFile = includeFile.replace(/Vertex/, "Ubo");
  596. includeFile = includeFile.replace(/Fragment/, "Ubo");
  597. }
  598. includeFile = includeFile + "Declaration";
  599. }
  600. if (Effect.IncludesShadersStore[includeFile]) {
  601. // Substitution
  602. var includeContent = Effect.IncludesShadersStore[includeFile];
  603. if (match[2]) {
  604. var splits = match[3].split(",");
  605. for (var index = 0; index < splits.length; index += 2) {
  606. var source = new RegExp(splits[index], "g");
  607. var dest = splits[index + 1];
  608. includeContent = includeContent.replace(source, dest);
  609. }
  610. }
  611. if (match[4]) {
  612. var indexString = match[5];
  613. if (indexString.indexOf("..") !== -1) {
  614. var indexSplits = indexString.split("..");
  615. var minIndex = parseInt(indexSplits[0]);
  616. var maxIndex = parseInt(indexSplits[1]);
  617. var sourceIncludeContent = includeContent.slice(0);
  618. includeContent = "";
  619. if (isNaN(maxIndex)) {
  620. maxIndex = this._indexParameters[indexSplits[1]];
  621. }
  622. for (var i = minIndex; i < maxIndex; i++) {
  623. if (!this._engine.supportsUniformBuffers) {
  624. // Ubo replacement
  625. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  626. return p1 + "{X}";
  627. });
  628. }
  629. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  630. }
  631. }
  632. else {
  633. if (!this._engine.supportsUniformBuffers) {
  634. // Ubo replacement
  635. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  636. return p1 + "{X}";
  637. });
  638. }
  639. includeContent = includeContent.replace(/\{X\}/g, indexString);
  640. }
  641. }
  642. // Replace
  643. returnValue = returnValue.replace(match[0], includeContent);
  644. }
  645. else {
  646. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  647. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  648. Effect.IncludesShadersStore[includeFile] = fileContent;
  649. _this._processIncludes(returnValue, callback);
  650. });
  651. return;
  652. }
  653. match = regex.exec(sourceCode);
  654. }
  655. callback(returnValue);
  656. };
  657. Effect.prototype._processPrecision = function (source) {
  658. if (source.indexOf("precision highp float") === -1) {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = "precision mediump float;\n" + source;
  661. }
  662. else {
  663. source = "precision highp float;\n" + source;
  664. }
  665. }
  666. else {
  667. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  668. source = source.replace("precision highp float", "precision mediump float");
  669. }
  670. }
  671. return source;
  672. };
  673. /**
  674. * Recompiles the webGL program
  675. * @param vertexSourceCode The source code for the vertex shader.
  676. * @param fragmentSourceCode The source code for the fragment shader.
  677. * @param onCompiled Callback called when completed.
  678. * @param onError Callback called on error.
  679. */
  680. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  681. var _this = this;
  682. this._isReady = false;
  683. this._vertexSourceCodeOverride = vertexSourceCode;
  684. this._fragmentSourceCodeOverride = fragmentSourceCode;
  685. this.onError = function (effect, error) {
  686. if (onError) {
  687. onError(error);
  688. }
  689. };
  690. this.onCompiled = function () {
  691. var scenes = _this.getEngine().scenes;
  692. for (var i = 0; i < scenes.length; i++) {
  693. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  694. }
  695. if (onCompiled) {
  696. onCompiled(_this._program);
  697. }
  698. };
  699. this._fallbacks = null;
  700. this._prepareEffect();
  701. };
  702. /**
  703. * Gets the uniform locations of the the specified variable names
  704. * @param names THe names of the variables to lookup.
  705. * @returns Array of locations in the same order as variable names.
  706. */
  707. Effect.prototype.getSpecificUniformLocations = function (names) {
  708. var engine = this._engine;
  709. return engine.getUniforms(this._program, names);
  710. };
  711. /**
  712. * Prepares the effect
  713. */
  714. Effect.prototype._prepareEffect = function () {
  715. var attributesNames = this._attributesNames;
  716. var defines = this.defines;
  717. var fallbacks = this._fallbacks;
  718. this._valueCache = {};
  719. var previousProgram = this._program;
  720. try {
  721. var engine = this._engine;
  722. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  723. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  724. }
  725. else {
  726. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  727. }
  728. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  729. if (engine.supportsUniformBuffers) {
  730. for (var name in this._uniformBuffersNames) {
  731. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  732. }
  733. }
  734. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  735. this._attributes = engine.getAttributes(this._program, attributesNames);
  736. var index;
  737. for (index = 0; index < this._samplers.length; index++) {
  738. var sampler = this.getUniform(this._samplers[index]);
  739. if (sampler == null) {
  740. this._samplers.splice(index, 1);
  741. index--;
  742. }
  743. }
  744. engine.bindSamplers(this);
  745. this._compilationError = "";
  746. this._isReady = true;
  747. if (this.onCompiled) {
  748. this.onCompiled(this);
  749. }
  750. this.onCompileObservable.notifyObservers(this);
  751. this.onCompileObservable.clear();
  752. // Unbind mesh reference in fallbacks
  753. if (this._fallbacks) {
  754. this._fallbacks.unBindMesh();
  755. }
  756. if (previousProgram) {
  757. this.getEngine()._deleteProgram(previousProgram);
  758. }
  759. }
  760. catch (e) {
  761. this._compilationError = e.message;
  762. // Let's go through fallbacks then
  763. BABYLON.Tools.Error("Unable to compile effect:");
  764. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  765. return " " + uniform;
  766. }));
  767. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  768. return " " + attribute;
  769. }));
  770. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  771. BABYLON.Tools.Error("Error: " + this._compilationError);
  772. if (previousProgram) {
  773. this._program = previousProgram;
  774. this._isReady = true;
  775. if (this.onError) {
  776. this.onError(this, this._compilationError);
  777. }
  778. this.onErrorObservable.notifyObservers(this);
  779. }
  780. if (fallbacks && fallbacks.isMoreFallbacks) {
  781. BABYLON.Tools.Error("Trying next fallback.");
  782. this.defines = fallbacks.reduce(this.defines, this);
  783. this._prepareEffect();
  784. }
  785. else { // Sorry we did everything we can
  786. if (this.onError) {
  787. this.onError(this, this._compilationError);
  788. }
  789. this.onErrorObservable.notifyObservers(this);
  790. this.onErrorObservable.clear();
  791. // Unbind mesh reference in fallbacks
  792. if (this._fallbacks) {
  793. this._fallbacks.unBindMesh();
  794. }
  795. }
  796. }
  797. };
  798. Object.defineProperty(Effect.prototype, "isSupported", {
  799. /**
  800. * Checks if the effect is supported. (Must be called after compilation)
  801. */
  802. get: function () {
  803. return this._compilationError === "";
  804. },
  805. enumerable: true,
  806. configurable: true
  807. });
  808. /**
  809. * Binds a texture to the engine to be used as output of the shader.
  810. * @param channel Name of the output variable.
  811. * @param texture Texture to bind.
  812. */
  813. Effect.prototype._bindTexture = function (channel, texture) {
  814. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  815. };
  816. /**
  817. * Sets a texture on the engine to be used in the shader.
  818. * @param channel Name of the sampler variable.
  819. * @param texture Texture to set.
  820. */
  821. Effect.prototype.setTexture = function (channel, texture) {
  822. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  826. * @param channel Name of the sampler variable.
  827. * @param texture Texture to set.
  828. */
  829. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  830. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  831. };
  832. /**
  833. * Sets an array of textures on the engine to be used in the shader.
  834. * @param channel Name of the variable.
  835. * @param textures Textures to set.
  836. */
  837. Effect.prototype.setTextureArray = function (channel, textures) {
  838. if (this._samplers.indexOf(channel + "Ex") === -1) {
  839. var initialPos = this._samplers.indexOf(channel);
  840. for (var index = 1; index < textures.length; index++) {
  841. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  842. }
  843. }
  844. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  845. };
  846. /**
  847. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  848. * @param channel Name of the sampler variable.
  849. * @param postProcess Post process to get the input texture from.
  850. */
  851. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  852. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  853. };
  854. /**
  855. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  856. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  857. * @param channel Name of the sampler variable.
  858. * @param postProcess Post process to get the output texture from.
  859. */
  860. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  861. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  862. };
  863. /** @hidden */
  864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  865. var cache = this._valueCache[uniformName];
  866. var flag = matrix.updateFlag;
  867. if (cache !== undefined && cache === flag) {
  868. return false;
  869. }
  870. this._valueCache[uniformName] = flag;
  871. return true;
  872. };
  873. /** @hidden */
  874. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  875. var cache = this._valueCache[uniformName];
  876. if (!cache) {
  877. cache = [x, y];
  878. this._valueCache[uniformName] = cache;
  879. return true;
  880. }
  881. var changed = false;
  882. if (cache[0] !== x) {
  883. cache[0] = x;
  884. changed = true;
  885. }
  886. if (cache[1] !== y) {
  887. cache[1] = y;
  888. changed = true;
  889. }
  890. return changed;
  891. };
  892. /** @hidden */
  893. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  894. var cache = this._valueCache[uniformName];
  895. if (!cache) {
  896. cache = [x, y, z];
  897. this._valueCache[uniformName] = cache;
  898. return true;
  899. }
  900. var changed = false;
  901. if (cache[0] !== x) {
  902. cache[0] = x;
  903. changed = true;
  904. }
  905. if (cache[1] !== y) {
  906. cache[1] = y;
  907. changed = true;
  908. }
  909. if (cache[2] !== z) {
  910. cache[2] = z;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /** @hidden */
  916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  917. var cache = this._valueCache[uniformName];
  918. if (!cache) {
  919. cache = [x, y, z, w];
  920. this._valueCache[uniformName] = cache;
  921. return true;
  922. }
  923. var changed = false;
  924. if (cache[0] !== x) {
  925. cache[0] = x;
  926. changed = true;
  927. }
  928. if (cache[1] !== y) {
  929. cache[1] = y;
  930. changed = true;
  931. }
  932. if (cache[2] !== z) {
  933. cache[2] = z;
  934. changed = true;
  935. }
  936. if (cache[3] !== w) {
  937. cache[3] = w;
  938. changed = true;
  939. }
  940. return changed;
  941. };
  942. /**
  943. * Binds a buffer to a uniform.
  944. * @param buffer Buffer to bind.
  945. * @param name Name of the uniform variable to bind to.
  946. */
  947. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  948. var bufferName = this._uniformBuffersNames[name];
  949. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  950. return;
  951. }
  952. Effect._baseCache[bufferName] = buffer;
  953. this._engine.bindUniformBufferBase(buffer, bufferName);
  954. };
  955. /**
  956. * Binds block to a uniform.
  957. * @param blockName Name of the block to bind.
  958. * @param index Index to bind.
  959. */
  960. Effect.prototype.bindUniformBlock = function (blockName, index) {
  961. this._engine.bindUniformBlock(this._program, blockName, index);
  962. };
  963. /**
  964. * Sets an interger value on a uniform variable.
  965. * @param uniformName Name of the variable.
  966. * @param value Value to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setInt = function (uniformName, value) {
  970. var cache = this._valueCache[uniformName];
  971. if (cache !== undefined && cache === value)
  972. return this;
  973. this._valueCache[uniformName] = value;
  974. this._engine.setInt(this.getUniform(uniformName), value);
  975. return this;
  976. };
  977. /**
  978. * Sets an int array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setIntArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setIntArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setIntArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setIntArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an float array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setFloatArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets an array on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param array array to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setArray = function (uniformName, array) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setArray(this.getUniform(uniformName), array);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1078. * @param uniformName Name of the variable.
  1079. * @param array array to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setArray2 = function (uniformName, array) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setArray2(this.getUniform(uniformName), array);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1089. * @param uniformName Name of the variable.
  1090. * @param array array to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setArray3 = function (uniformName, array) {
  1094. this._valueCache[uniformName] = null;
  1095. this._engine.setArray3(this.getUniform(uniformName), array);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1100. * @param uniformName Name of the variable.
  1101. * @param array array to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setArray4 = function (uniformName, array) {
  1105. this._valueCache[uniformName] = null;
  1106. this._engine.setArray4(this.getUniform(uniformName), array);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets matrices on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param matrices matrices to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1116. if (!matrices) {
  1117. return this;
  1118. }
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets matrix on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param matrix matrix to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1130. if (this._cacheMatrix(uniformName, matrix)) {
  1131. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1137. * @param uniformName Name of the variable.
  1138. * @param matrix matrix to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1142. this._valueCache[uniformName] = null;
  1143. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1148. * @param uniformName Name of the variable.
  1149. * @param matrix matrix to be set.
  1150. * @returns this effect.
  1151. */
  1152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets a float on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param value value to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setFloat = function (uniformName, value) {
  1164. var cache = this._valueCache[uniformName];
  1165. if (cache !== undefined && cache === value)
  1166. return this;
  1167. this._valueCache[uniformName] = value;
  1168. this._engine.setFloat(this.getUniform(uniformName), value);
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a boolean on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param bool value to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setBool = function (uniformName, bool) {
  1178. var cache = this._valueCache[uniformName];
  1179. if (cache !== undefined && cache === bool)
  1180. return this;
  1181. this._valueCache[uniformName] = bool;
  1182. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1183. return this;
  1184. };
  1185. /**
  1186. * Sets a Vector2 on a uniform variable.
  1187. * @param uniformName Name of the variable.
  1188. * @param vector2 vector2 to be set.
  1189. * @returns this effect.
  1190. */
  1191. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1192. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1193. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1194. }
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a float2 on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param x First float in float2.
  1201. * @param y Second float in float2.
  1202. * @returns this effect.
  1203. */
  1204. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1205. if (this._cacheFloat2(uniformName, x, y)) {
  1206. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1207. }
  1208. return this;
  1209. };
  1210. /**
  1211. * Sets a Vector3 on a uniform variable.
  1212. * @param uniformName Name of the variable.
  1213. * @param vector3 Value to be set.
  1214. * @returns this effect.
  1215. */
  1216. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1217. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1218. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1219. }
  1220. return this;
  1221. };
  1222. /**
  1223. * Sets a float3 on a uniform variable.
  1224. * @param uniformName Name of the variable.
  1225. * @param x First float in float3.
  1226. * @param y Second float in float3.
  1227. * @param z Third float in float3.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1231. if (this._cacheFloat3(uniformName, x, y, z)) {
  1232. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector4 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector4 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1243. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1244. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float4.
  1252. * @param y Second float in float4.
  1253. * @param z Third float in float4.
  1254. * @param w Fourth float in float4.
  1255. * @returns this effect.
  1256. */
  1257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1260. }
  1261. return this;
  1262. };
  1263. /**
  1264. * Sets a Color3 on a uniform variable.
  1265. * @param uniformName Name of the variable.
  1266. * @param color3 Value to be set.
  1267. * @returns this effect.
  1268. */
  1269. Effect.prototype.setColor3 = function (uniformName, color3) {
  1270. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1271. this._engine.setColor3(this.getUniform(uniformName), color3);
  1272. }
  1273. return this;
  1274. };
  1275. /**
  1276. * Sets a Color4 on a uniform variable.
  1277. * @param uniformName Name of the variable.
  1278. * @param color3 Value to be set.
  1279. * @param alpha Alpha value to be set.
  1280. * @returns this effect.
  1281. */
  1282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1283. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1284. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1285. }
  1286. return this;
  1287. };
  1288. /**
  1289. * Sets a Color4 on a uniform variable
  1290. * @param uniformName defines the name of the variable
  1291. * @param color4 defines the value to be set
  1292. * @returns this effect.
  1293. */
  1294. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1295. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1296. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1297. }
  1298. return this;
  1299. };
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. Effect.ResetCache = function () {
  1304. Effect._baseCache = {};
  1305. };
  1306. Effect._uniqueIdSeed = 0;
  1307. Effect._baseCache = {};
  1308. /**
  1309. * Store of each shader (The can be looked up using effect.key)
  1310. */
  1311. Effect.ShadersStore = {};
  1312. /**
  1313. * Store of each included file for a shader (The can be looked up using effect.key)
  1314. */
  1315. Effect.IncludesShadersStore = {};
  1316. return Effect;
  1317. }());
  1318. BABYLON.Effect = Effect;
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.effect.js.map
  1321. //# sourceMappingURL=babylon.types.js.map
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. var PointerEventTypes = /** @class */ (function () {
  1373. function PointerEventTypes() {
  1374. }
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOWN;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1383. get: function () {
  1384. return PointerEventTypes._POINTERUP;
  1385. },
  1386. enumerable: true,
  1387. configurable: true
  1388. });
  1389. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1390. get: function () {
  1391. return PointerEventTypes._POINTERMOVE;
  1392. },
  1393. enumerable: true,
  1394. configurable: true
  1395. });
  1396. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1397. get: function () {
  1398. return PointerEventTypes._POINTERWHEEL;
  1399. },
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERPICK;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERTAP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERDOUBLETAP;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. PointerEventTypes._POINTERDOWN = 0x01;
  1425. PointerEventTypes._POINTERUP = 0x02;
  1426. PointerEventTypes._POINTERMOVE = 0x04;
  1427. PointerEventTypes._POINTERWHEEL = 0x08;
  1428. PointerEventTypes._POINTERPICK = 0x10;
  1429. PointerEventTypes._POINTERTAP = 0x20;
  1430. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1431. return PointerEventTypes;
  1432. }());
  1433. BABYLON.PointerEventTypes = PointerEventTypes;
  1434. var PointerInfoBase = /** @class */ (function () {
  1435. function PointerInfoBase(type, event) {
  1436. this.type = type;
  1437. this.event = event;
  1438. }
  1439. return PointerInfoBase;
  1440. }());
  1441. BABYLON.PointerInfoBase = PointerInfoBase;
  1442. /**
  1443. * This class is used to store pointer related info for the onPrePointerObservable event.
  1444. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1445. */
  1446. var PointerInfoPre = /** @class */ (function (_super) {
  1447. __extends(PointerInfoPre, _super);
  1448. function PointerInfoPre(type, event, localX, localY) {
  1449. var _this = _super.call(this, type, event) || this;
  1450. _this.skipOnPointerObservable = false;
  1451. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1452. return _this;
  1453. }
  1454. return PointerInfoPre;
  1455. }(PointerInfoBase));
  1456. BABYLON.PointerInfoPre = PointerInfoPre;
  1457. /**
  1458. * This type contains all the data related to a pointer event in Babylon.js.
  1459. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1460. */
  1461. var PointerInfo = /** @class */ (function (_super) {
  1462. __extends(PointerInfo, _super);
  1463. function PointerInfo(type, event, pickInfo) {
  1464. var _this = _super.call(this, type, event) || this;
  1465. _this.pickInfo = pickInfo;
  1466. return _this;
  1467. }
  1468. return PointerInfo;
  1469. }(PointerInfoBase));
  1470. BABYLON.PointerInfo = PointerInfo;
  1471. })(BABYLON || (BABYLON = {}));
  1472. //# sourceMappingURL=babylon.pointerEvents.js.map
  1473. var BABYLON;
  1474. (function (BABYLON) {
  1475. BABYLON.ToGammaSpace = 1 / 2.2;
  1476. BABYLON.ToLinearSpace = 2.2;
  1477. BABYLON.Epsilon = 0.001;
  1478. /**
  1479. * Class used to hold a RBG color
  1480. */
  1481. var Color3 = /** @class */ (function () {
  1482. /**
  1483. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1484. * @param r defines the red component (between 0 and 1, default is 0)
  1485. * @param g defines the green component (between 0 and 1, default is 0)
  1486. * @param b defines the blue component (between 0 and 1, default is 0)
  1487. */
  1488. function Color3(
  1489. /**
  1490. * Defines the red component (between 0 and 1, default is 0)
  1491. */
  1492. r,
  1493. /**
  1494. * Defines the green component (between 0 and 1, default is 0)
  1495. */
  1496. g,
  1497. /**
  1498. * Defines the blue component (between 0 and 1, default is 0)
  1499. */
  1500. b) {
  1501. if (r === void 0) { r = 0; }
  1502. if (g === void 0) { g = 0; }
  1503. if (b === void 0) { b = 0; }
  1504. this.r = r;
  1505. this.g = g;
  1506. this.b = b;
  1507. }
  1508. /**
  1509. * Creates a string with the Color3 current values
  1510. * @returns the string representation of the Color3 object
  1511. */
  1512. Color3.prototype.toString = function () {
  1513. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1514. };
  1515. /**
  1516. * Returns the string "Color3"
  1517. * @returns "Color3"
  1518. */
  1519. Color3.prototype.getClassName = function () {
  1520. return "Color3";
  1521. };
  1522. /**
  1523. * Compute the Color3 hash code
  1524. * @returns an unique number that can be used to hash Color3 objects
  1525. */
  1526. Color3.prototype.getHashCode = function () {
  1527. var hash = this.r || 0;
  1528. hash = (hash * 397) ^ (this.g || 0);
  1529. hash = (hash * 397) ^ (this.b || 0);
  1530. return hash;
  1531. };
  1532. // Operators
  1533. /**
  1534. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1535. * @param array defines the array where to store the r,g,b components
  1536. * @param index defines an optional index in the target array to define where to start storing values
  1537. * @returns the current Color3 object
  1538. */
  1539. Color3.prototype.toArray = function (array, index) {
  1540. if (index === undefined) {
  1541. index = 0;
  1542. }
  1543. array[index] = this.r;
  1544. array[index + 1] = this.g;
  1545. array[index + 2] = this.b;
  1546. return this;
  1547. };
  1548. /**
  1549. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1550. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1551. * @returns a new {BABYLON.Color4} object
  1552. */
  1553. Color3.prototype.toColor4 = function (alpha) {
  1554. if (alpha === void 0) { alpha = 1; }
  1555. return new Color4(this.r, this.g, this.b, alpha);
  1556. };
  1557. /**
  1558. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1559. * @returns the new array
  1560. */
  1561. Color3.prototype.asArray = function () {
  1562. var result = new Array();
  1563. this.toArray(result, 0);
  1564. return result;
  1565. };
  1566. /**
  1567. * Returns the luminance value
  1568. * @returns a float value
  1569. */
  1570. Color3.prototype.toLuminance = function () {
  1571. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1572. };
  1573. /**
  1574. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3 object
  1577. */
  1578. Color3.prototype.multiply = function (otherColor) {
  1579. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1580. };
  1581. /**
  1582. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines the Color3 object where to store the result
  1585. * @returns the current Color3
  1586. */
  1587. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1588. result.r = this.r * otherColor.r;
  1589. result.g = this.g * otherColor.g;
  1590. result.b = this.b * otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Determines equality between Color3 objects
  1595. * @param otherColor defines the second operand
  1596. * @returns true if the rgb values are equal to the given ones
  1597. */
  1598. Color3.prototype.equals = function (otherColor) {
  1599. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1600. };
  1601. /**
  1602. * Determines equality between the current Color3 object and a set of r,b,g values
  1603. * @param r defines the red component to check
  1604. * @param g defines the green component to check
  1605. * @param b defines the blue component to check
  1606. * @returns true if the rgb values are equal to the given ones
  1607. */
  1608. Color3.prototype.equalsFloats = function (r, g, b) {
  1609. return this.r === r && this.g === g && this.b === b;
  1610. };
  1611. /**
  1612. * Multiplies in place each rgb value by scale
  1613. * @param scale defines the scaling factor
  1614. * @returns the updated Color3
  1615. */
  1616. Color3.prototype.scale = function (scale) {
  1617. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1618. };
  1619. /**
  1620. * Multiplies the rgb values by scale and stores the result into "result"
  1621. * @param scale defines the scaling factor
  1622. * @param result defines the Color3 object where to store the result
  1623. * @returns the unmodified current Color3
  1624. */
  1625. Color3.prototype.scaleToRef = function (scale, result) {
  1626. result.r = this.r * scale;
  1627. result.g = this.g * scale;
  1628. result.b = this.b * scale;
  1629. return this;
  1630. };
  1631. /**
  1632. * Scale the current Color3 values by a factor and add the result to a given Color3
  1633. * @param scale defines the scale factor
  1634. * @param result defines color to store the result into
  1635. * @returns the unmodified current Color3
  1636. */
  1637. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1638. result.r += this.r * scale;
  1639. result.g += this.g * scale;
  1640. result.b += this.b * scale;
  1641. return this;
  1642. };
  1643. /**
  1644. * Clamps the rgb values by the min and max values and stores the result into "result"
  1645. * @param min defines minimum clamping value (default is 0)
  1646. * @param max defines maximum clamping value (default is 1)
  1647. * @param result defines color to store the result into
  1648. * @returns the original Color3
  1649. */
  1650. Color3.prototype.clampToRef = function (min, max, result) {
  1651. if (min === void 0) { min = 0; }
  1652. if (max === void 0) { max = 1; }
  1653. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1654. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1655. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1656. return this;
  1657. };
  1658. /**
  1659. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1660. * @param otherColor defines the second operand
  1661. * @returns the new Color3
  1662. */
  1663. Color3.prototype.add = function (otherColor) {
  1664. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1665. };
  1666. /**
  1667. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1668. * @param otherColor defines the second operand
  1669. * @param result defines Color3 object to store the result into
  1670. * @returns the unmodified current Color3
  1671. */
  1672. Color3.prototype.addToRef = function (otherColor, result) {
  1673. result.r = this.r + otherColor.r;
  1674. result.g = this.g + otherColor.g;
  1675. result.b = this.b + otherColor.b;
  1676. return this;
  1677. };
  1678. /**
  1679. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1680. * @param otherColor defines the second operand
  1681. * @returns the new Color3
  1682. */
  1683. Color3.prototype.subtract = function (otherColor) {
  1684. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1685. };
  1686. /**
  1687. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1688. * @param otherColor defines the second operand
  1689. * @param result defines Color3 object to store the result into
  1690. * @returns the unmodified current Color3
  1691. */
  1692. Color3.prototype.subtractToRef = function (otherColor, result) {
  1693. result.r = this.r - otherColor.r;
  1694. result.g = this.g - otherColor.g;
  1695. result.b = this.b - otherColor.b;
  1696. return this;
  1697. };
  1698. /**
  1699. * Copy the current object
  1700. * @returns a new Color3 copied the current one
  1701. */
  1702. Color3.prototype.clone = function () {
  1703. return new Color3(this.r, this.g, this.b);
  1704. };
  1705. /**
  1706. * Copies the rgb values from the source in the current Color3
  1707. * @param source defines the source Color3 object
  1708. * @returns the updated Color3 object
  1709. */
  1710. Color3.prototype.copyFrom = function (source) {
  1711. this.r = source.r;
  1712. this.g = source.g;
  1713. this.b = source.b;
  1714. return this;
  1715. };
  1716. /**
  1717. * Updates the Color3 rgb values from the given floats
  1718. * @param r defines the red component to read from
  1719. * @param g defines the green component to read from
  1720. * @param b defines the blue component to read from
  1721. * @returns the current Color3 object
  1722. */
  1723. Color3.prototype.copyFromFloats = function (r, g, b) {
  1724. this.r = r;
  1725. this.g = g;
  1726. this.b = b;
  1727. return this;
  1728. };
  1729. /**
  1730. * Updates the Color3 rgb values from the given floats
  1731. * @param r defines the red component to read from
  1732. * @param g defines the green component to read from
  1733. * @param b defines the blue component to read from
  1734. * @returns the current Color3 object
  1735. */
  1736. Color3.prototype.set = function (r, g, b) {
  1737. return this.copyFromFloats(r, g, b);
  1738. };
  1739. /**
  1740. * Compute the Color3 hexadecimal code as a string
  1741. * @returns a string containing the hexadecimal representation of the Color3 object
  1742. */
  1743. Color3.prototype.toHexString = function () {
  1744. var intR = (this.r * 255) | 0;
  1745. var intG = (this.g * 255) | 0;
  1746. var intB = (this.b * 255) | 0;
  1747. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1748. };
  1749. /**
  1750. * Computes a new Color3 converted from the current one to linear space
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.prototype.toLinearSpace = function () {
  1754. var convertedColor = new Color3();
  1755. this.toLinearSpaceToRef(convertedColor);
  1756. return convertedColor;
  1757. };
  1758. /**
  1759. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1760. * @param convertedColor defines the Color3 object where to store the linear space version
  1761. * @returns the unmodified Color3
  1762. */
  1763. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1764. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1765. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1766. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1767. return this;
  1768. };
  1769. /**
  1770. * Computes a new Color3 converted from the current one to gamma space
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.prototype.toGammaSpace = function () {
  1774. var convertedColor = new Color3();
  1775. this.toGammaSpaceToRef(convertedColor);
  1776. return convertedColor;
  1777. };
  1778. /**
  1779. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1780. * @param convertedColor defines the Color3 object where to store the gamma space version
  1781. * @returns the unmodified Color3
  1782. */
  1783. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1784. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1785. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1786. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1787. return this;
  1788. };
  1789. // Statics
  1790. /**
  1791. * Creates a new Color3 from the string containing valid hexadecimal values
  1792. * @param hex defines a string containing valid hexadecimal values
  1793. * @returns a new Color3 object
  1794. */
  1795. Color3.FromHexString = function (hex) {
  1796. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1797. return new Color3(0, 0, 0);
  1798. }
  1799. var r = parseInt(hex.substring(1, 3), 16);
  1800. var g = parseInt(hex.substring(3, 5), 16);
  1801. var b = parseInt(hex.substring(5, 7), 16);
  1802. return Color3.FromInts(r, g, b);
  1803. };
  1804. /**
  1805. * Creates a new Vector3 from the starting index of the given array
  1806. * @param array defines the source array
  1807. * @param offset defines an offset in the source array
  1808. * @returns a new Color3 object
  1809. */
  1810. Color3.FromArray = function (array, offset) {
  1811. if (offset === void 0) { offset = 0; }
  1812. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1813. };
  1814. /**
  1815. * Creates a new Color3 from integer values (< 256)
  1816. * @param r defines the red component to read from (value between 0 and 255)
  1817. * @param g defines the green component to read from (value between 0 and 255)
  1818. * @param b defines the blue component to read from (value between 0 and 255)
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.FromInts = function (r, g, b) {
  1822. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1823. };
  1824. /**
  1825. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1826. * @param start defines the start Color3 value
  1827. * @param end defines the end Color3 value
  1828. * @param amount defines the gradient value between start and end
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Lerp = function (start, end, amount) {
  1832. var r = start.r + ((end.r - start.r) * amount);
  1833. var g = start.g + ((end.g - start.g) * amount);
  1834. var b = start.b + ((end.b - start.b) * amount);
  1835. return new Color3(r, g, b);
  1836. };
  1837. /**
  1838. * Returns a Color3 value containing a red color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.Red = function () { return new Color3(1, 0, 0); };
  1842. /**
  1843. * Returns a Color3 value containing a green color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Green = function () { return new Color3(0, 1, 0); };
  1847. /**
  1848. * Returns a Color3 value containing a blue color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1852. /**
  1853. * Returns a Color3 value containing a black color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Black = function () { return new Color3(0, 0, 0); };
  1857. /**
  1858. * Returns a Color3 value containing a white color
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.White = function () { return new Color3(1, 1, 1); };
  1862. /**
  1863. * Returns a Color3 value containing a purple color
  1864. * @returns a new Color3 object
  1865. */
  1866. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1867. /**
  1868. * Returns a Color3 value containing a magenta color
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1872. /**
  1873. * Returns a Color3 value containing a yellow color
  1874. * @returns a new Color3 object
  1875. */
  1876. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1877. /**
  1878. * Returns a Color3 value containing a gray color
  1879. * @returns a new Color3 object
  1880. */
  1881. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1882. /**
  1883. * Returns a Color3 value containing a teal color
  1884. * @returns a new Color3 object
  1885. */
  1886. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1887. /**
  1888. * Returns a Color3 value containing a random color
  1889. * @returns a new Color3 object
  1890. */
  1891. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1892. return Color3;
  1893. }());
  1894. BABYLON.Color3 = Color3;
  1895. /**
  1896. * Class used to hold a RBGA color
  1897. */
  1898. var Color4 = /** @class */ (function () {
  1899. /**
  1900. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1901. * @param r defines the red component (between 0 and 1, default is 0)
  1902. * @param g defines the green component (between 0 and 1, default is 0)
  1903. * @param b defines the blue component (between 0 and 1, default is 0)
  1904. * @param a defines the alpha component (between 0 and 1, default is 1)
  1905. */
  1906. function Color4(
  1907. /**
  1908. * Defines the red component (between 0 and 1, default is 0)
  1909. */
  1910. r,
  1911. /**
  1912. * Defines the green component (between 0 and 1, default is 0)
  1913. */
  1914. g,
  1915. /**
  1916. * Defines the blue component (between 0 and 1, default is 0)
  1917. */
  1918. b,
  1919. /**
  1920. * Defines the alpha component (between 0 and 1, default is 1)
  1921. */
  1922. a) {
  1923. if (r === void 0) { r = 0; }
  1924. if (g === void 0) { g = 0; }
  1925. if (b === void 0) { b = 0; }
  1926. if (a === void 0) { a = 1; }
  1927. this.r = r;
  1928. this.g = g;
  1929. this.b = b;
  1930. this.a = a;
  1931. }
  1932. // Operators
  1933. /**
  1934. * Adds in place the given Color4 values to the current Color4 object
  1935. * @param right defines the second operand
  1936. * @returns the current updated Color4 object
  1937. */
  1938. Color4.prototype.addInPlace = function (right) {
  1939. this.r += right.r;
  1940. this.g += right.g;
  1941. this.b += right.b;
  1942. this.a += right.a;
  1943. return this;
  1944. };
  1945. /**
  1946. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1947. * @returns the new array
  1948. */
  1949. Color4.prototype.asArray = function () {
  1950. var result = new Array();
  1951. this.toArray(result, 0);
  1952. return result;
  1953. };
  1954. /**
  1955. * Stores from the starting index in the given array the Color4 successive values
  1956. * @param array defines the array where to store the r,g,b components
  1957. * @param index defines an optional index in the target array to define where to start storing values
  1958. * @returns the current Color4 object
  1959. */
  1960. Color4.prototype.toArray = function (array, index) {
  1961. if (index === undefined) {
  1962. index = 0;
  1963. }
  1964. array[index] = this.r;
  1965. array[index + 1] = this.g;
  1966. array[index + 2] = this.b;
  1967. array[index + 3] = this.a;
  1968. return this;
  1969. };
  1970. /**
  1971. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1972. * @param right defines the second operand
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.add = function (right) {
  1976. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1977. };
  1978. /**
  1979. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1980. * @param right defines the second operand
  1981. * @returns a new Color4 object
  1982. */
  1983. Color4.prototype.subtract = function (right) {
  1984. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1985. };
  1986. /**
  1987. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1988. * @param right defines the second operand
  1989. * @param result defines the Color4 object where to store the result
  1990. * @returns the current Color4 object
  1991. */
  1992. Color4.prototype.subtractToRef = function (right, result) {
  1993. result.r = this.r - right.r;
  1994. result.g = this.g - right.g;
  1995. result.b = this.b - right.b;
  1996. result.a = this.a - right.a;
  1997. return this;
  1998. };
  1999. /**
  2000. * Creates a new Color4 with the current Color4 values multiplied by scale
  2001. * @param scale defines the scaling factor to apply
  2002. * @returns a new Color4 object
  2003. */
  2004. Color4.prototype.scale = function (scale) {
  2005. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2006. };
  2007. /**
  2008. * Multiplies the current Color4 values by scale and stores the result in "result"
  2009. * @param scale defines the scaling factor to apply
  2010. * @param result defines the Color4 object where to store the result
  2011. * @returns the current unmodified Color4
  2012. */
  2013. Color4.prototype.scaleToRef = function (scale, result) {
  2014. result.r = this.r * scale;
  2015. result.g = this.g * scale;
  2016. result.b = this.b * scale;
  2017. result.a = this.a * scale;
  2018. return this;
  2019. };
  2020. /**
  2021. * Scale the current Color4 values by a factor and add the result to a given Color4
  2022. * @param scale defines the scale factor
  2023. * @param result defines the Color4 object where to store the result
  2024. * @returns the unmodified current Color4
  2025. */
  2026. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2027. result.r += this.r * scale;
  2028. result.g += this.g * scale;
  2029. result.b += this.b * scale;
  2030. result.a += this.a * scale;
  2031. return this;
  2032. };
  2033. /**
  2034. * Clamps the rgb values by the min and max values and stores the result into "result"
  2035. * @param min defines minimum clamping value (default is 0)
  2036. * @param max defines maximum clamping value (default is 1)
  2037. * @param result defines color to store the result into.
  2038. * @returns the cuurent Color4
  2039. */
  2040. Color4.prototype.clampToRef = function (min, max, result) {
  2041. if (min === void 0) { min = 0; }
  2042. if (max === void 0) { max = 1; }
  2043. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2044. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2045. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2046. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2047. return this;
  2048. };
  2049. /**
  2050. * Multipy an Color4 value by another and return a new Color4 object
  2051. * @param color defines the Color4 value to multiply by
  2052. * @returns a new Color4 object
  2053. */
  2054. Color4.prototype.multiply = function (color) {
  2055. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2056. };
  2057. /**
  2058. * Multipy a Color4 value by another and push the result in a reference value
  2059. * @param color defines the Color4 value to multiply by
  2060. * @param result defines the Color4 to fill the result in
  2061. * @returns the result Color4
  2062. */
  2063. Color4.prototype.multiplyToRef = function (color, result) {
  2064. result.r = this.r * color.r;
  2065. result.g = this.g * color.g;
  2066. result.b = this.b * color.b;
  2067. result.a = this.a * color.a;
  2068. return result;
  2069. };
  2070. /**
  2071. * Creates a string with the Color4 current values
  2072. * @returns the string representation of the Color4 object
  2073. */
  2074. Color4.prototype.toString = function () {
  2075. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2076. };
  2077. /**
  2078. * Returns the string "Color4"
  2079. * @returns "Color4"
  2080. */
  2081. Color4.prototype.getClassName = function () {
  2082. return "Color4";
  2083. };
  2084. /**
  2085. * Compute the Color4 hash code
  2086. * @returns an unique number that can be used to hash Color4 objects
  2087. */
  2088. Color4.prototype.getHashCode = function () {
  2089. var hash = this.r || 0;
  2090. hash = (hash * 397) ^ (this.g || 0);
  2091. hash = (hash * 397) ^ (this.b || 0);
  2092. hash = (hash * 397) ^ (this.a || 0);
  2093. return hash;
  2094. };
  2095. /**
  2096. * Creates a new Color4 copied from the current one
  2097. * @returns a new Color4 object
  2098. */
  2099. Color4.prototype.clone = function () {
  2100. return new Color4(this.r, this.g, this.b, this.a);
  2101. };
  2102. /**
  2103. * Copies the given Color4 values into the current one
  2104. * @param source defines the source Color4 object
  2105. * @returns the current updated Color4 object
  2106. */
  2107. Color4.prototype.copyFrom = function (source) {
  2108. this.r = source.r;
  2109. this.g = source.g;
  2110. this.b = source.b;
  2111. this.a = source.a;
  2112. return this;
  2113. };
  2114. /**
  2115. * Copies the given float values into the current one
  2116. * @param r defines the red component to read from
  2117. * @param g defines the green component to read from
  2118. * @param b defines the blue component to read from
  2119. * @param a defines the alpha component to read from
  2120. * @returns the current updated Color4 object
  2121. */
  2122. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2123. this.r = r;
  2124. this.g = g;
  2125. this.b = b;
  2126. this.a = a;
  2127. return this;
  2128. };
  2129. /**
  2130. * Copies the given float values into the current one
  2131. * @param r defines the red component to read from
  2132. * @param g defines the green component to read from
  2133. * @param b defines the blue component to read from
  2134. * @param a defines the alpha component to read from
  2135. * @returns the current updated Color4 object
  2136. */
  2137. Color4.prototype.set = function (r, g, b, a) {
  2138. return this.copyFromFloats(r, g, b, a);
  2139. };
  2140. /**
  2141. * Compute the Color4 hexadecimal code as a string
  2142. * @returns a string containing the hexadecimal representation of the Color4 object
  2143. */
  2144. Color4.prototype.toHexString = function () {
  2145. var intR = (this.r * 255) | 0;
  2146. var intG = (this.g * 255) | 0;
  2147. var intB = (this.b * 255) | 0;
  2148. var intA = (this.a * 255) | 0;
  2149. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2150. };
  2151. /**
  2152. * Computes a new Color4 converted from the current one to linear space
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.prototype.toLinearSpace = function () {
  2156. var convertedColor = new Color4();
  2157. this.toLinearSpaceToRef(convertedColor);
  2158. return convertedColor;
  2159. };
  2160. /**
  2161. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2162. * @param convertedColor defines the Color4 object where to store the linear space version
  2163. * @returns the unmodified Color4
  2164. */
  2165. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2166. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2167. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2168. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2169. convertedColor.a = this.a;
  2170. return this;
  2171. };
  2172. /**
  2173. * Computes a new Color4 converted from the current one to gamma space
  2174. * @returns a new Color4 object
  2175. */
  2176. Color4.prototype.toGammaSpace = function () {
  2177. var convertedColor = new Color4();
  2178. this.toGammaSpaceToRef(convertedColor);
  2179. return convertedColor;
  2180. };
  2181. /**
  2182. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2183. * @param convertedColor defines the Color4 object where to store the gamma space version
  2184. * @returns the unmodified Color4
  2185. */
  2186. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2187. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2188. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2189. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2190. convertedColor.a = this.a;
  2191. return this;
  2192. };
  2193. // Statics
  2194. /**
  2195. * Creates a new Color4 from the string containing valid hexadecimal values
  2196. * @param hex defines a string containing valid hexadecimal values
  2197. * @returns a new Color4 object
  2198. */
  2199. Color4.FromHexString = function (hex) {
  2200. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2201. return new Color4(0.0, 0.0, 0.0, 0.0);
  2202. }
  2203. var r = parseInt(hex.substring(1, 3), 16);
  2204. var g = parseInt(hex.substring(3, 5), 16);
  2205. var b = parseInt(hex.substring(5, 7), 16);
  2206. var a = parseInt(hex.substring(7, 9), 16);
  2207. return Color4.FromInts(r, g, b, a);
  2208. };
  2209. /**
  2210. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2211. * @param left defines the start value
  2212. * @param right defines the end value
  2213. * @param amount defines the gradient factor
  2214. * @returns a new Color4 object
  2215. */
  2216. Color4.Lerp = function (left, right, amount) {
  2217. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2218. Color4.LerpToRef(left, right, amount, result);
  2219. return result;
  2220. };
  2221. /**
  2222. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2223. * @param left defines the start value
  2224. * @param right defines the end value
  2225. * @param amount defines the gradient factor
  2226. * @param result defines the Color4 object where to store data
  2227. */
  2228. Color4.LerpToRef = function (left, right, amount, result) {
  2229. result.r = left.r + (right.r - left.r) * amount;
  2230. result.g = left.g + (right.g - left.g) * amount;
  2231. result.b = left.b + (right.b - left.b) * amount;
  2232. result.a = left.a + (right.a - left.a) * amount;
  2233. };
  2234. /**
  2235. * Creates a new Color4 from the starting index element of the given array
  2236. * @param array defines the source array to read from
  2237. * @param offset defines the offset in the source array
  2238. * @returns a new Color4 object
  2239. */
  2240. Color4.FromArray = function (array, offset) {
  2241. if (offset === void 0) { offset = 0; }
  2242. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2243. };
  2244. /**
  2245. * Creates a new Color3 from integer values (< 256)
  2246. * @param r defines the red component to read from (value between 0 and 255)
  2247. * @param g defines the green component to read from (value between 0 and 255)
  2248. * @param b defines the blue component to read from (value between 0 and 255)
  2249. * @param a defines the alpha component to read from (value between 0 and 255)
  2250. * @returns a new Color3 object
  2251. */
  2252. Color4.FromInts = function (r, g, b, a) {
  2253. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2254. };
  2255. /**
  2256. * Check the content of a given array and convert it to an array containing RGBA data
  2257. * If the original array was already containing count * 4 values then it is returned directly
  2258. * @param colors defines the array to check
  2259. * @param count defines the number of RGBA data to expect
  2260. * @returns an array containing count * 4 values (RGBA)
  2261. */
  2262. Color4.CheckColors4 = function (colors, count) {
  2263. // Check if color3 was used
  2264. if (colors.length === count * 3) {
  2265. var colors4 = [];
  2266. for (var index = 0; index < colors.length; index += 3) {
  2267. var newIndex = (index / 3) * 4;
  2268. colors4[newIndex] = colors[index];
  2269. colors4[newIndex + 1] = colors[index + 1];
  2270. colors4[newIndex + 2] = colors[index + 2];
  2271. colors4[newIndex + 3] = 1.0;
  2272. }
  2273. return colors4;
  2274. }
  2275. return colors;
  2276. };
  2277. return Color4;
  2278. }());
  2279. BABYLON.Color4 = Color4;
  2280. /**
  2281. * Class representing a vector containing 2 coordinates
  2282. */
  2283. var Vector2 = /** @class */ (function () {
  2284. /**
  2285. * Creates a new Vector2 from the given x and y coordinates
  2286. * @param x defines the first coordinate
  2287. * @param y defines the second coordinate
  2288. */
  2289. function Vector2(
  2290. /** defines the first coordinate */
  2291. x,
  2292. /** defines the second coordinate */
  2293. y) {
  2294. this.x = x;
  2295. this.y = y;
  2296. }
  2297. /**
  2298. * Gets a string with the Vector2 coordinates
  2299. * @returns a string with the Vector2 coordinates
  2300. */
  2301. Vector2.prototype.toString = function () {
  2302. return "{X: " + this.x + " Y:" + this.y + "}";
  2303. };
  2304. /**
  2305. * Gets class name
  2306. * @returns the string "Vector2"
  2307. */
  2308. Vector2.prototype.getClassName = function () {
  2309. return "Vector2";
  2310. };
  2311. /**
  2312. * Gets current vector hash code
  2313. * @returns the Vector2 hash code as a number
  2314. */
  2315. Vector2.prototype.getHashCode = function () {
  2316. var hash = this.x || 0;
  2317. hash = (hash * 397) ^ (this.y || 0);
  2318. return hash;
  2319. };
  2320. // Operators
  2321. /**
  2322. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2323. * @param array defines the source array
  2324. * @param index defines the offset in source array
  2325. * @returns the current Vector2
  2326. */
  2327. Vector2.prototype.toArray = function (array, index) {
  2328. if (index === void 0) { index = 0; }
  2329. array[index] = this.x;
  2330. array[index + 1] = this.y;
  2331. return this;
  2332. };
  2333. /**
  2334. * Copy the current vector to an array
  2335. * @returns a new array with 2 elements: the Vector2 coordinates.
  2336. */
  2337. Vector2.prototype.asArray = function () {
  2338. var result = new Array();
  2339. this.toArray(result, 0);
  2340. return result;
  2341. };
  2342. /**
  2343. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2344. * @param source defines the source Vector2
  2345. * @returns the current updated Vector2
  2346. */
  2347. Vector2.prototype.copyFrom = function (source) {
  2348. this.x = source.x;
  2349. this.y = source.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Sets the Vector2 coordinates with the given floats
  2354. * @param x defines the first coordinate
  2355. * @param y defines the second coordinate
  2356. * @returns the current updated Vector2
  2357. */
  2358. Vector2.prototype.copyFromFloats = function (x, y) {
  2359. this.x = x;
  2360. this.y = y;
  2361. return this;
  2362. };
  2363. /**
  2364. * Sets the Vector2 coordinates with the given floats
  2365. * @param x defines the first coordinate
  2366. * @param y defines the second coordinate
  2367. * @returns the current updated Vector2
  2368. */
  2369. Vector2.prototype.set = function (x, y) {
  2370. return this.copyFromFloats(x, y);
  2371. };
  2372. /**
  2373. * Add another vector with the current one
  2374. * @param otherVector defines the other vector
  2375. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2376. */
  2377. Vector2.prototype.add = function (otherVector) {
  2378. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2379. };
  2380. /**
  2381. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2382. * @param otherVector defines the other vector
  2383. * @param result defines the target vector
  2384. * @returns the unmodified current Vector2
  2385. */
  2386. Vector2.prototype.addToRef = function (otherVector, result) {
  2387. result.x = this.x + otherVector.x;
  2388. result.y = this.y + otherVector.y;
  2389. return this;
  2390. };
  2391. /**
  2392. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2393. * @param otherVector defines the other vector
  2394. * @returns the current updated Vector2
  2395. */
  2396. Vector2.prototype.addInPlace = function (otherVector) {
  2397. this.x += otherVector.x;
  2398. this.y += otherVector.y;
  2399. return this;
  2400. };
  2401. /**
  2402. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2403. * @param otherVector defines the other vector
  2404. * @returns a new Vector2
  2405. */
  2406. Vector2.prototype.addVector3 = function (otherVector) {
  2407. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2408. };
  2409. /**
  2410. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2411. * @param otherVector defines the other vector
  2412. * @returns a new Vector2
  2413. */
  2414. Vector2.prototype.subtract = function (otherVector) {
  2415. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2416. };
  2417. /**
  2418. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2419. * @param otherVector defines the other vector
  2420. * @param result defines the target vector
  2421. * @returns the unmodified current Vector2
  2422. */
  2423. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2424. result.x = this.x - otherVector.x;
  2425. result.y = this.y - otherVector.y;
  2426. return this;
  2427. };
  2428. /**
  2429. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2430. * @param otherVector defines the other vector
  2431. * @returns the current updated Vector2
  2432. */
  2433. Vector2.prototype.subtractInPlace = function (otherVector) {
  2434. this.x -= otherVector.x;
  2435. this.y -= otherVector.y;
  2436. return this;
  2437. };
  2438. /**
  2439. * Multiplies in place the current Vector2 coordinates by the given ones
  2440. * @param otherVector defines the other vector
  2441. * @returns the current updated Vector2
  2442. */
  2443. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2444. this.x *= otherVector.x;
  2445. this.y *= otherVector.y;
  2446. return this;
  2447. };
  2448. /**
  2449. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2450. * @param otherVector defines the other vector
  2451. * @returns a new Vector2
  2452. */
  2453. Vector2.prototype.multiply = function (otherVector) {
  2454. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2455. };
  2456. /**
  2457. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2458. * @param otherVector defines the other vector
  2459. * @param result defines the target vector
  2460. * @returns the unmodified current Vector2
  2461. */
  2462. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2463. result.x = this.x * otherVector.x;
  2464. result.y = this.y * otherVector.y;
  2465. return this;
  2466. };
  2467. /**
  2468. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2469. * @param x defines the first coordinate
  2470. * @param y defines the second coordinate
  2471. * @returns a new Vector2
  2472. */
  2473. Vector2.prototype.multiplyByFloats = function (x, y) {
  2474. return new Vector2(this.x * x, this.y * y);
  2475. };
  2476. /**
  2477. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2478. * @param otherVector defines the other vector
  2479. * @returns a new Vector2
  2480. */
  2481. Vector2.prototype.divide = function (otherVector) {
  2482. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2483. };
  2484. /**
  2485. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2486. * @param otherVector defines the other vector
  2487. * @param result defines the target vector
  2488. * @returns the unmodified current Vector2
  2489. */
  2490. Vector2.prototype.divideToRef = function (otherVector, result) {
  2491. result.x = this.x / otherVector.x;
  2492. result.y = this.y / otherVector.y;
  2493. return this;
  2494. };
  2495. /**
  2496. * Divides the current Vector3 coordinates by the given ones
  2497. * @param otherVector defines the other vector
  2498. * @returns the current updated Vector2
  2499. */
  2500. Vector2.prototype.divideInPlace = function (otherVector) {
  2501. return this.divideToRef(otherVector, this);
  2502. };
  2503. /**
  2504. * Gets a new Vector2 with current Vector2 negated coordinates
  2505. * @returns a new Vector2
  2506. */
  2507. Vector2.prototype.negate = function () {
  2508. return new Vector2(-this.x, -this.y);
  2509. };
  2510. /**
  2511. * Multiply the Vector2 coordinates by scale
  2512. * @param scale defines the scaling factor
  2513. * @returns the current updated Vector2
  2514. */
  2515. Vector2.prototype.scaleInPlace = function (scale) {
  2516. this.x *= scale;
  2517. this.y *= scale;
  2518. return this;
  2519. };
  2520. /**
  2521. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2522. * @param scale defines the scaling factor
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.scale = function (scale) {
  2526. var result = new Vector2(0, 0);
  2527. this.scaleToRef(scale, result);
  2528. return result;
  2529. };
  2530. /**
  2531. * Scale the current Vector2 values by a factor to a given Vector2
  2532. * @param scale defines the scale factor
  2533. * @param result defines the Vector2 object where to store the result
  2534. * @returns the unmodified current Vector2
  2535. */
  2536. Vector2.prototype.scaleToRef = function (scale, result) {
  2537. result.x = this.x * scale;
  2538. result.y = this.y * scale;
  2539. return this;
  2540. };
  2541. /**
  2542. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2543. * @param scale defines the scale factor
  2544. * @param result defines the Vector2 object where to store the result
  2545. * @returns the unmodified current Vector2
  2546. */
  2547. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2548. result.x += this.x * scale;
  2549. result.y += this.y * scale;
  2550. return this;
  2551. };
  2552. /**
  2553. * Gets a boolean if two vectors are equals
  2554. * @param otherVector defines the other vector
  2555. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2556. */
  2557. Vector2.prototype.equals = function (otherVector) {
  2558. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2559. };
  2560. /**
  2561. * Gets a boolean if two vectors are equals (using an epsilon value)
  2562. * @param otherVector defines the other vector
  2563. * @param epsilon defines the minimal distance to consider equality
  2564. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2565. */
  2566. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2567. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2568. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2569. };
  2570. // Properties
  2571. /**
  2572. * Gets the length of the vector
  2573. * @returns the vector length (float)
  2574. */
  2575. Vector2.prototype.length = function () {
  2576. return Math.sqrt(this.x * this.x + this.y * this.y);
  2577. };
  2578. /**
  2579. * Gets the vector squared length
  2580. * @returns the vector squared length (float)
  2581. */
  2582. Vector2.prototype.lengthSquared = function () {
  2583. return (this.x * this.x + this.y * this.y);
  2584. };
  2585. // Methods
  2586. /**
  2587. * Normalize the vector
  2588. * @returns the current updated Vector2
  2589. */
  2590. Vector2.prototype.normalize = function () {
  2591. var len = this.length();
  2592. if (len === 0)
  2593. return this;
  2594. var num = 1.0 / len;
  2595. this.x *= num;
  2596. this.y *= num;
  2597. return this;
  2598. };
  2599. /**
  2600. * Gets a new Vector2 copied from the Vector2
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.prototype.clone = function () {
  2604. return new Vector2(this.x, this.y);
  2605. };
  2606. // Statics
  2607. /**
  2608. * Gets a new Vector2(0, 0)
  2609. * @returns a new Vector2
  2610. */
  2611. Vector2.Zero = function () {
  2612. return new Vector2(0, 0);
  2613. };
  2614. /**
  2615. * Gets a new Vector2(1, 1)
  2616. * @returns a new Vector2
  2617. */
  2618. Vector2.One = function () {
  2619. return new Vector2(1, 1);
  2620. };
  2621. /**
  2622. * Gets a new Vector2 set from the given index element of the given array
  2623. * @param array defines the data source
  2624. * @param offset defines the offset in the data source
  2625. * @returns a new Vector2
  2626. */
  2627. Vector2.FromArray = function (array, offset) {
  2628. if (offset === void 0) { offset = 0; }
  2629. return new Vector2(array[offset], array[offset + 1]);
  2630. };
  2631. /**
  2632. * Sets "result" from the given index element of the given array
  2633. * @param array defines the data source
  2634. * @param offset defines the offset in the data source
  2635. * @param result defines the target vector
  2636. */
  2637. Vector2.FromArrayToRef = function (array, offset, result) {
  2638. result.x = array[offset];
  2639. result.y = array[offset + 1];
  2640. };
  2641. /**
  2642. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2643. * @param value1 defines 1st point of control
  2644. * @param value2 defines 2nd point of control
  2645. * @param value3 defines 3rd point of control
  2646. * @param value4 defines 4th point of control
  2647. * @param amount defines the interpolation factor
  2648. * @returns a new Vector2
  2649. */
  2650. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2651. var squared = amount * amount;
  2652. var cubed = amount * squared;
  2653. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2654. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2655. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2656. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2657. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2658. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2659. return new Vector2(x, y);
  2660. };
  2661. /**
  2662. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2663. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2664. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2665. * @param value defines the value to clamp
  2666. * @param min defines the lower limit
  2667. * @param max defines the upper limit
  2668. * @returns a new Vector2
  2669. */
  2670. Vector2.Clamp = function (value, min, max) {
  2671. var x = value.x;
  2672. x = (x > max.x) ? max.x : x;
  2673. x = (x < min.x) ? min.x : x;
  2674. var y = value.y;
  2675. y = (y > max.y) ? max.y : y;
  2676. y = (y < min.y) ? min.y : y;
  2677. return new Vector2(x, y);
  2678. };
  2679. /**
  2680. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2681. * @param value1 defines the 1st control point
  2682. * @param tangent1 defines the outgoing tangent
  2683. * @param value2 defines the 2nd control point
  2684. * @param tangent2 defines the incoming tangent
  2685. * @param amount defines the interpolation factor
  2686. * @returns a new Vector2
  2687. */
  2688. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2689. var squared = amount * amount;
  2690. var cubed = amount * squared;
  2691. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2692. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2693. var part3 = (cubed - (2.0 * squared)) + amount;
  2694. var part4 = cubed - squared;
  2695. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2696. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2697. return new Vector2(x, y);
  2698. };
  2699. /**
  2700. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2701. * @param start defines the start vector
  2702. * @param end defines the end vector
  2703. * @param amount defines the interpolation factor
  2704. * @returns a new Vector2
  2705. */
  2706. Vector2.Lerp = function (start, end, amount) {
  2707. var x = start.x + ((end.x - start.x) * amount);
  2708. var y = start.y + ((end.y - start.y) * amount);
  2709. return new Vector2(x, y);
  2710. };
  2711. /**
  2712. * Gets the dot product of the vector "left" and the vector "right"
  2713. * @param left defines first vector
  2714. * @param right defines second vector
  2715. * @returns the dot product (float)
  2716. */
  2717. Vector2.Dot = function (left, right) {
  2718. return left.x * right.x + left.y * right.y;
  2719. };
  2720. /**
  2721. * Returns a new Vector2 equal to the normalized given vector
  2722. * @param vector defines the vector to normalize
  2723. * @returns a new Vector2
  2724. */
  2725. Vector2.Normalize = function (vector) {
  2726. var newVector = vector.clone();
  2727. newVector.normalize();
  2728. return newVector;
  2729. };
  2730. /**
  2731. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2732. * @param left defines 1st vector
  2733. * @param right defines 2nd vector
  2734. * @returns a new Vector2
  2735. */
  2736. Vector2.Minimize = function (left, right) {
  2737. var x = (left.x < right.x) ? left.x : right.x;
  2738. var y = (left.y < right.y) ? left.y : right.y;
  2739. return new Vector2(x, y);
  2740. };
  2741. /**
  2742. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2743. * @param left defines 1st vector
  2744. * @param right defines 2nd vector
  2745. * @returns a new Vector2
  2746. */
  2747. Vector2.Maximize = function (left, right) {
  2748. var x = (left.x > right.x) ? left.x : right.x;
  2749. var y = (left.y > right.y) ? left.y : right.y;
  2750. return new Vector2(x, y);
  2751. };
  2752. /**
  2753. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2754. * @param vector defines the vector to transform
  2755. * @param transformation defines the matrix to apply
  2756. * @returns a new Vector2
  2757. */
  2758. Vector2.Transform = function (vector, transformation) {
  2759. var r = Vector2.Zero();
  2760. Vector2.TransformToRef(vector, transformation, r);
  2761. return r;
  2762. };
  2763. /**
  2764. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2765. * @param vector defines the vector to transform
  2766. * @param transformation defines the matrix to apply
  2767. * @param result defines the target vector
  2768. */
  2769. Vector2.TransformToRef = function (vector, transformation, result) {
  2770. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2771. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2772. result.x = x;
  2773. result.y = y;
  2774. };
  2775. /**
  2776. * Determines if a given vector is included in a triangle
  2777. * @param p defines the vector to test
  2778. * @param p0 defines 1st triangle point
  2779. * @param p1 defines 2nd triangle point
  2780. * @param p2 defines 3rd triangle point
  2781. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2782. */
  2783. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2784. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2785. var sign = a < 0 ? -1 : 1;
  2786. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2787. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2788. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2789. };
  2790. /**
  2791. * Gets the distance between the vectors "value1" and "value2"
  2792. * @param value1 defines first vector
  2793. * @param value2 defines second vector
  2794. * @returns the distance between vectors
  2795. */
  2796. Vector2.Distance = function (value1, value2) {
  2797. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2798. };
  2799. /**
  2800. * Returns the squared distance between the vectors "value1" and "value2"
  2801. * @param value1 defines first vector
  2802. * @param value2 defines second vector
  2803. * @returns the squared distance between vectors
  2804. */
  2805. Vector2.DistanceSquared = function (value1, value2) {
  2806. var x = value1.x - value2.x;
  2807. var y = value1.y - value2.y;
  2808. return (x * x) + (y * y);
  2809. };
  2810. /**
  2811. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2812. * @param value1 defines first vector
  2813. * @param value2 defines second vector
  2814. * @returns a new Vector2
  2815. */
  2816. Vector2.Center = function (value1, value2) {
  2817. var center = value1.add(value2);
  2818. center.scaleInPlace(0.5);
  2819. return center;
  2820. };
  2821. /**
  2822. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2823. * @param p defines the middle point
  2824. * @param segA defines one point of the segment
  2825. * @param segB defines the other point of the segment
  2826. * @returns the shortest distance
  2827. */
  2828. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2829. var l2 = Vector2.DistanceSquared(segA, segB);
  2830. if (l2 === 0.0) {
  2831. return Vector2.Distance(p, segA);
  2832. }
  2833. var v = segB.subtract(segA);
  2834. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2835. var proj = segA.add(v.multiplyByFloats(t, t));
  2836. return Vector2.Distance(p, proj);
  2837. };
  2838. return Vector2;
  2839. }());
  2840. BABYLON.Vector2 = Vector2;
  2841. /**
  2842. * Classed used to store (x,y,z) vector representation
  2843. * A Vector3 is the main object used in 3D geometry
  2844. * It can represent etiher the coordinates of a point the space, either a direction
  2845. * Reminder: Babylon.js uses a left handed forward facing system
  2846. */
  2847. var Vector3 = /** @class */ (function () {
  2848. /**
  2849. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2850. * @param x defines the first coordinates (on X axis)
  2851. * @param y defines the second coordinates (on Y axis)
  2852. * @param z defines the third coordinates (on Z axis)
  2853. */
  2854. function Vector3(
  2855. /**
  2856. * Defines the first coordinates (on X axis)
  2857. */
  2858. x,
  2859. /**
  2860. * Defines the second coordinates (on Y axis)
  2861. */
  2862. y,
  2863. /**
  2864. * Defines the third coordinates (on Z axis)
  2865. */
  2866. z) {
  2867. this.x = x;
  2868. this.y = y;
  2869. this.z = z;
  2870. }
  2871. /**
  2872. * Creates a string representation of the Vector3
  2873. * @returns a string with the Vector3 coordinates.
  2874. */
  2875. Vector3.prototype.toString = function () {
  2876. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2877. };
  2878. /**
  2879. * Gets the class name
  2880. * @returns the string "Vector3"
  2881. */
  2882. Vector3.prototype.getClassName = function () {
  2883. return "Vector3";
  2884. };
  2885. /**
  2886. * Creates the Vector3 hash code
  2887. * @returns a number which tends to be unique between Vector3 instances
  2888. */
  2889. Vector3.prototype.getHashCode = function () {
  2890. var hash = this.x || 0;
  2891. hash = (hash * 397) ^ (this.y || 0);
  2892. hash = (hash * 397) ^ (this.z || 0);
  2893. return hash;
  2894. };
  2895. // Operators
  2896. /**
  2897. * Creates an array containing three elements : the coordinates of the Vector3
  2898. * @returns a new array of numbers
  2899. */
  2900. Vector3.prototype.asArray = function () {
  2901. var result = [];
  2902. this.toArray(result, 0);
  2903. return result;
  2904. };
  2905. /**
  2906. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2907. * @param array defines the destination array
  2908. * @param index defines the offset in the destination array
  2909. * @returns the current Vector3
  2910. */
  2911. Vector3.prototype.toArray = function (array, index) {
  2912. if (index === void 0) { index = 0; }
  2913. array[index] = this.x;
  2914. array[index + 1] = this.y;
  2915. array[index + 2] = this.z;
  2916. return this;
  2917. };
  2918. /**
  2919. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2920. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2921. */
  2922. Vector3.prototype.toQuaternion = function () {
  2923. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2924. };
  2925. /**
  2926. * Adds the given vector to the current Vector3
  2927. * @param otherVector defines the second operand
  2928. * @returns the current updated Vector3
  2929. */
  2930. Vector3.prototype.addInPlace = function (otherVector) {
  2931. this.x += otherVector.x;
  2932. this.y += otherVector.y;
  2933. this.z += otherVector.z;
  2934. return this;
  2935. };
  2936. /**
  2937. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2938. * @param otherVector defines the second operand
  2939. * @returns the resulting Vector3
  2940. */
  2941. Vector3.prototype.add = function (otherVector) {
  2942. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2943. };
  2944. /**
  2945. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2946. * @param otherVector defines the second operand
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the current Vector3
  2949. */
  2950. Vector3.prototype.addToRef = function (otherVector, result) {
  2951. result.x = this.x + otherVector.x;
  2952. result.y = this.y + otherVector.y;
  2953. result.z = this.z + otherVector.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Subtract the given vector from the current Vector3
  2958. * @param otherVector defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.subtractInPlace = function (otherVector) {
  2962. this.x -= otherVector.x;
  2963. this.y -= otherVector.y;
  2964. this.z -= otherVector.z;
  2965. return this;
  2966. };
  2967. /**
  2968. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2969. * @param otherVector defines the second operand
  2970. * @returns the resulting Vector3
  2971. */
  2972. Vector3.prototype.subtract = function (otherVector) {
  2973. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2974. };
  2975. /**
  2976. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2977. * @param otherVector defines the second operand
  2978. * @param result defines the Vector3 object where to store the result
  2979. * @returns the current Vector3
  2980. */
  2981. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2982. result.x = this.x - otherVector.x;
  2983. result.y = this.y - otherVector.y;
  2984. result.z = this.z - otherVector.z;
  2985. return this;
  2986. };
  2987. /**
  2988. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2989. * @param x defines the x coordinate of the operand
  2990. * @param y defines the y coordinate of the operand
  2991. * @param z defines the z coordinate of the operand
  2992. * @returns the resulting Vector3
  2993. */
  2994. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2995. return new Vector3(this.x - x, this.y - y, this.z - z);
  2996. };
  2997. /**
  2998. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2999. * @param x defines the x coordinate of the operand
  3000. * @param y defines the y coordinate of the operand
  3001. * @param z defines the z coordinate of the operand
  3002. * @param result defines the Vector3 object where to store the result
  3003. * @returns the current Vector3
  3004. */
  3005. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3006. result.x = this.x - x;
  3007. result.y = this.y - y;
  3008. result.z = this.z - z;
  3009. return this;
  3010. };
  3011. /**
  3012. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3013. * @returns a new Vector3
  3014. */
  3015. Vector3.prototype.negate = function () {
  3016. return new Vector3(-this.x, -this.y, -this.z);
  3017. };
  3018. /**
  3019. * Multiplies the Vector3 coordinates by the float "scale"
  3020. * @param scale defines the multiplier factor
  3021. * @returns the current updated Vector3
  3022. */
  3023. Vector3.prototype.scaleInPlace = function (scale) {
  3024. this.x *= scale;
  3025. this.y *= scale;
  3026. this.z *= scale;
  3027. return this;
  3028. };
  3029. /**
  3030. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3031. * @param scale defines the multiplier factor
  3032. * @returns a new Vector3
  3033. */
  3034. Vector3.prototype.scale = function (scale) {
  3035. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3036. };
  3037. /**
  3038. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3039. * @param scale defines the multiplier factor
  3040. * @param result defines the Vector3 object where to store the result
  3041. * @returns the current Vector3
  3042. */
  3043. Vector3.prototype.scaleToRef = function (scale, result) {
  3044. result.x = this.x * scale;
  3045. result.y = this.y * scale;
  3046. result.z = this.z * scale;
  3047. return this;
  3048. };
  3049. /**
  3050. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3051. * @param scale defines the scale factor
  3052. * @param result defines the Vector3 object where to store the result
  3053. * @returns the unmodified current Vector3
  3054. */
  3055. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3056. result.x += this.x * scale;
  3057. result.y += this.y * scale;
  3058. result.z += this.z * scale;
  3059. return this;
  3060. };
  3061. /**
  3062. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3063. * @param otherVector defines the second operand
  3064. * @returns true if both vectors are equals
  3065. */
  3066. Vector3.prototype.equals = function (otherVector) {
  3067. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3068. };
  3069. /**
  3070. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3071. * @param otherVector defines the second operand
  3072. * @param epsilon defines the minimal distance to define values as equals
  3073. * @returns true if both vectors are distant less than epsilon
  3074. */
  3075. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3076. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3077. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3078. };
  3079. /**
  3080. * Returns true if the current Vector3 coordinates equals the given floats
  3081. * @param x defines the x coordinate of the operand
  3082. * @param y defines the y coordinate of the operand
  3083. * @param z defines the z coordinate of the operand
  3084. * @returns true if both vectors are equals
  3085. */
  3086. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3087. return this.x === x && this.y === y && this.z === z;
  3088. };
  3089. /**
  3090. * Multiplies the current Vector3 coordinates by the given ones
  3091. * @param otherVector defines the second operand
  3092. * @returns the current updated Vector3
  3093. */
  3094. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3095. this.x *= otherVector.x;
  3096. this.y *= otherVector.y;
  3097. this.z *= otherVector.z;
  3098. return this;
  3099. };
  3100. /**
  3101. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3102. * @param otherVector defines the second operand
  3103. * @returns the new Vector3
  3104. */
  3105. Vector3.prototype.multiply = function (otherVector) {
  3106. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3107. };
  3108. /**
  3109. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3110. * @param otherVector defines the second operand
  3111. * @param result defines the Vector3 object where to store the result
  3112. * @returns the current Vector3
  3113. */
  3114. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3115. result.x = this.x * otherVector.x;
  3116. result.y = this.y * otherVector.y;
  3117. result.z = this.z * otherVector.z;
  3118. return this;
  3119. };
  3120. /**
  3121. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3122. * @param x defines the x coordinate of the operand
  3123. * @param y defines the y coordinate of the operand
  3124. * @param z defines the z coordinate of the operand
  3125. * @returns the new Vector3
  3126. */
  3127. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3128. return new Vector3(this.x * x, this.y * y, this.z * z);
  3129. };
  3130. /**
  3131. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3132. * @param otherVector defines the second operand
  3133. * @returns the new Vector3
  3134. */
  3135. Vector3.prototype.divide = function (otherVector) {
  3136. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3137. };
  3138. /**
  3139. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3140. * @param otherVector defines the second operand
  3141. * @param result defines the Vector3 object where to store the result
  3142. * @returns the current Vector3
  3143. */
  3144. Vector3.prototype.divideToRef = function (otherVector, result) {
  3145. result.x = this.x / otherVector.x;
  3146. result.y = this.y / otherVector.y;
  3147. result.z = this.z / otherVector.z;
  3148. return this;
  3149. };
  3150. /**
  3151. * Divides the current Vector3 coordinates by the given ones.
  3152. * @param otherVector defines the second operand
  3153. * @returns the current updated Vector3
  3154. */
  3155. Vector3.prototype.divideInPlace = function (otherVector) {
  3156. return this.divideToRef(otherVector, this);
  3157. };
  3158. /**
  3159. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3160. * @param other defines the second operand
  3161. * @returns the current updated Vector3
  3162. */
  3163. Vector3.prototype.minimizeInPlace = function (other) {
  3164. if (other.x < this.x)
  3165. this.x = other.x;
  3166. if (other.y < this.y)
  3167. this.y = other.y;
  3168. if (other.z < this.z)
  3169. this.z = other.z;
  3170. return this;
  3171. };
  3172. /**
  3173. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3174. * @param other defines the second operand
  3175. * @returns the current updated Vector3
  3176. */
  3177. Vector3.prototype.maximizeInPlace = function (other) {
  3178. if (other.x > this.x)
  3179. this.x = other.x;
  3180. if (other.y > this.y)
  3181. this.y = other.y;
  3182. if (other.z > this.z)
  3183. this.z = other.z;
  3184. return this;
  3185. };
  3186. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3187. /**
  3188. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3189. */
  3190. get: function () {
  3191. var absX = Math.abs(this.x);
  3192. var absY = Math.abs(this.y);
  3193. if (absX !== absY) {
  3194. return true;
  3195. }
  3196. var absZ = Math.abs(this.z);
  3197. if (absX !== absZ) {
  3198. return true;
  3199. }
  3200. if (absY !== absZ) {
  3201. return true;
  3202. }
  3203. return false;
  3204. },
  3205. enumerable: true,
  3206. configurable: true
  3207. });
  3208. // Properties
  3209. /**
  3210. * Gets the length of the Vector3
  3211. * @returns the length of the Vecto3
  3212. */
  3213. Vector3.prototype.length = function () {
  3214. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3215. };
  3216. /**
  3217. * Gets the squared length of the Vector3
  3218. * @returns squared length of the Vector3
  3219. */
  3220. Vector3.prototype.lengthSquared = function () {
  3221. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3222. };
  3223. /**
  3224. * Normalize the current Vector3.
  3225. * Please note that this is an in place operation.
  3226. * @returns the current updated Vector3
  3227. */
  3228. Vector3.prototype.normalize = function () {
  3229. var len = this.length();
  3230. if (len === 0 || len === 1.0)
  3231. return this;
  3232. var num = 1.0 / len;
  3233. this.x *= num;
  3234. this.y *= num;
  3235. this.z *= num;
  3236. return this;
  3237. };
  3238. /**
  3239. * Normalize the current Vector3 to a new vector
  3240. * @returns the new Vector3
  3241. */
  3242. Vector3.prototype.normalizeToNew = function () {
  3243. var normalized = new Vector3(0, 0, 0);
  3244. this.normalizeToRef(normalized);
  3245. return normalized;
  3246. };
  3247. /**
  3248. * Normalize the current Vector3 to the reference
  3249. * @param reference define the Vector3 to update
  3250. * @returns the updated Vector3
  3251. */
  3252. Vector3.prototype.normalizeToRef = function (reference) {
  3253. var len = this.length();
  3254. if (len === 0 || len === 1.0) {
  3255. reference.set(this.x, this.y, this.z);
  3256. return reference;
  3257. }
  3258. var scale = 1.0 / len;
  3259. this.scaleToRef(scale, reference);
  3260. return reference;
  3261. };
  3262. /**
  3263. * Creates a new Vector3 copied from the current Vector3
  3264. * @returns the new Vector3
  3265. */
  3266. Vector3.prototype.clone = function () {
  3267. return new Vector3(this.x, this.y, this.z);
  3268. };
  3269. /**
  3270. * Copies the given vector coordinates to the current Vector3 ones
  3271. * @param source defines the source Vector3
  3272. * @returns the current updated Vector3
  3273. */
  3274. Vector3.prototype.copyFrom = function (source) {
  3275. this.x = source.x;
  3276. this.y = source.y;
  3277. this.z = source.z;
  3278. return this;
  3279. };
  3280. /**
  3281. * Copies the given floats to the current Vector3 coordinates
  3282. * @param x defines the x coordinate of the operand
  3283. * @param y defines the y coordinate of the operand
  3284. * @param z defines the z coordinate of the operand
  3285. * @returns the current updated Vector3
  3286. */
  3287. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3288. this.x = x;
  3289. this.y = y;
  3290. this.z = z;
  3291. return this;
  3292. };
  3293. /**
  3294. * Copies the given floats to the current Vector3 coordinates
  3295. * @param x defines the x coordinate of the operand
  3296. * @param y defines the y coordinate of the operand
  3297. * @param z defines the z coordinate of the operand
  3298. * @returns the current updated Vector3
  3299. */
  3300. Vector3.prototype.set = function (x, y, z) {
  3301. return this.copyFromFloats(x, y, z);
  3302. };
  3303. // Statics
  3304. /**
  3305. * Get the clip factor between two vectors
  3306. * @param vector0 defines the first operand
  3307. * @param vector1 defines the second operand
  3308. * @param axis defines the axis to use
  3309. * @param size defines the size along the axis
  3310. * @returns the clip factor
  3311. */
  3312. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3313. var d0 = Vector3.Dot(vector0, axis) - size;
  3314. var d1 = Vector3.Dot(vector1, axis) - size;
  3315. var s = d0 / (d0 - d1);
  3316. return s;
  3317. };
  3318. /**
  3319. * Get angle between two vectors
  3320. * @param vector0 angle between vector0 and vector1
  3321. * @param vector1 angle between vector0 and vector1
  3322. * @param normal direction of the normal
  3323. * @return the angle between vector0 and vector1
  3324. */
  3325. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3326. var v0 = vector0.clone().normalize();
  3327. var v1 = vector1.clone().normalize();
  3328. var dot = Vector3.Dot(v0, v1);
  3329. var n = Vector3.Cross(v0, v1);
  3330. if (Vector3.Dot(n, normal) > 0) {
  3331. return Math.acos(dot);
  3332. }
  3333. return -Math.acos(dot);
  3334. };
  3335. /**
  3336. * Returns a new Vector3 set from the index "offset" of the given array
  3337. * @param array defines the source array
  3338. * @param offset defines the offset in the source array
  3339. * @returns the new Vector3
  3340. */
  3341. Vector3.FromArray = function (array, offset) {
  3342. if (!offset) {
  3343. offset = 0;
  3344. }
  3345. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3349. * This function is deprecated. Use FromArray instead
  3350. * @param array defines the source array
  3351. * @param offset defines the offset in the source array
  3352. * @returns the new Vector3
  3353. */
  3354. Vector3.FromFloatArray = function (array, offset) {
  3355. return Vector3.FromArray(array, offset);
  3356. };
  3357. /**
  3358. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3359. * @param array defines the source array
  3360. * @param offset defines the offset in the source array
  3361. * @param result defines the Vector3 where to store the result
  3362. */
  3363. Vector3.FromArrayToRef = function (array, offset, result) {
  3364. result.x = array[offset];
  3365. result.y = array[offset + 1];
  3366. result.z = array[offset + 2];
  3367. };
  3368. /**
  3369. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3370. * This function is deprecated. Use FromArrayToRef instead.
  3371. * @param array defines the source array
  3372. * @param offset defines the offset in the source array
  3373. * @param result defines the Vector3 where to store the result
  3374. */
  3375. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3376. return Vector3.FromArrayToRef(array, offset, result);
  3377. };
  3378. /**
  3379. * Sets the given vector "result" with the given floats.
  3380. * @param x defines the x coordinate of the source
  3381. * @param y defines the y coordinate of the source
  3382. * @param z defines the z coordinate of the source
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3386. result.x = x;
  3387. result.y = y;
  3388. result.z = z;
  3389. };
  3390. /**
  3391. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3392. * @returns a new empty Vector3
  3393. */
  3394. Vector3.Zero = function () {
  3395. return new Vector3(0.0, 0.0, 0.0);
  3396. };
  3397. /**
  3398. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3399. * @returns a new unit Vector3
  3400. */
  3401. Vector3.One = function () {
  3402. return new Vector3(1.0, 1.0, 1.0);
  3403. };
  3404. /**
  3405. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3406. * @returns a new up Vector3
  3407. */
  3408. Vector3.Up = function () {
  3409. return new Vector3(0.0, 1.0, 0.0);
  3410. };
  3411. /**
  3412. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3413. * @returns a new forward Vector3
  3414. */
  3415. Vector3.Forward = function () {
  3416. return new Vector3(0.0, 0.0, 1.0);
  3417. };
  3418. /**
  3419. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3420. * @returns a new right Vector3
  3421. */
  3422. Vector3.Right = function () {
  3423. return new Vector3(1.0, 0.0, 0.0);
  3424. };
  3425. /**
  3426. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3427. * @returns a new left Vector3
  3428. */
  3429. Vector3.Left = function () {
  3430. return new Vector3(-1.0, 0.0, 0.0);
  3431. };
  3432. /**
  3433. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3434. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3435. * @param vector defines the Vector3 to transform
  3436. * @param transformation defines the transformation matrix
  3437. * @returns the transformed Vector3
  3438. */
  3439. Vector3.TransformCoordinates = function (vector, transformation) {
  3440. var result = Vector3.Zero();
  3441. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3442. return result;
  3443. };
  3444. /**
  3445. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3446. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3447. * @param vector defines the Vector3 to transform
  3448. * @param transformation defines the transformation matrix
  3449. * @param result defines the Vector3 where to store the result
  3450. */
  3451. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3452. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3453. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3454. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3455. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3456. result.x = x / w;
  3457. result.y = y / w;
  3458. result.z = z / w;
  3459. };
  3460. /**
  3461. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3462. * This method computes tranformed coordinates only, not transformed direction vectors
  3463. * @param x define the x coordinate of the source vector
  3464. * @param y define the y coordinate of the source vector
  3465. * @param z define the z coordinate of the source vector
  3466. * @param transformation defines the transformation matrix
  3467. * @param result defines the Vector3 where to store the result
  3468. */
  3469. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3470. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3471. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3472. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3473. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3474. result.x = rx / rw;
  3475. result.y = ry / rw;
  3476. result.z = rz / rw;
  3477. };
  3478. /**
  3479. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3480. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3481. * @param vector defines the Vector3 to transform
  3482. * @param transformation defines the transformation matrix
  3483. * @returns the new Vector3
  3484. */
  3485. Vector3.TransformNormal = function (vector, transformation) {
  3486. var result = Vector3.Zero();
  3487. Vector3.TransformNormalToRef(vector, transformation, result);
  3488. return result;
  3489. };
  3490. /**
  3491. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3492. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3493. * @param vector defines the Vector3 to transform
  3494. * @param transformation defines the transformation matrix
  3495. * @param result defines the Vector3 where to store the result
  3496. */
  3497. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3500. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3501. result.x = x;
  3502. result.y = y;
  3503. result.z = z;
  3504. };
  3505. /**
  3506. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3507. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3508. * @param x define the x coordinate of the source vector
  3509. * @param y define the y coordinate of the source vector
  3510. * @param z define the z coordinate of the source vector
  3511. * @param transformation defines the transformation matrix
  3512. * @param result defines the Vector3 where to store the result
  3513. */
  3514. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3515. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3516. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3517. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3518. };
  3519. /**
  3520. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3521. * @param value1 defines the first control point
  3522. * @param value2 defines the second control point
  3523. * @param value3 defines the third control point
  3524. * @param value4 defines the fourth control point
  3525. * @param amount defines the amount on the spline to use
  3526. * @returns the new Vector3
  3527. */
  3528. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3529. var squared = amount * amount;
  3530. var cubed = amount * squared;
  3531. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3532. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3533. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3534. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3535. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3536. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3537. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3538. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3539. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3540. return new Vector3(x, y, z);
  3541. };
  3542. /**
  3543. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3544. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3545. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3546. * @param value defines the current value
  3547. * @param min defines the lower range value
  3548. * @param max defines the upper range value
  3549. * @returns the new Vector3
  3550. */
  3551. Vector3.Clamp = function (value, min, max) {
  3552. var x = value.x;
  3553. x = (x > max.x) ? max.x : x;
  3554. x = (x < min.x) ? min.x : x;
  3555. var y = value.y;
  3556. y = (y > max.y) ? max.y : y;
  3557. y = (y < min.y) ? min.y : y;
  3558. var z = value.z;
  3559. z = (z > max.z) ? max.z : z;
  3560. z = (z < min.z) ? min.z : z;
  3561. return new Vector3(x, y, z);
  3562. };
  3563. /**
  3564. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3565. * @param value1 defines the first control point
  3566. * @param tangent1 defines the first tangent vector
  3567. * @param value2 defines the second control point
  3568. * @param tangent2 defines the second tangent vector
  3569. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3570. * @returns the new Vector3
  3571. */
  3572. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3573. var squared = amount * amount;
  3574. var cubed = amount * squared;
  3575. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3576. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3577. var part3 = (cubed - (2.0 * squared)) + amount;
  3578. var part4 = cubed - squared;
  3579. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3580. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3581. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3582. return new Vector3(x, y, z);
  3583. };
  3584. /**
  3585. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3586. * @param start defines the start value
  3587. * @param end defines the end value
  3588. * @param amount max defines amount between both (between 0 and 1)
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Lerp = function (start, end, amount) {
  3592. var result = new Vector3(0, 0, 0);
  3593. Vector3.LerpToRef(start, end, amount, result);
  3594. return result;
  3595. };
  3596. /**
  3597. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3598. * @param start defines the start value
  3599. * @param end defines the end value
  3600. * @param amount max defines amount between both (between 0 and 1)
  3601. * @param result defines the Vector3 where to store the result
  3602. */
  3603. Vector3.LerpToRef = function (start, end, amount, result) {
  3604. result.x = start.x + ((end.x - start.x) * amount);
  3605. result.y = start.y + ((end.y - start.y) * amount);
  3606. result.z = start.z + ((end.z - start.z) * amount);
  3607. };
  3608. /**
  3609. * Returns the dot product (float) between the vectors "left" and "right"
  3610. * @param left defines the left operand
  3611. * @param right defines the right operand
  3612. * @returns the dot product
  3613. */
  3614. Vector3.Dot = function (left, right) {
  3615. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3616. };
  3617. /**
  3618. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3619. * The cross product is then orthogonal to both "left" and "right"
  3620. * @param left defines the left operand
  3621. * @param right defines the right operand
  3622. * @returns the cross product
  3623. */
  3624. Vector3.Cross = function (left, right) {
  3625. var result = Vector3.Zero();
  3626. Vector3.CrossToRef(left, right, result);
  3627. return result;
  3628. };
  3629. /**
  3630. * Sets the given vector "result" with the cross product of "left" and "right"
  3631. * The cross product is then orthogonal to both "left" and "right"
  3632. * @param left defines the left operand
  3633. * @param right defines the right operand
  3634. * @param result defines the Vector3 where to store the result
  3635. */
  3636. Vector3.CrossToRef = function (left, right, result) {
  3637. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3638. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3639. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3640. result.copyFrom(MathTmp.Vector3[0]);
  3641. };
  3642. /**
  3643. * Returns a new Vector3 as the normalization of the given vector
  3644. * @param vector defines the Vector3 to normalize
  3645. * @returns the new Vector3
  3646. */
  3647. Vector3.Normalize = function (vector) {
  3648. var result = Vector3.Zero();
  3649. Vector3.NormalizeToRef(vector, result);
  3650. return result;
  3651. };
  3652. /**
  3653. * Sets the given vector "result" with the normalization of the given first vector
  3654. * @param vector defines the Vector3 to normalize
  3655. * @param result defines the Vector3 where to store the result
  3656. */
  3657. Vector3.NormalizeToRef = function (vector, result) {
  3658. result.copyFrom(vector);
  3659. result.normalize();
  3660. };
  3661. /**
  3662. * Project a Vector3 onto screen space
  3663. * @param vector defines the Vector3 to project
  3664. * @param world defines the world matrix to use
  3665. * @param transform defines the transform (view x projection) matrix to use
  3666. * @param viewport defines the screen viewport to use
  3667. * @returns the new Vector3
  3668. */
  3669. Vector3.Project = function (vector, world, transform, viewport) {
  3670. var cw = viewport.width;
  3671. var ch = viewport.height;
  3672. var cx = viewport.x;
  3673. var cy = viewport.y;
  3674. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3675. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3676. var matrix = MathTmp.Matrix[0];
  3677. world.multiplyToRef(transform, matrix);
  3678. matrix.multiplyToRef(viewportMatrix, matrix);
  3679. return Vector3.TransformCoordinates(vector, matrix);
  3680. };
  3681. /**
  3682. * Unproject from screen space to object space
  3683. * @param source defines the screen space Vector3 to use
  3684. * @param viewportWidth defines the current width of the viewport
  3685. * @param viewportHeight defines the current height of the viewport
  3686. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3687. * @param transform defines the transform (view x projection) matrix to use
  3688. * @returns the new Vector3
  3689. */
  3690. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3691. var matrix = MathTmp.Matrix[0];
  3692. world.multiplyToRef(transform, matrix);
  3693. matrix.invert();
  3694. source.x = source.x / viewportWidth * 2 - 1;
  3695. source.y = -(source.y / viewportHeight * 2 - 1);
  3696. var vector = Vector3.TransformCoordinates(source, matrix);
  3697. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3698. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3699. vector = vector.scale(1.0 / num);
  3700. }
  3701. return vector;
  3702. };
  3703. /**
  3704. * Unproject from screen space to object space
  3705. * @param source defines the screen space Vector3 to use
  3706. * @param viewportWidth defines the current width of the viewport
  3707. * @param viewportHeight defines the current height of the viewport
  3708. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3709. * @param view defines the view matrix to use
  3710. * @param projection defines the projection matrix to use
  3711. * @returns the new Vector3
  3712. */
  3713. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3714. var result = Vector3.Zero();
  3715. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * Unproject from screen space to object space
  3720. * @param source defines the screen space Vector3 to use
  3721. * @param viewportWidth defines the current width of the viewport
  3722. * @param viewportHeight defines the current height of the viewport
  3723. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3724. * @param view defines the view matrix to use
  3725. * @param projection defines the projection matrix to use
  3726. * @param result defines the Vector3 where to store the result
  3727. */
  3728. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3729. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3730. };
  3731. /**
  3732. * Unproject from screen space to object space
  3733. * @param sourceX defines the screen space x coordinate to use
  3734. * @param sourceY defines the screen space y coordinate to use
  3735. * @param sourceZ defines the screen space z coordinate to use
  3736. * @param viewportWidth defines the current width of the viewport
  3737. * @param viewportHeight defines the current height of the viewport
  3738. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3739. * @param view defines the view matrix to use
  3740. * @param projection defines the projection matrix to use
  3741. * @param result defines the Vector3 where to store the result
  3742. */
  3743. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3744. var matrix = MathTmp.Matrix[0];
  3745. world.multiplyToRef(view, matrix);
  3746. matrix.multiplyToRef(projection, matrix);
  3747. matrix.invert();
  3748. var screenSource = MathTmp.Vector3[0];
  3749. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3750. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3751. screenSource.z = 2 * sourceZ - 1.0;
  3752. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3753. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3754. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3755. result.scaleInPlace(1.0 / num);
  3756. }
  3757. };
  3758. /**
  3759. * Gets the minimal coordinate values between two Vector3
  3760. * @param left defines the first operand
  3761. * @param right defines the second operand
  3762. * @returns the new Vector3
  3763. */
  3764. Vector3.Minimize = function (left, right) {
  3765. var min = left.clone();
  3766. min.minimizeInPlace(right);
  3767. return min;
  3768. };
  3769. /**
  3770. * Gets the maximal coordinate values between two Vector3
  3771. * @param left defines the first operand
  3772. * @param right defines the second operand
  3773. * @returns the new Vector3
  3774. */
  3775. Vector3.Maximize = function (left, right) {
  3776. var max = left.clone();
  3777. max.maximizeInPlace(right);
  3778. return max;
  3779. };
  3780. /**
  3781. * Returns the distance between the vectors "value1" and "value2"
  3782. * @param value1 defines the first operand
  3783. * @param value2 defines the second operand
  3784. * @returns the distance
  3785. */
  3786. Vector3.Distance = function (value1, value2) {
  3787. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3788. };
  3789. /**
  3790. * Returns the squared distance between the vectors "value1" and "value2"
  3791. * @param value1 defines the first operand
  3792. * @param value2 defines the second operand
  3793. * @returns the squared distance
  3794. */
  3795. Vector3.DistanceSquared = function (value1, value2) {
  3796. var x = value1.x - value2.x;
  3797. var y = value1.y - value2.y;
  3798. var z = value1.z - value2.z;
  3799. return (x * x) + (y * y) + (z * z);
  3800. };
  3801. /**
  3802. * Returns a new Vector3 located at the center between "value1" and "value2"
  3803. * @param value1 defines the first operand
  3804. * @param value2 defines the second operand
  3805. * @returns the new Vector3
  3806. */
  3807. Vector3.Center = function (value1, value2) {
  3808. var center = value1.add(value2);
  3809. center.scaleInPlace(0.5);
  3810. return center;
  3811. };
  3812. /**
  3813. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3814. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3815. * to something in order to rotate it from its local system to the given target system
  3816. * Note: axis1, axis2 and axis3 are normalized during this operation
  3817. * @param axis1 defines the first axis
  3818. * @param axis2 defines the second axis
  3819. * @param axis3 defines the third axis
  3820. * @returns a new Vector3
  3821. */
  3822. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3823. var rotation = Vector3.Zero();
  3824. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3825. return rotation;
  3826. };
  3827. /**
  3828. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3829. * @param axis1 defines the first axis
  3830. * @param axis2 defines the second axis
  3831. * @param axis3 defines the third axis
  3832. * @param ref defines the Vector3 where to store the result
  3833. */
  3834. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3835. var quat = MathTmp.Quaternion[0];
  3836. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3837. quat.toEulerAnglesToRef(ref);
  3838. };
  3839. return Vector3;
  3840. }());
  3841. BABYLON.Vector3 = Vector3;
  3842. //Vector4 class created for EulerAngle class conversion to Quaternion
  3843. var Vector4 = /** @class */ (function () {
  3844. /**
  3845. * Creates a Vector4 object from the given floats.
  3846. */
  3847. function Vector4(x, y, z, w) {
  3848. this.x = x;
  3849. this.y = y;
  3850. this.z = z;
  3851. this.w = w;
  3852. }
  3853. /**
  3854. * Returns the string with the Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.toString = function () {
  3857. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3858. };
  3859. /**
  3860. * Returns the string "Vector4".
  3861. */
  3862. Vector4.prototype.getClassName = function () {
  3863. return "Vector4";
  3864. };
  3865. /**
  3866. * Returns the Vector4 hash code.
  3867. */
  3868. Vector4.prototype.getHashCode = function () {
  3869. var hash = this.x || 0;
  3870. hash = (hash * 397) ^ (this.y || 0);
  3871. hash = (hash * 397) ^ (this.z || 0);
  3872. hash = (hash * 397) ^ (this.w || 0);
  3873. return hash;
  3874. };
  3875. // Operators
  3876. /**
  3877. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3878. */
  3879. Vector4.prototype.asArray = function () {
  3880. var result = new Array();
  3881. this.toArray(result, 0);
  3882. return result;
  3883. };
  3884. /**
  3885. * Populates the given array from the given index with the Vector4 coordinates.
  3886. * Returns the Vector4.
  3887. */
  3888. Vector4.prototype.toArray = function (array, index) {
  3889. if (index === undefined) {
  3890. index = 0;
  3891. }
  3892. array[index] = this.x;
  3893. array[index + 1] = this.y;
  3894. array[index + 2] = this.z;
  3895. array[index + 3] = this.w;
  3896. return this;
  3897. };
  3898. /**
  3899. * Adds the given vector to the current Vector4.
  3900. * Returns the updated Vector4.
  3901. */
  3902. Vector4.prototype.addInPlace = function (otherVector) {
  3903. this.x += otherVector.x;
  3904. this.y += otherVector.y;
  3905. this.z += otherVector.z;
  3906. this.w += otherVector.w;
  3907. return this;
  3908. };
  3909. /**
  3910. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3911. */
  3912. Vector4.prototype.add = function (otherVector) {
  3913. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3914. };
  3915. /**
  3916. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3917. * Returns the current Vector4.
  3918. */
  3919. Vector4.prototype.addToRef = function (otherVector, result) {
  3920. result.x = this.x + otherVector.x;
  3921. result.y = this.y + otherVector.y;
  3922. result.z = this.z + otherVector.z;
  3923. result.w = this.w + otherVector.w;
  3924. return this;
  3925. };
  3926. /**
  3927. * Subtract in place the given vector from the current Vector4.
  3928. * Returns the updated Vector4.
  3929. */
  3930. Vector4.prototype.subtractInPlace = function (otherVector) {
  3931. this.x -= otherVector.x;
  3932. this.y -= otherVector.y;
  3933. this.z -= otherVector.z;
  3934. this.w -= otherVector.w;
  3935. return this;
  3936. };
  3937. /**
  3938. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3939. */
  3940. Vector4.prototype.subtract = function (otherVector) {
  3941. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3942. };
  3943. /**
  3944. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3945. * Returns the current Vector4.
  3946. */
  3947. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3948. result.x = this.x - otherVector.x;
  3949. result.y = this.y - otherVector.y;
  3950. result.z = this.z - otherVector.z;
  3951. result.w = this.w - otherVector.w;
  3952. return this;
  3953. };
  3954. /**
  3955. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3956. */
  3957. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3958. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3959. };
  3960. /**
  3961. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3962. * Returns the current Vector4.
  3963. */
  3964. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3965. result.x = this.x - x;
  3966. result.y = this.y - y;
  3967. result.z = this.z - z;
  3968. result.w = this.w - w;
  3969. return this;
  3970. };
  3971. /**
  3972. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3973. */
  3974. Vector4.prototype.negate = function () {
  3975. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3976. };
  3977. /**
  3978. * Multiplies the current Vector4 coordinates by scale (float).
  3979. * Returns the updated Vector4.
  3980. */
  3981. Vector4.prototype.scaleInPlace = function (scale) {
  3982. this.x *= scale;
  3983. this.y *= scale;
  3984. this.z *= scale;
  3985. this.w *= scale;
  3986. return this;
  3987. };
  3988. /**
  3989. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3990. */
  3991. Vector4.prototype.scale = function (scale) {
  3992. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3993. };
  3994. /**
  3995. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3996. * Returns the current Vector4.
  3997. */
  3998. Vector4.prototype.scaleToRef = function (scale, result) {
  3999. result.x = this.x * scale;
  4000. result.y = this.y * scale;
  4001. result.z = this.z * scale;
  4002. result.w = this.w * scale;
  4003. return this;
  4004. };
  4005. /**
  4006. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4007. * @param scale defines the scale factor
  4008. * @param result defines the Vector4 object where to store the result
  4009. * @returns the unmodified current Vector4
  4010. */
  4011. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4012. result.x += this.x * scale;
  4013. result.y += this.y * scale;
  4014. result.z += this.z * scale;
  4015. result.w += this.w * scale;
  4016. return this;
  4017. };
  4018. /**
  4019. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4020. */
  4021. Vector4.prototype.equals = function (otherVector) {
  4022. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4023. };
  4024. /**
  4025. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4026. */
  4027. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4028. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4029. return otherVector
  4030. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4031. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4032. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4033. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4034. };
  4035. /**
  4036. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4037. */
  4038. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4039. return this.x === x && this.y === y && this.z === z && this.w === w;
  4040. };
  4041. /**
  4042. * Multiplies in place the current Vector4 by the given one.
  4043. * Returns the updated Vector4.
  4044. */
  4045. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4046. this.x *= otherVector.x;
  4047. this.y *= otherVector.y;
  4048. this.z *= otherVector.z;
  4049. this.w *= otherVector.w;
  4050. return this;
  4051. };
  4052. /**
  4053. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4054. */
  4055. Vector4.prototype.multiply = function (otherVector) {
  4056. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4057. };
  4058. /**
  4059. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4060. * Returns the current Vector4.
  4061. */
  4062. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4063. result.x = this.x * otherVector.x;
  4064. result.y = this.y * otherVector.y;
  4065. result.z = this.z * otherVector.z;
  4066. result.w = this.w * otherVector.w;
  4067. return this;
  4068. };
  4069. /**
  4070. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4071. */
  4072. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4073. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4074. };
  4075. /**
  4076. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4077. */
  4078. Vector4.prototype.divide = function (otherVector) {
  4079. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4080. };
  4081. /**
  4082. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4083. * Returns the current Vector4.
  4084. */
  4085. Vector4.prototype.divideToRef = function (otherVector, result) {
  4086. result.x = this.x / otherVector.x;
  4087. result.y = this.y / otherVector.y;
  4088. result.z = this.z / otherVector.z;
  4089. result.w = this.w / otherVector.w;
  4090. return this;
  4091. };
  4092. /**
  4093. * Divides the current Vector3 coordinates by the given ones.
  4094. * @returns the updated Vector3.
  4095. */
  4096. Vector4.prototype.divideInPlace = function (otherVector) {
  4097. return this.divideToRef(otherVector, this);
  4098. };
  4099. /**
  4100. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4101. * @param other defines the second operand
  4102. * @returns the current updated Vector4
  4103. */
  4104. Vector4.prototype.minimizeInPlace = function (other) {
  4105. if (other.x < this.x)
  4106. this.x = other.x;
  4107. if (other.y < this.y)
  4108. this.y = other.y;
  4109. if (other.z < this.z)
  4110. this.z = other.z;
  4111. if (other.w < this.w)
  4112. this.w = other.w;
  4113. return this;
  4114. };
  4115. /**
  4116. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4117. * @param other defines the second operand
  4118. * @returns the current updated Vector4
  4119. */
  4120. Vector4.prototype.maximizeInPlace = function (other) {
  4121. if (other.x > this.x)
  4122. this.x = other.x;
  4123. if (other.y > this.y)
  4124. this.y = other.y;
  4125. if (other.z > this.z)
  4126. this.z = other.z;
  4127. if (other.w > this.w)
  4128. this.w = other.w;
  4129. return this;
  4130. };
  4131. // Properties
  4132. /**
  4133. * Returns the Vector4 length (float).
  4134. */
  4135. Vector4.prototype.length = function () {
  4136. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4137. };
  4138. /**
  4139. * Returns the Vector4 squared length (float).
  4140. */
  4141. Vector4.prototype.lengthSquared = function () {
  4142. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4143. };
  4144. // Methods
  4145. /**
  4146. * Normalizes in place the Vector4.
  4147. * Returns the updated Vector4.
  4148. */
  4149. Vector4.prototype.normalize = function () {
  4150. var len = this.length();
  4151. if (len === 0)
  4152. return this;
  4153. var num = 1.0 / len;
  4154. this.x *= num;
  4155. this.y *= num;
  4156. this.z *= num;
  4157. this.w *= num;
  4158. return this;
  4159. };
  4160. /**
  4161. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4162. */
  4163. Vector4.prototype.toVector3 = function () {
  4164. return new Vector3(this.x, this.y, this.z);
  4165. };
  4166. /**
  4167. * Returns a new Vector4 copied from the current one.
  4168. */
  4169. Vector4.prototype.clone = function () {
  4170. return new Vector4(this.x, this.y, this.z, this.w);
  4171. };
  4172. /**
  4173. * Updates the current Vector4 with the given one coordinates.
  4174. * Returns the updated Vector4.
  4175. */
  4176. Vector4.prototype.copyFrom = function (source) {
  4177. this.x = source.x;
  4178. this.y = source.y;
  4179. this.z = source.z;
  4180. this.w = source.w;
  4181. return this;
  4182. };
  4183. /**
  4184. * Updates the current Vector4 coordinates with the given floats.
  4185. * Returns the updated Vector4.
  4186. */
  4187. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4188. this.x = x;
  4189. this.y = y;
  4190. this.z = z;
  4191. this.w = w;
  4192. return this;
  4193. };
  4194. /**
  4195. * Updates the current Vector4 coordinates with the given floats.
  4196. * Returns the updated Vector4.
  4197. */
  4198. Vector4.prototype.set = function (x, y, z, w) {
  4199. return this.copyFromFloats(x, y, z, w);
  4200. };
  4201. // Statics
  4202. /**
  4203. * Returns a new Vector4 set from the starting index of the given array.
  4204. */
  4205. Vector4.FromArray = function (array, offset) {
  4206. if (!offset) {
  4207. offset = 0;
  4208. }
  4209. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4210. };
  4211. /**
  4212. * Updates the given vector "result" from the starting index of the given array.
  4213. */
  4214. Vector4.FromArrayToRef = function (array, offset, result) {
  4215. result.x = array[offset];
  4216. result.y = array[offset + 1];
  4217. result.z = array[offset + 2];
  4218. result.w = array[offset + 3];
  4219. };
  4220. /**
  4221. * Updates the given vector "result" from the starting index of the given Float32Array.
  4222. */
  4223. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4224. Vector4.FromArrayToRef(array, offset, result);
  4225. };
  4226. /**
  4227. * Updates the given vector "result" coordinates from the given floats.
  4228. */
  4229. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4230. result.x = x;
  4231. result.y = y;
  4232. result.z = z;
  4233. result.w = w;
  4234. };
  4235. /**
  4236. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4237. */
  4238. Vector4.Zero = function () {
  4239. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4240. };
  4241. /**
  4242. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4243. */
  4244. Vector4.One = function () {
  4245. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4246. };
  4247. /**
  4248. * Returns a new normalized Vector4 from the given one.
  4249. */
  4250. Vector4.Normalize = function (vector) {
  4251. var result = Vector4.Zero();
  4252. Vector4.NormalizeToRef(vector, result);
  4253. return result;
  4254. };
  4255. /**
  4256. * Updates the given vector "result" from the normalization of the given one.
  4257. */
  4258. Vector4.NormalizeToRef = function (vector, result) {
  4259. result.copyFrom(vector);
  4260. result.normalize();
  4261. };
  4262. Vector4.Minimize = function (left, right) {
  4263. var min = left.clone();
  4264. min.minimizeInPlace(right);
  4265. return min;
  4266. };
  4267. Vector4.Maximize = function (left, right) {
  4268. var max = left.clone();
  4269. max.maximizeInPlace(right);
  4270. return max;
  4271. };
  4272. /**
  4273. * Returns the distance (float) between the vectors "value1" and "value2".
  4274. */
  4275. Vector4.Distance = function (value1, value2) {
  4276. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4277. };
  4278. /**
  4279. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4280. */
  4281. Vector4.DistanceSquared = function (value1, value2) {
  4282. var x = value1.x - value2.x;
  4283. var y = value1.y - value2.y;
  4284. var z = value1.z - value2.z;
  4285. var w = value1.w - value2.w;
  4286. return (x * x) + (y * y) + (z * z) + (w * w);
  4287. };
  4288. /**
  4289. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4290. */
  4291. Vector4.Center = function (value1, value2) {
  4292. var center = value1.add(value2);
  4293. center.scaleInPlace(0.5);
  4294. return center;
  4295. };
  4296. /**
  4297. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4298. * This methods computes transformed normalized direction vectors only.
  4299. */
  4300. Vector4.TransformNormal = function (vector, transformation) {
  4301. var result = Vector4.Zero();
  4302. Vector4.TransformNormalToRef(vector, transformation, result);
  4303. return result;
  4304. };
  4305. /**
  4306. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4307. * This methods computes transformed normalized direction vectors only.
  4308. */
  4309. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4310. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4311. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4312. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4313. result.x = x;
  4314. result.y = y;
  4315. result.z = z;
  4316. result.w = vector.w;
  4317. };
  4318. /**
  4319. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4320. * This methods computes transformed normalized direction vectors only.
  4321. */
  4322. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4323. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4324. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4325. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4326. result.w = w;
  4327. };
  4328. return Vector4;
  4329. }());
  4330. BABYLON.Vector4 = Vector4;
  4331. var Size = /** @class */ (function () {
  4332. /**
  4333. * Creates a Size object from the given width and height (floats).
  4334. */
  4335. function Size(width, height) {
  4336. this.width = width;
  4337. this.height = height;
  4338. }
  4339. // Returns a string with the Size width and height.
  4340. Size.prototype.toString = function () {
  4341. return "{W: " + this.width + ", H: " + this.height + "}";
  4342. };
  4343. /**
  4344. * Returns the string "Size"
  4345. */
  4346. Size.prototype.getClassName = function () {
  4347. return "Size";
  4348. };
  4349. /**
  4350. * Returns the Size hash code.
  4351. */
  4352. Size.prototype.getHashCode = function () {
  4353. var hash = this.width || 0;
  4354. hash = (hash * 397) ^ (this.height || 0);
  4355. return hash;
  4356. };
  4357. /**
  4358. * Updates the current size from the given one.
  4359. * Returns the updated Size.
  4360. */
  4361. Size.prototype.copyFrom = function (src) {
  4362. this.width = src.width;
  4363. this.height = src.height;
  4364. };
  4365. /**
  4366. * Updates in place the current Size from the given floats.
  4367. * Returns the updated Size.
  4368. */
  4369. Size.prototype.copyFromFloats = function (width, height) {
  4370. this.width = width;
  4371. this.height = height;
  4372. return this;
  4373. };
  4374. /**
  4375. * Updates in place the current Size from the given floats.
  4376. * Returns the updated Size.
  4377. */
  4378. Size.prototype.set = function (width, height) {
  4379. return this.copyFromFloats(width, height);
  4380. };
  4381. /**
  4382. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4383. */
  4384. Size.prototype.multiplyByFloats = function (w, h) {
  4385. return new Size(this.width * w, this.height * h);
  4386. };
  4387. /**
  4388. * Returns a new Size copied from the given one.
  4389. */
  4390. Size.prototype.clone = function () {
  4391. return new Size(this.width, this.height);
  4392. };
  4393. /**
  4394. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4395. */
  4396. Size.prototype.equals = function (other) {
  4397. if (!other) {
  4398. return false;
  4399. }
  4400. return (this.width === other.width) && (this.height === other.height);
  4401. };
  4402. Object.defineProperty(Size.prototype, "surface", {
  4403. /**
  4404. * Returns the surface of the Size : width * height (float).
  4405. */
  4406. get: function () {
  4407. return this.width * this.height;
  4408. },
  4409. enumerable: true,
  4410. configurable: true
  4411. });
  4412. /**
  4413. * Returns a new Size set to (0.0, 0.0)
  4414. */
  4415. Size.Zero = function () {
  4416. return new Size(0.0, 0.0);
  4417. };
  4418. /**
  4419. * Returns a new Size set as the addition result of the current Size and the given one.
  4420. */
  4421. Size.prototype.add = function (otherSize) {
  4422. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4423. return r;
  4424. };
  4425. /**
  4426. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4427. */
  4428. Size.prototype.subtract = function (otherSize) {
  4429. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4430. return r;
  4431. };
  4432. /**
  4433. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4434. */
  4435. Size.Lerp = function (start, end, amount) {
  4436. var w = start.width + ((end.width - start.width) * amount);
  4437. var h = start.height + ((end.height - start.height) * amount);
  4438. return new Size(w, h);
  4439. };
  4440. return Size;
  4441. }());
  4442. BABYLON.Size = Size;
  4443. /**
  4444. * Class used to store quaternion data
  4445. * @see https://en.wikipedia.org/wiki/Quaternion
  4446. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4447. */
  4448. var Quaternion = /** @class */ (function () {
  4449. /**
  4450. * Creates a new Quaternion from the given floats
  4451. * @param x defines the first component (0 by default)
  4452. * @param y defines the second component (0 by default)
  4453. * @param z defines the third component (0 by default)
  4454. * @param w defines the fourth component (1.0 by default)
  4455. */
  4456. function Quaternion(
  4457. /** defines the first component (0 by default) */
  4458. x,
  4459. /** defines the second component (0 by default) */
  4460. y,
  4461. /** defines the third component (0 by default) */
  4462. z,
  4463. /** defines the fourth component (1.0 by default) */
  4464. w) {
  4465. if (x === void 0) { x = 0.0; }
  4466. if (y === void 0) { y = 0.0; }
  4467. if (z === void 0) { z = 0.0; }
  4468. if (w === void 0) { w = 1.0; }
  4469. this.x = x;
  4470. this.y = y;
  4471. this.z = z;
  4472. this.w = w;
  4473. }
  4474. /**
  4475. * Gets a string representation for the current quaternion
  4476. * @returns a string with the Quaternion coordinates
  4477. */
  4478. Quaternion.prototype.toString = function () {
  4479. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4480. };
  4481. /**
  4482. * Gets the class name of the quaternion
  4483. * @returns the string "Quaternion"
  4484. */
  4485. Quaternion.prototype.getClassName = function () {
  4486. return "Quaternion";
  4487. };
  4488. /**
  4489. * Gets a hash code for this quaternion
  4490. * @returns the quaternion hash code
  4491. */
  4492. Quaternion.prototype.getHashCode = function () {
  4493. var hash = this.x || 0;
  4494. hash = (hash * 397) ^ (this.y || 0);
  4495. hash = (hash * 397) ^ (this.z || 0);
  4496. hash = (hash * 397) ^ (this.w || 0);
  4497. return hash;
  4498. };
  4499. /**
  4500. * Copy the quaternion to an array
  4501. * @returns a new array populated with 4 elements from the quaternion coordinates
  4502. */
  4503. Quaternion.prototype.asArray = function () {
  4504. return [this.x, this.y, this.z, this.w];
  4505. };
  4506. /**
  4507. * Check if two quaternions are equals
  4508. * @param otherQuaternion defines the second operand
  4509. * @return true if the current quaternion and the given one coordinates are strictly equals
  4510. */
  4511. Quaternion.prototype.equals = function (otherQuaternion) {
  4512. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4513. };
  4514. /**
  4515. * Clone the current quaternion
  4516. * @returns a new quaternion copied from the current one
  4517. */
  4518. Quaternion.prototype.clone = function () {
  4519. return new Quaternion(this.x, this.y, this.z, this.w);
  4520. };
  4521. /**
  4522. * Copy a quaternion to the current one
  4523. * @param other defines the other quaternion
  4524. * @returns the updated current quaternion
  4525. */
  4526. Quaternion.prototype.copyFrom = function (other) {
  4527. this.x = other.x;
  4528. this.y = other.y;
  4529. this.z = other.z;
  4530. this.w = other.w;
  4531. return this;
  4532. };
  4533. /**
  4534. * Updates the current quaternion with the given float coordinates
  4535. * @param x defines the x coordinate
  4536. * @param y defines the y coordinate
  4537. * @param z defines the z coordinate
  4538. * @param w defines the w coordinate
  4539. * @returns the updated current quaternion
  4540. */
  4541. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4542. this.x = x;
  4543. this.y = y;
  4544. this.z = z;
  4545. this.w = w;
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current quaternion from the given float coordinates
  4550. * @param x defines the x coordinate
  4551. * @param y defines the y coordinate
  4552. * @param z defines the z coordinate
  4553. * @param w defines the w coordinate
  4554. * @returns the updated current quaternion
  4555. */
  4556. Quaternion.prototype.set = function (x, y, z, w) {
  4557. return this.copyFromFloats(x, y, z, w);
  4558. };
  4559. /**
  4560. * Adds two quaternions
  4561. * @param other defines the second operand
  4562. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4563. */
  4564. Quaternion.prototype.add = function (other) {
  4565. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4566. };
  4567. /**
  4568. * Add a quaternion to the current one
  4569. * @param other defines the quaternion to add
  4570. * @returns the current quaternion
  4571. */
  4572. Quaternion.prototype.addInPlace = function (other) {
  4573. this.x += other.x;
  4574. this.y += other.y;
  4575. this.z += other.z;
  4576. this.w += other.w;
  4577. return this;
  4578. };
  4579. /**
  4580. * Subtract two quaternions
  4581. * @param other defines the second operand
  4582. * @returns a new quaternion as the subtraction result of the given one from the current one
  4583. */
  4584. Quaternion.prototype.subtract = function (other) {
  4585. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4586. };
  4587. /**
  4588. * Multiplies the current quaternion by a scale factor
  4589. * @param value defines the scale factor
  4590. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4591. */
  4592. Quaternion.prototype.scale = function (value) {
  4593. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4594. };
  4595. /**
  4596. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4597. * @param scale defines the scale factor
  4598. * @param result defines the Quaternion object where to store the result
  4599. * @returns the unmodified current quaternion
  4600. */
  4601. Quaternion.prototype.scaleToRef = function (scale, result) {
  4602. result.x = this.x * scale;
  4603. result.y = this.y * scale;
  4604. result.z = this.z * scale;
  4605. result.w = this.w * scale;
  4606. return this;
  4607. };
  4608. /**
  4609. * Multiplies in place the current quaternion by a scale factor
  4610. * @param value defines the scale factor
  4611. * @returns the current modified quaternion
  4612. */
  4613. Quaternion.prototype.scaleInPlace = function (value) {
  4614. this.x *= value;
  4615. this.y *= value;
  4616. this.z *= value;
  4617. this.w *= value;
  4618. return this;
  4619. };
  4620. /**
  4621. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4622. * @param scale defines the scale factor
  4623. * @param result defines the Quaternion object where to store the result
  4624. * @returns the unmodified current quaternion
  4625. */
  4626. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4627. result.x += this.x * scale;
  4628. result.y += this.y * scale;
  4629. result.z += this.z * scale;
  4630. result.w += this.w * scale;
  4631. return this;
  4632. };
  4633. /**
  4634. * Multiplies two quaternions
  4635. * @param q1 defines the second operand
  4636. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4637. */
  4638. Quaternion.prototype.multiply = function (q1) {
  4639. var result = new Quaternion(0, 0, 0, 1.0);
  4640. this.multiplyToRef(q1, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4645. * @param q1 defines the second operand
  4646. * @param result defines the target quaternion
  4647. * @returns the current quaternion
  4648. */
  4649. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4650. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4651. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4652. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4653. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4654. result.copyFromFloats(x, y, z, w);
  4655. return this;
  4656. };
  4657. /**
  4658. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4659. * @param q1 defines the second operand
  4660. * @returns the currentupdated quaternion
  4661. */
  4662. Quaternion.prototype.multiplyInPlace = function (q1) {
  4663. this.multiplyToRef(q1, this);
  4664. return this;
  4665. };
  4666. /**
  4667. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4668. * @param ref defines the target quaternion
  4669. * @returns the current quaternion
  4670. */
  4671. Quaternion.prototype.conjugateToRef = function (ref) {
  4672. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4673. return this;
  4674. };
  4675. /**
  4676. * Conjugates in place (1-q) the current quaternion
  4677. * @returns the current updated quaternion
  4678. */
  4679. Quaternion.prototype.conjugateInPlace = function () {
  4680. this.x *= -1;
  4681. this.y *= -1;
  4682. this.z *= -1;
  4683. return this;
  4684. };
  4685. /**
  4686. * Conjugates in place (1-q) the current quaternion
  4687. * @returns a new quaternion
  4688. */
  4689. Quaternion.prototype.conjugate = function () {
  4690. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4691. return result;
  4692. };
  4693. /**
  4694. * Gets length of current quaternion
  4695. * @returns the quaternion length (float)
  4696. */
  4697. Quaternion.prototype.length = function () {
  4698. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4699. };
  4700. /**
  4701. * Normalize in place the current quaternion
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.normalize = function () {
  4705. var length = 1.0 / this.length();
  4706. this.x *= length;
  4707. this.y *= length;
  4708. this.z *= length;
  4709. this.w *= length;
  4710. return this;
  4711. };
  4712. /**
  4713. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4714. * @param order is a reserved parameter and is ignore for now
  4715. * @returns a new Vector3 containing the Euler angles
  4716. */
  4717. Quaternion.prototype.toEulerAngles = function (order) {
  4718. if (order === void 0) { order = "YZX"; }
  4719. var result = Vector3.Zero();
  4720. this.toEulerAnglesToRef(result, order);
  4721. return result;
  4722. };
  4723. /**
  4724. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4725. * @param result defines the vector which will be filled with the Euler angles
  4726. * @param order is a reserved parameter and is ignore for now
  4727. * @returns the current unchanged quaternion
  4728. */
  4729. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4730. if (order === void 0) { order = "YZX"; }
  4731. var qz = this.z;
  4732. var qx = this.x;
  4733. var qy = this.y;
  4734. var qw = this.w;
  4735. var sqw = qw * qw;
  4736. var sqz = qz * qz;
  4737. var sqx = qx * qx;
  4738. var sqy = qy * qy;
  4739. var zAxisY = qy * qz - qx * qw;
  4740. var limit = .4999999;
  4741. if (zAxisY < -limit) {
  4742. result.y = 2 * Math.atan2(qy, qw);
  4743. result.x = Math.PI / 2;
  4744. result.z = 0;
  4745. }
  4746. else if (zAxisY > limit) {
  4747. result.y = 2 * Math.atan2(qy, qw);
  4748. result.x = -Math.PI / 2;
  4749. result.z = 0;
  4750. }
  4751. else {
  4752. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4753. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4754. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4755. }
  4756. return this;
  4757. };
  4758. /**
  4759. * Updates the given rotation matrix with the current quaternion values
  4760. * @param result defines the target matrix
  4761. * @returns the current unchanged quaternion
  4762. */
  4763. Quaternion.prototype.toRotationMatrix = function (result) {
  4764. var xx = this.x * this.x;
  4765. var yy = this.y * this.y;
  4766. var zz = this.z * this.z;
  4767. var xy = this.x * this.y;
  4768. var zw = this.z * this.w;
  4769. var zx = this.z * this.x;
  4770. var yw = this.y * this.w;
  4771. var yz = this.y * this.z;
  4772. var xw = this.x * this.w;
  4773. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4774. result.m[1] = 2.0 * (xy + zw);
  4775. result.m[2] = 2.0 * (zx - yw);
  4776. result.m[3] = 0;
  4777. result.m[4] = 2.0 * (xy - zw);
  4778. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4779. result.m[6] = 2.0 * (yz + xw);
  4780. result.m[7] = 0;
  4781. result.m[8] = 2.0 * (zx + yw);
  4782. result.m[9] = 2.0 * (yz - xw);
  4783. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4784. result.m[11] = 0;
  4785. result.m[12] = 0;
  4786. result.m[13] = 0;
  4787. result.m[14] = 0;
  4788. result.m[15] = 1.0;
  4789. result._markAsUpdated();
  4790. return this;
  4791. };
  4792. /**
  4793. * Updates the current quaternion from the given rotation matrix values
  4794. * @param matrix defines the source matrix
  4795. * @returns the current updated quaternion
  4796. */
  4797. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4798. Quaternion.FromRotationMatrixToRef(matrix, this);
  4799. return this;
  4800. };
  4801. // Statics
  4802. /**
  4803. * Creates a new quaternion from a rotation matrix
  4804. * @param matrix defines the source matrix
  4805. * @returns a new quaternion created from the given rotation matrix values
  4806. */
  4807. Quaternion.FromRotationMatrix = function (matrix) {
  4808. var result = new Quaternion();
  4809. Quaternion.FromRotationMatrixToRef(matrix, result);
  4810. return result;
  4811. };
  4812. /**
  4813. * Updates the given quaternion with the given rotation matrix values
  4814. * @param matrix defines the source matrix
  4815. * @param result defines the target quaternion
  4816. */
  4817. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4818. var data = matrix.m;
  4819. var m11 = data[0], m12 = data[4], m13 = data[8];
  4820. var m21 = data[1], m22 = data[5], m23 = data[9];
  4821. var m31 = data[2], m32 = data[6], m33 = data[10];
  4822. var trace = m11 + m22 + m33;
  4823. var s;
  4824. if (trace > 0) {
  4825. s = 0.5 / Math.sqrt(trace + 1.0);
  4826. result.w = 0.25 / s;
  4827. result.x = (m32 - m23) * s;
  4828. result.y = (m13 - m31) * s;
  4829. result.z = (m21 - m12) * s;
  4830. }
  4831. else if (m11 > m22 && m11 > m33) {
  4832. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4833. result.w = (m32 - m23) / s;
  4834. result.x = 0.25 * s;
  4835. result.y = (m12 + m21) / s;
  4836. result.z = (m13 + m31) / s;
  4837. }
  4838. else if (m22 > m33) {
  4839. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4840. result.w = (m13 - m31) / s;
  4841. result.x = (m12 + m21) / s;
  4842. result.y = 0.25 * s;
  4843. result.z = (m23 + m32) / s;
  4844. }
  4845. else {
  4846. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4847. result.w = (m21 - m12) / s;
  4848. result.x = (m13 + m31) / s;
  4849. result.y = (m23 + m32) / s;
  4850. result.z = 0.25 * s;
  4851. }
  4852. };
  4853. /**
  4854. * Returns the dot product (float) between the quaternions "left" and "right"
  4855. * @param left defines the left operand
  4856. * @param right defines the right operand
  4857. * @returns the dot product
  4858. */
  4859. Quaternion.Dot = function (left, right) {
  4860. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4861. };
  4862. /**
  4863. * Checks if the two quaternions are close to each other
  4864. * @param quat0 defines the first quaternion to check
  4865. * @param quat1 defines the second quaternion to check
  4866. * @returns true if the two quaternions are close to each other
  4867. */
  4868. Quaternion.AreClose = function (quat0, quat1) {
  4869. var dot = Quaternion.Dot(quat0, quat1);
  4870. return dot >= 0;
  4871. };
  4872. /**
  4873. * Creates an empty quaternion
  4874. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4875. */
  4876. Quaternion.Zero = function () {
  4877. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4878. };
  4879. /**
  4880. * Inverse a given quaternion
  4881. * @param q defines the source quaternion
  4882. * @returns a new quaternion as the inverted current quaternion
  4883. */
  4884. Quaternion.Inverse = function (q) {
  4885. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4886. };
  4887. /**
  4888. * Creates an identity quaternion
  4889. * @returns the identity quaternion
  4890. */
  4891. Quaternion.Identity = function () {
  4892. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4893. };
  4894. /**
  4895. * Gets a boolean indicating if the given quaternion is identity
  4896. * @param quaternion defines the quaternion to check
  4897. * @returns true if the quaternion is identity
  4898. */
  4899. Quaternion.IsIdentity = function (quaternion) {
  4900. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4901. };
  4902. /**
  4903. * Creates a quaternion from a rotation around an axis
  4904. * @param axis defines the axis to use
  4905. * @param angle defines the angle to use
  4906. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4907. */
  4908. Quaternion.RotationAxis = function (axis, angle) {
  4909. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4910. };
  4911. /**
  4912. * Creates a rotation around an axis and stores it into the given quaternion
  4913. * @param axis defines the axis to use
  4914. * @param angle defines the angle to use
  4915. * @param result defines the target quaternion
  4916. * @returns the target quaternion
  4917. */
  4918. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4919. var sin = Math.sin(angle / 2);
  4920. axis.normalize();
  4921. result.w = Math.cos(angle / 2);
  4922. result.x = axis.x * sin;
  4923. result.y = axis.y * sin;
  4924. result.z = axis.z * sin;
  4925. return result;
  4926. };
  4927. /**
  4928. * Creates a new quaternion from data stored into an array
  4929. * @param array defines the data source
  4930. * @param offset defines the offset in the source array where the data starts
  4931. * @returns a new quaternion
  4932. */
  4933. Quaternion.FromArray = function (array, offset) {
  4934. if (!offset) {
  4935. offset = 0;
  4936. }
  4937. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4938. };
  4939. /**
  4940. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4941. * @param yaw defines the rotation around Y axis
  4942. * @param pitch defines the rotation around X axis
  4943. * @param roll defines the rotation around Z axis
  4944. * @returns the new quaternion
  4945. */
  4946. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4947. var q = new Quaternion();
  4948. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4949. return q;
  4950. };
  4951. /**
  4952. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4953. * @param yaw defines the rotation around Y axis
  4954. * @param pitch defines the rotation around X axis
  4955. * @param roll defines the rotation around Z axis
  4956. * @param result defines the target quaternion
  4957. */
  4958. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4959. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4960. var halfRoll = roll * 0.5;
  4961. var halfPitch = pitch * 0.5;
  4962. var halfYaw = yaw * 0.5;
  4963. var sinRoll = Math.sin(halfRoll);
  4964. var cosRoll = Math.cos(halfRoll);
  4965. var sinPitch = Math.sin(halfPitch);
  4966. var cosPitch = Math.cos(halfPitch);
  4967. var sinYaw = Math.sin(halfYaw);
  4968. var cosYaw = Math.cos(halfYaw);
  4969. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4970. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4971. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4972. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4973. };
  4974. /**
  4975. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4976. * @param alpha defines the rotation around first axis
  4977. * @param beta defines the rotation around second axis
  4978. * @param gamma defines the rotation around third axis
  4979. * @returns the new quaternion
  4980. */
  4981. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4982. var result = new Quaternion();
  4983. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4984. return result;
  4985. };
  4986. /**
  4987. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4988. * @param alpha defines the rotation around first axis
  4989. * @param beta defines the rotation around second axis
  4990. * @param gamma defines the rotation around third axis
  4991. * @param result defines the target quaternion
  4992. */
  4993. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4994. // Produces a quaternion from Euler angles in the z-x-z orientation
  4995. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4996. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4997. var halfBeta = beta * 0.5;
  4998. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4999. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5000. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5001. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5002. };
  5003. /**
  5004. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5005. * @param axis1 defines the first axis
  5006. * @param axis2 defines the second axis
  5007. * @param axis3 defines the third axis
  5008. * @returns the new quaternion
  5009. */
  5010. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5011. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5012. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5013. return quat;
  5014. };
  5015. /**
  5016. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5017. * @param axis1 defines the first axis
  5018. * @param axis2 defines the second axis
  5019. * @param axis3 defines the third axis
  5020. * @param ref defines the target quaternion
  5021. */
  5022. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5023. var rotMat = MathTmp.Matrix[0];
  5024. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5025. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5026. };
  5027. /**
  5028. * Interpolates between two quaternions
  5029. * @param left defines first quaternion
  5030. * @param right defines second quaternion
  5031. * @param amount defines the gradient to use
  5032. * @returns the new interpolated quaternion
  5033. */
  5034. Quaternion.Slerp = function (left, right, amount) {
  5035. var result = Quaternion.Identity();
  5036. Quaternion.SlerpToRef(left, right, amount, result);
  5037. return result;
  5038. };
  5039. /**
  5040. * Interpolates between two quaternions and stores it into a target quaternion
  5041. * @param left defines first quaternion
  5042. * @param right defines second quaternion
  5043. * @param amount defines the gradient to use
  5044. * @param result defines the target quaternion
  5045. */
  5046. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5047. var num2;
  5048. var num3;
  5049. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5050. var flag = false;
  5051. if (num4 < 0) {
  5052. flag = true;
  5053. num4 = -num4;
  5054. }
  5055. if (num4 > 0.999999) {
  5056. num3 = 1 - amount;
  5057. num2 = flag ? -amount : amount;
  5058. }
  5059. else {
  5060. var num5 = Math.acos(num4);
  5061. var num6 = (1.0 / Math.sin(num5));
  5062. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5063. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5064. }
  5065. result.x = (num3 * left.x) + (num2 * right.x);
  5066. result.y = (num3 * left.y) + (num2 * right.y);
  5067. result.z = (num3 * left.z) + (num2 * right.z);
  5068. result.w = (num3 * left.w) + (num2 * right.w);
  5069. };
  5070. /**
  5071. * Interpolate between two quaternions using Hermite interpolation
  5072. * @param value1 defines first quaternion
  5073. * @param tangent1 defines the incoming tangent
  5074. * @param value2 defines second quaternion
  5075. * @param tangent2 defines the outgoing tangent
  5076. * @param amount defines the target quaternion
  5077. * @returns the new interpolated quaternion
  5078. */
  5079. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5080. var squared = amount * amount;
  5081. var cubed = amount * squared;
  5082. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5083. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5084. var part3 = (cubed - (2.0 * squared)) + amount;
  5085. var part4 = cubed - squared;
  5086. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5087. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5088. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5089. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5090. return new Quaternion(x, y, z, w);
  5091. };
  5092. return Quaternion;
  5093. }());
  5094. BABYLON.Quaternion = Quaternion;
  5095. /**
  5096. * Class used to store matrix data (4x4)
  5097. */
  5098. var Matrix = /** @class */ (function () {
  5099. /**
  5100. * Creates an empty matrix (filled with zeros)
  5101. */
  5102. function Matrix() {
  5103. this._isIdentity = false;
  5104. this._isIdentityDirty = true;
  5105. /**
  5106. * Gets or sets the internal data of the matrix
  5107. */
  5108. this.m = new Float32Array(16);
  5109. this._markAsUpdated();
  5110. }
  5111. /** @hidden */
  5112. Matrix.prototype._markAsUpdated = function () {
  5113. this.updateFlag = Matrix._updateFlagSeed++;
  5114. this._isIdentityDirty = true;
  5115. };
  5116. // Properties
  5117. /**
  5118. * Check if the current matrix is indentity
  5119. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5120. * @returns true is the matrix is the identity matrix
  5121. */
  5122. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5123. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5124. if (this._isIdentityDirty) {
  5125. this._isIdentityDirty = false;
  5126. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5127. this._isIdentity = false;
  5128. }
  5129. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5130. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5131. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5132. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5133. this._isIdentity = false;
  5134. }
  5135. else {
  5136. this._isIdentity = true;
  5137. }
  5138. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5139. this._isIdentity = false;
  5140. }
  5141. }
  5142. return this._isIdentity;
  5143. };
  5144. /**
  5145. * Gets the determinant of the matrix
  5146. * @returns the matrix determinant
  5147. */
  5148. Matrix.prototype.determinant = function () {
  5149. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5150. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5151. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5152. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5153. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5154. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5155. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5156. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5157. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5158. };
  5159. // Methods
  5160. /**
  5161. * Returns the matrix as a Float32Array
  5162. * @returns the matrix underlying array
  5163. */
  5164. Matrix.prototype.toArray = function () {
  5165. return this.m;
  5166. };
  5167. /**
  5168. * Returns the matrix as a Float32Array
  5169. * @returns the matrix underlying array.
  5170. */
  5171. Matrix.prototype.asArray = function () {
  5172. return this.toArray();
  5173. };
  5174. /**
  5175. * Inverts the current matrix in place
  5176. * @returns the current inverted matrix
  5177. */
  5178. Matrix.prototype.invert = function () {
  5179. this.invertToRef(this);
  5180. return this;
  5181. };
  5182. /**
  5183. * Sets all the matrix elements to zero
  5184. * @returns the current matrix
  5185. */
  5186. Matrix.prototype.reset = function () {
  5187. for (var index = 0; index < 16; index++) {
  5188. this.m[index] = 0.0;
  5189. }
  5190. this._markAsUpdated();
  5191. return this;
  5192. };
  5193. /**
  5194. * Adds the current matrix with a second one
  5195. * @param other defines the matrix to add
  5196. * @returns a new matrix as the addition of the current matrix and the given one
  5197. */
  5198. Matrix.prototype.add = function (other) {
  5199. var result = new Matrix();
  5200. this.addToRef(other, result);
  5201. return result;
  5202. };
  5203. /**
  5204. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5205. * @param other defines the matrix to add
  5206. * @param result defines the target matrix
  5207. * @returns the current matrix
  5208. */
  5209. Matrix.prototype.addToRef = function (other, result) {
  5210. for (var index = 0; index < 16; index++) {
  5211. result.m[index] = this.m[index] + other.m[index];
  5212. }
  5213. result._markAsUpdated();
  5214. return this;
  5215. };
  5216. /**
  5217. * Adds in place the given matrix to the current matrix
  5218. * @param other defines the second operand
  5219. * @returns the current updated matrix
  5220. */
  5221. Matrix.prototype.addToSelf = function (other) {
  5222. for (var index = 0; index < 16; index++) {
  5223. this.m[index] += other.m[index];
  5224. }
  5225. this._markAsUpdated();
  5226. return this;
  5227. };
  5228. /**
  5229. * Sets the given matrix to the current inverted Matrix
  5230. * @param other defines the target matrix
  5231. * @returns the unmodified current matrix
  5232. */
  5233. Matrix.prototype.invertToRef = function (other) {
  5234. var l1 = this.m[0];
  5235. var l2 = this.m[1];
  5236. var l3 = this.m[2];
  5237. var l4 = this.m[3];
  5238. var l5 = this.m[4];
  5239. var l6 = this.m[5];
  5240. var l7 = this.m[6];
  5241. var l8 = this.m[7];
  5242. var l9 = this.m[8];
  5243. var l10 = this.m[9];
  5244. var l11 = this.m[10];
  5245. var l12 = this.m[11];
  5246. var l13 = this.m[12];
  5247. var l14 = this.m[13];
  5248. var l15 = this.m[14];
  5249. var l16 = this.m[15];
  5250. var l17 = (l11 * l16) - (l12 * l15);
  5251. var l18 = (l10 * l16) - (l12 * l14);
  5252. var l19 = (l10 * l15) - (l11 * l14);
  5253. var l20 = (l9 * l16) - (l12 * l13);
  5254. var l21 = (l9 * l15) - (l11 * l13);
  5255. var l22 = (l9 * l14) - (l10 * l13);
  5256. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5257. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5258. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5259. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5260. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5261. var l28 = (l7 * l16) - (l8 * l15);
  5262. var l29 = (l6 * l16) - (l8 * l14);
  5263. var l30 = (l6 * l15) - (l7 * l14);
  5264. var l31 = (l5 * l16) - (l8 * l13);
  5265. var l32 = (l5 * l15) - (l7 * l13);
  5266. var l33 = (l5 * l14) - (l6 * l13);
  5267. var l34 = (l7 * l12) - (l8 * l11);
  5268. var l35 = (l6 * l12) - (l8 * l10);
  5269. var l36 = (l6 * l11) - (l7 * l10);
  5270. var l37 = (l5 * l12) - (l8 * l9);
  5271. var l38 = (l5 * l11) - (l7 * l9);
  5272. var l39 = (l5 * l10) - (l6 * l9);
  5273. other.m[0] = l23 * l27;
  5274. other.m[4] = l24 * l27;
  5275. other.m[8] = l25 * l27;
  5276. other.m[12] = l26 * l27;
  5277. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5278. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5279. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5280. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5281. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5282. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5283. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5284. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5285. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5286. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5287. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5288. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5289. other._markAsUpdated();
  5290. return this;
  5291. };
  5292. /**
  5293. * Inserts the translation vector (using 3 floats) in the current matrix
  5294. * @param x defines the 1st component of the translation
  5295. * @param y defines the 2nd component of the translation
  5296. * @param z defines the 3rd component of the translation
  5297. * @returns the current updated matrix
  5298. */
  5299. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5300. this.m[12] = x;
  5301. this.m[13] = y;
  5302. this.m[14] = z;
  5303. this._markAsUpdated();
  5304. return this;
  5305. };
  5306. /**
  5307. * Inserts the translation vector in the current matrix
  5308. * @param vector3 defines the translation to insert
  5309. * @returns the current updated matrix
  5310. */
  5311. Matrix.prototype.setTranslation = function (vector3) {
  5312. this.m[12] = vector3.x;
  5313. this.m[13] = vector3.y;
  5314. this.m[14] = vector3.z;
  5315. this._markAsUpdated();
  5316. return this;
  5317. };
  5318. /**
  5319. * Gets the translation value of the current matrix
  5320. * @returns a new Vector3 as the extracted translation from the matrix
  5321. */
  5322. Matrix.prototype.getTranslation = function () {
  5323. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5324. };
  5325. /**
  5326. * Fill a Vector3 with the extracted translation from the matrix
  5327. * @param result defines the Vector3 where to store the translation
  5328. * @returns the current matrix
  5329. */
  5330. Matrix.prototype.getTranslationToRef = function (result) {
  5331. result.x = this.m[12];
  5332. result.y = this.m[13];
  5333. result.z = this.m[14];
  5334. return this;
  5335. };
  5336. /**
  5337. * Remove rotation and scaling part from the matrix
  5338. * @returns the updated matrix
  5339. */
  5340. Matrix.prototype.removeRotationAndScaling = function () {
  5341. this.setRowFromFloats(0, 1, 0, 0, 0);
  5342. this.setRowFromFloats(1, 0, 1, 0, 0);
  5343. this.setRowFromFloats(2, 0, 0, 1, 0);
  5344. return this;
  5345. };
  5346. /**
  5347. * Multiply two matrices
  5348. * @param other defines the second operand
  5349. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5350. */
  5351. Matrix.prototype.multiply = function (other) {
  5352. var result = new Matrix();
  5353. this.multiplyToRef(other, result);
  5354. return result;
  5355. };
  5356. /**
  5357. * Copy the current matrix from the given one
  5358. * @param other defines the source matrix
  5359. * @returns the current updated matrix
  5360. */
  5361. Matrix.prototype.copyFrom = function (other) {
  5362. for (var index = 0; index < 16; index++) {
  5363. this.m[index] = other.m[index];
  5364. }
  5365. this._markAsUpdated();
  5366. return this;
  5367. };
  5368. /**
  5369. * Populates the given array from the starting index with the current matrix values
  5370. * @param array defines the target array
  5371. * @param offset defines the offset in the target array where to start storing values
  5372. * @returns the current matrix
  5373. */
  5374. Matrix.prototype.copyToArray = function (array, offset) {
  5375. if (offset === void 0) { offset = 0; }
  5376. for (var index = 0; index < 16; index++) {
  5377. array[offset + index] = this.m[index];
  5378. }
  5379. return this;
  5380. };
  5381. /**
  5382. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5383. * @param other defines the second operand
  5384. * @param result defines the matrix where to store the multiplication
  5385. * @returns the current matrix
  5386. */
  5387. Matrix.prototype.multiplyToRef = function (other, result) {
  5388. this.multiplyToArray(other, result.m, 0);
  5389. result._markAsUpdated();
  5390. return this;
  5391. };
  5392. /**
  5393. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5394. * @param other defines the second operand
  5395. * @param result defines the array where to store the multiplication
  5396. * @param offset defines the offset in the target array where to start storing values
  5397. * @returns the current matrix
  5398. */
  5399. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5400. var tm0 = this.m[0];
  5401. var tm1 = this.m[1];
  5402. var tm2 = this.m[2];
  5403. var tm3 = this.m[3];
  5404. var tm4 = this.m[4];
  5405. var tm5 = this.m[5];
  5406. var tm6 = this.m[6];
  5407. var tm7 = this.m[7];
  5408. var tm8 = this.m[8];
  5409. var tm9 = this.m[9];
  5410. var tm10 = this.m[10];
  5411. var tm11 = this.m[11];
  5412. var tm12 = this.m[12];
  5413. var tm13 = this.m[13];
  5414. var tm14 = this.m[14];
  5415. var tm15 = this.m[15];
  5416. var om0 = other.m[0];
  5417. var om1 = other.m[1];
  5418. var om2 = other.m[2];
  5419. var om3 = other.m[3];
  5420. var om4 = other.m[4];
  5421. var om5 = other.m[5];
  5422. var om6 = other.m[6];
  5423. var om7 = other.m[7];
  5424. var om8 = other.m[8];
  5425. var om9 = other.m[9];
  5426. var om10 = other.m[10];
  5427. var om11 = other.m[11];
  5428. var om12 = other.m[12];
  5429. var om13 = other.m[13];
  5430. var om14 = other.m[14];
  5431. var om15 = other.m[15];
  5432. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5433. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5434. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5435. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5436. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5437. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5438. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5439. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5440. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5441. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5442. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5443. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5444. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5445. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5446. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5447. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5448. return this;
  5449. };
  5450. /**
  5451. * Check equality between this matrix and a second one
  5452. * @param value defines the second matrix to compare
  5453. * @returns true is the current matrix and the given one values are strictly equal
  5454. */
  5455. Matrix.prototype.equals = function (value) {
  5456. return value &&
  5457. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5458. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5459. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5460. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5461. };
  5462. /**
  5463. * Clone the current matrix
  5464. * @returns a new matrix from the current matrix
  5465. */
  5466. Matrix.prototype.clone = function () {
  5467. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5468. };
  5469. /**
  5470. * Returns the name of the current matrix class
  5471. * @returns the string "Matrix"
  5472. */
  5473. Matrix.prototype.getClassName = function () {
  5474. return "Matrix";
  5475. };
  5476. /**
  5477. * Gets the hash code of the current matrix
  5478. * @returns the hash code
  5479. */
  5480. Matrix.prototype.getHashCode = function () {
  5481. var hash = this.m[0] || 0;
  5482. for (var i = 1; i < 16; i++) {
  5483. hash = (hash * 397) ^ (this.m[i] || 0);
  5484. }
  5485. return hash;
  5486. };
  5487. /**
  5488. * Decomposes the current Matrix into a translation, rotation and scaling components
  5489. * @param scale defines the scale vector3 given as a reference to update
  5490. * @param rotation defines the rotation quaternion given as a reference to update
  5491. * @param translation defines the translation vector3 given as a reference to update
  5492. * @returns true if operation was successful
  5493. */
  5494. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5495. if (translation) {
  5496. translation.x = this.m[12];
  5497. translation.y = this.m[13];
  5498. translation.z = this.m[14];
  5499. }
  5500. scale = scale || MathTmp.Vector3[0];
  5501. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5502. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5503. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5504. if (this.determinant() <= 0) {
  5505. scale.y *= -1;
  5506. }
  5507. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5508. if (rotation) {
  5509. rotation.x = 0;
  5510. rotation.y = 0;
  5511. rotation.z = 0;
  5512. rotation.w = 1;
  5513. }
  5514. return false;
  5515. }
  5516. if (rotation) {
  5517. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5518. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5519. }
  5520. return true;
  5521. };
  5522. /**
  5523. * Gets specific row of the matrix
  5524. * @param index defines the number of the row to get
  5525. * @returns the index-th row of the current matrix as a new Vector4
  5526. */
  5527. Matrix.prototype.getRow = function (index) {
  5528. if (index < 0 || index > 3) {
  5529. return null;
  5530. }
  5531. var i = index * 4;
  5532. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5533. };
  5534. /**
  5535. * Sets the index-th row of the current matrix to the vector4 values
  5536. * @param index defines the number of the row to set
  5537. * @param row defines the target vector4
  5538. * @returns the updated current matrix
  5539. */
  5540. Matrix.prototype.setRow = function (index, row) {
  5541. if (index < 0 || index > 3) {
  5542. return this;
  5543. }
  5544. var i = index * 4;
  5545. this.m[i + 0] = row.x;
  5546. this.m[i + 1] = row.y;
  5547. this.m[i + 2] = row.z;
  5548. this.m[i + 3] = row.w;
  5549. this._markAsUpdated();
  5550. return this;
  5551. };
  5552. /**
  5553. * Compute the transpose of the matrix
  5554. * @returns the new transposed matrix
  5555. */
  5556. Matrix.prototype.transpose = function () {
  5557. return Matrix.Transpose(this);
  5558. };
  5559. /**
  5560. * Compute the transpose of the matrix and store it in a given matrix
  5561. * @param result defines the target matrix
  5562. * @returns the current matrix
  5563. */
  5564. Matrix.prototype.transposeToRef = function (result) {
  5565. Matrix.TransposeToRef(this, result);
  5566. return this;
  5567. };
  5568. /**
  5569. * Sets the index-th row of the current matrix with the given 4 x float values
  5570. * @param index defines the row index
  5571. * @param x defines the x component to set
  5572. * @param y defines the y component to set
  5573. * @param z defines the z component to set
  5574. * @param w defines the w component to set
  5575. * @returns the updated current matrix
  5576. */
  5577. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5578. if (index < 0 || index > 3) {
  5579. return this;
  5580. }
  5581. var i = index * 4;
  5582. this.m[i + 0] = x;
  5583. this.m[i + 1] = y;
  5584. this.m[i + 2] = z;
  5585. this.m[i + 3] = w;
  5586. this._markAsUpdated();
  5587. return this;
  5588. };
  5589. /**
  5590. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5591. * @param scale defines the scale factor
  5592. * @returns a new matrix
  5593. */
  5594. Matrix.prototype.scale = function (scale) {
  5595. var result = new Matrix();
  5596. this.scaleToRef(scale, result);
  5597. return result;
  5598. };
  5599. /**
  5600. * Scale the current matrix values by a factor to a given result matrix
  5601. * @param scale defines the scale factor
  5602. * @param result defines the matrix to store the result
  5603. * @returns the current matrix
  5604. */
  5605. Matrix.prototype.scaleToRef = function (scale, result) {
  5606. for (var index = 0; index < 16; index++) {
  5607. result.m[index] = this.m[index] * scale;
  5608. }
  5609. result._markAsUpdated();
  5610. return this;
  5611. };
  5612. /**
  5613. * Scale the current matrix values by a factor and add the result to a given matrix
  5614. * @param scale defines the scale factor
  5615. * @param result defines the Matrix to store the result
  5616. * @returns the current matrix
  5617. */
  5618. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5619. for (var index = 0; index < 16; index++) {
  5620. result.m[index] += this.m[index] * scale;
  5621. }
  5622. result._markAsUpdated();
  5623. return this;
  5624. };
  5625. /**
  5626. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5627. * @param ref matrix to store the result
  5628. */
  5629. Matrix.prototype.toNormalMatrix = function (ref) {
  5630. this.invertToRef(ref);
  5631. ref.transpose();
  5632. var m = ref.m;
  5633. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5634. };
  5635. /**
  5636. * Gets only rotation part of the current matrix
  5637. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5638. */
  5639. Matrix.prototype.getRotationMatrix = function () {
  5640. var result = Matrix.Identity();
  5641. this.getRotationMatrixToRef(result);
  5642. return result;
  5643. };
  5644. /**
  5645. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5646. * @param result defines the target matrix to store data to
  5647. * @returns the current matrix
  5648. */
  5649. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5650. var m = this.m;
  5651. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5652. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5653. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5654. if (this.determinant() <= 0) {
  5655. sy *= -1;
  5656. }
  5657. if (sx === 0 || sy === 0 || sz === 0) {
  5658. Matrix.IdentityToRef(result);
  5659. }
  5660. else {
  5661. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5662. }
  5663. return this;
  5664. };
  5665. // Statics
  5666. /**
  5667. * Creates a matrix from an array
  5668. * @param array defines the source array
  5669. * @param offset defines an offset in the source array
  5670. * @returns a new Matrix set from the starting index of the given array
  5671. */
  5672. Matrix.FromArray = function (array, offset) {
  5673. var result = new Matrix();
  5674. if (!offset) {
  5675. offset = 0;
  5676. }
  5677. Matrix.FromArrayToRef(array, offset, result);
  5678. return result;
  5679. };
  5680. /**
  5681. * Copy the content of an array into a given matrix
  5682. * @param array defines the source array
  5683. * @param offset defines an offset in the source array
  5684. * @param result defines the target matrix
  5685. */
  5686. Matrix.FromArrayToRef = function (array, offset, result) {
  5687. for (var index = 0; index < 16; index++) {
  5688. result.m[index] = array[index + offset];
  5689. }
  5690. result._markAsUpdated();
  5691. };
  5692. /**
  5693. * Stores an array into a matrix after having multiplied each component by a given factor
  5694. * @param array defines the source array
  5695. * @param offset defines the offset in the source array
  5696. * @param scale defines the scaling factor
  5697. * @param result defines the target matrix
  5698. */
  5699. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5700. for (var index = 0; index < 16; index++) {
  5701. result.m[index] = array[index + offset] * scale;
  5702. }
  5703. result._markAsUpdated();
  5704. };
  5705. /**
  5706. * Stores a list of values (16) inside a given matrix
  5707. * @param initialM11 defines 1st value of 1st row
  5708. * @param initialM12 defines 2nd value of 1st row
  5709. * @param initialM13 defines 3rd value of 1st row
  5710. * @param initialM14 defines 4th value of 1st row
  5711. * @param initialM21 defines 1st value of 2nd row
  5712. * @param initialM22 defines 2nd value of 2nd row
  5713. * @param initialM23 defines 3rd value of 2nd row
  5714. * @param initialM24 defines 4th value of 2nd row
  5715. * @param initialM31 defines 1st value of 3rd row
  5716. * @param initialM32 defines 2nd value of 3rd row
  5717. * @param initialM33 defines 3rd value of 3rd row
  5718. * @param initialM34 defines 4th value of 3rd row
  5719. * @param initialM41 defines 1st value of 4th row
  5720. * @param initialM42 defines 2nd value of 4th row
  5721. * @param initialM43 defines 3rd value of 4th row
  5722. * @param initialM44 defines 4th value of 4th row
  5723. * @param result defines the target matrix
  5724. */
  5725. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5726. result.m[0] = initialM11;
  5727. result.m[1] = initialM12;
  5728. result.m[2] = initialM13;
  5729. result.m[3] = initialM14;
  5730. result.m[4] = initialM21;
  5731. result.m[5] = initialM22;
  5732. result.m[6] = initialM23;
  5733. result.m[7] = initialM24;
  5734. result.m[8] = initialM31;
  5735. result.m[9] = initialM32;
  5736. result.m[10] = initialM33;
  5737. result.m[11] = initialM34;
  5738. result.m[12] = initialM41;
  5739. result.m[13] = initialM42;
  5740. result.m[14] = initialM43;
  5741. result.m[15] = initialM44;
  5742. result._markAsUpdated();
  5743. };
  5744. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5745. /**
  5746. * Gets an identity matrix that must not be updated
  5747. */
  5748. get: function () {
  5749. return Matrix._identityReadOnly;
  5750. },
  5751. enumerable: true,
  5752. configurable: true
  5753. });
  5754. /**
  5755. * Creates new matrix from a list of values (16)
  5756. * @param initialM11 defines 1st value of 1st row
  5757. * @param initialM12 defines 2nd value of 1st row
  5758. * @param initialM13 defines 3rd value of 1st row
  5759. * @param initialM14 defines 4th value of 1st row
  5760. * @param initialM21 defines 1st value of 2nd row
  5761. * @param initialM22 defines 2nd value of 2nd row
  5762. * @param initialM23 defines 3rd value of 2nd row
  5763. * @param initialM24 defines 4th value of 2nd row
  5764. * @param initialM31 defines 1st value of 3rd row
  5765. * @param initialM32 defines 2nd value of 3rd row
  5766. * @param initialM33 defines 3rd value of 3rd row
  5767. * @param initialM34 defines 4th value of 3rd row
  5768. * @param initialM41 defines 1st value of 4th row
  5769. * @param initialM42 defines 2nd value of 4th row
  5770. * @param initialM43 defines 3rd value of 4th row
  5771. * @param initialM44 defines 4th value of 4th row
  5772. * @returns the new matrix
  5773. */
  5774. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5775. var result = new Matrix();
  5776. result.m[0] = initialM11;
  5777. result.m[1] = initialM12;
  5778. result.m[2] = initialM13;
  5779. result.m[3] = initialM14;
  5780. result.m[4] = initialM21;
  5781. result.m[5] = initialM22;
  5782. result.m[6] = initialM23;
  5783. result.m[7] = initialM24;
  5784. result.m[8] = initialM31;
  5785. result.m[9] = initialM32;
  5786. result.m[10] = initialM33;
  5787. result.m[11] = initialM34;
  5788. result.m[12] = initialM41;
  5789. result.m[13] = initialM42;
  5790. result.m[14] = initialM43;
  5791. result.m[15] = initialM44;
  5792. return result;
  5793. };
  5794. /**
  5795. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5796. * @param scale defines the scale vector3
  5797. * @param rotation defines the rotation quaternion
  5798. * @param translation defines the translation vector3
  5799. * @returns a new matrix
  5800. */
  5801. Matrix.Compose = function (scale, rotation, translation) {
  5802. var result = Matrix.Identity();
  5803. Matrix.ComposeToRef(scale, rotation, translation, result);
  5804. return result;
  5805. };
  5806. /**
  5807. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5808. * @param scale defines the scale vector3
  5809. * @param rotation defines the rotation quaternion
  5810. * @param translation defines the translation vector3
  5811. * @param result defines the target matrix
  5812. */
  5813. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5814. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5815. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5816. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5817. result.setTranslation(translation);
  5818. };
  5819. /**
  5820. * Creates a new identity matrix
  5821. * @returns a new identity matrix
  5822. */
  5823. Matrix.Identity = function () {
  5824. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5825. };
  5826. /**
  5827. * Creates a new identity matrix and stores the result in a given matrix
  5828. * @param result defines the target matrix
  5829. */
  5830. Matrix.IdentityToRef = function (result) {
  5831. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5832. };
  5833. /**
  5834. * Creates a new zero matrix
  5835. * @returns a new zero matrix
  5836. */
  5837. Matrix.Zero = function () {
  5838. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5839. };
  5840. /**
  5841. * Creates a new rotation matrix for "angle" radians around the X axis
  5842. * @param angle defines the angle (in radians) to use
  5843. * @return the new matrix
  5844. */
  5845. Matrix.RotationX = function (angle) {
  5846. var result = new Matrix();
  5847. Matrix.RotationXToRef(angle, result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Creates a new matrix as the invert of a given matrix
  5852. * @param source defines the source matrix
  5853. * @returns the new matrix
  5854. */
  5855. Matrix.Invert = function (source) {
  5856. var result = new Matrix();
  5857. source.invertToRef(result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5862. * @param angle defines the angle (in radians) to use
  5863. * @param result defines the target matrix
  5864. */
  5865. Matrix.RotationXToRef = function (angle, result) {
  5866. var s = Math.sin(angle);
  5867. var c = Math.cos(angle);
  5868. result.m[0] = 1.0;
  5869. result.m[15] = 1.0;
  5870. result.m[5] = c;
  5871. result.m[10] = c;
  5872. result.m[9] = -s;
  5873. result.m[6] = s;
  5874. result.m[1] = 0.0;
  5875. result.m[2] = 0.0;
  5876. result.m[3] = 0.0;
  5877. result.m[4] = 0.0;
  5878. result.m[7] = 0.0;
  5879. result.m[8] = 0.0;
  5880. result.m[11] = 0.0;
  5881. result.m[12] = 0.0;
  5882. result.m[13] = 0.0;
  5883. result.m[14] = 0.0;
  5884. result._markAsUpdated();
  5885. };
  5886. /**
  5887. * Creates a new rotation matrix for "angle" radians around the Y axis
  5888. * @param angle defines the angle (in radians) to use
  5889. * @return the new matrix
  5890. */
  5891. Matrix.RotationY = function (angle) {
  5892. var result = new Matrix();
  5893. Matrix.RotationYToRef(angle, result);
  5894. return result;
  5895. };
  5896. /**
  5897. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5898. * @param angle defines the angle (in radians) to use
  5899. * @param result defines the target matrix
  5900. */
  5901. Matrix.RotationYToRef = function (angle, result) {
  5902. var s = Math.sin(angle);
  5903. var c = Math.cos(angle);
  5904. result.m[5] = 1.0;
  5905. result.m[15] = 1.0;
  5906. result.m[0] = c;
  5907. result.m[2] = -s;
  5908. result.m[8] = s;
  5909. result.m[10] = c;
  5910. result.m[1] = 0.0;
  5911. result.m[3] = 0.0;
  5912. result.m[4] = 0.0;
  5913. result.m[6] = 0.0;
  5914. result.m[7] = 0.0;
  5915. result.m[9] = 0.0;
  5916. result.m[11] = 0.0;
  5917. result.m[12] = 0.0;
  5918. result.m[13] = 0.0;
  5919. result.m[14] = 0.0;
  5920. result._markAsUpdated();
  5921. };
  5922. /**
  5923. * Creates a new rotation matrix for "angle" radians around the Z axis
  5924. * @param angle defines the angle (in radians) to use
  5925. * @return the new matrix
  5926. */
  5927. Matrix.RotationZ = function (angle) {
  5928. var result = new Matrix();
  5929. Matrix.RotationZToRef(angle, result);
  5930. return result;
  5931. };
  5932. /**
  5933. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5934. * @param angle defines the angle (in radians) to use
  5935. * @param result defines the target matrix
  5936. */
  5937. Matrix.RotationZToRef = function (angle, result) {
  5938. var s = Math.sin(angle);
  5939. var c = Math.cos(angle);
  5940. result.m[10] = 1.0;
  5941. result.m[15] = 1.0;
  5942. result.m[0] = c;
  5943. result.m[1] = s;
  5944. result.m[4] = -s;
  5945. result.m[5] = c;
  5946. result.m[2] = 0.0;
  5947. result.m[3] = 0.0;
  5948. result.m[6] = 0.0;
  5949. result.m[7] = 0.0;
  5950. result.m[8] = 0.0;
  5951. result.m[9] = 0.0;
  5952. result.m[11] = 0.0;
  5953. result.m[12] = 0.0;
  5954. result.m[13] = 0.0;
  5955. result.m[14] = 0.0;
  5956. result._markAsUpdated();
  5957. };
  5958. /**
  5959. * Creates a new rotation matrix for "angle" radians around the given axis
  5960. * @param axis defines the axis to use
  5961. * @param angle defines the angle (in radians) to use
  5962. * @return the new matrix
  5963. */
  5964. Matrix.RotationAxis = function (axis, angle) {
  5965. var result = Matrix.Zero();
  5966. Matrix.RotationAxisToRef(axis, angle, result);
  5967. return result;
  5968. };
  5969. /**
  5970. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5971. * @param axis defines the axis to use
  5972. * @param angle defines the angle (in radians) to use
  5973. * @param result defines the target matrix
  5974. */
  5975. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5976. var s = Math.sin(-angle);
  5977. var c = Math.cos(-angle);
  5978. var c1 = 1 - c;
  5979. axis.normalize();
  5980. result.m[0] = (axis.x * axis.x) * c1 + c;
  5981. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5982. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5983. result.m[3] = 0.0;
  5984. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5985. result.m[5] = (axis.y * axis.y) * c1 + c;
  5986. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5987. result.m[7] = 0.0;
  5988. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5989. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5990. result.m[10] = (axis.z * axis.z) * c1 + c;
  5991. result.m[11] = 0.0;
  5992. result.m[15] = 1.0;
  5993. result._markAsUpdated();
  5994. };
  5995. /**
  5996. * Creates a rotation matrix
  5997. * @param yaw defines the yaw angle in radians (Y axis)
  5998. * @param pitch defines the pitch angle in radians (X axis)
  5999. * @param roll defines the roll angle in radians (X axis)
  6000. * @returns the new rotation matrix
  6001. */
  6002. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6003. var result = new Matrix();
  6004. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6005. return result;
  6006. };
  6007. /**
  6008. * Creates a rotation matrix and stores it in a given matrix
  6009. * @param yaw defines the yaw angle in radians (Y axis)
  6010. * @param pitch defines the pitch angle in radians (X axis)
  6011. * @param roll defines the roll angle in radians (X axis)
  6012. * @param result defines the target matrix
  6013. */
  6014. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6015. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6016. this._tempQuaternion.toRotationMatrix(result);
  6017. };
  6018. /**
  6019. * Creates a scaling matrix
  6020. * @param x defines the scale factor on X axis
  6021. * @param y defines the scale factor on Y axis
  6022. * @param z defines the scale factor on Z axis
  6023. * @returns the new matrix
  6024. */
  6025. Matrix.Scaling = function (x, y, z) {
  6026. var result = Matrix.Zero();
  6027. Matrix.ScalingToRef(x, y, z, result);
  6028. return result;
  6029. };
  6030. /**
  6031. * Creates a scaling matrix and stores it in a given matrix
  6032. * @param x defines the scale factor on X axis
  6033. * @param y defines the scale factor on Y axis
  6034. * @param z defines the scale factor on Z axis
  6035. * @param result defines the target matrix
  6036. */
  6037. Matrix.ScalingToRef = function (x, y, z, result) {
  6038. result.m[0] = x;
  6039. result.m[1] = 0.0;
  6040. result.m[2] = 0.0;
  6041. result.m[3] = 0.0;
  6042. result.m[4] = 0.0;
  6043. result.m[5] = y;
  6044. result.m[6] = 0.0;
  6045. result.m[7] = 0.0;
  6046. result.m[8] = 0.0;
  6047. result.m[9] = 0.0;
  6048. result.m[10] = z;
  6049. result.m[11] = 0.0;
  6050. result.m[12] = 0.0;
  6051. result.m[13] = 0.0;
  6052. result.m[14] = 0.0;
  6053. result.m[15] = 1.0;
  6054. result._markAsUpdated();
  6055. };
  6056. /**
  6057. * Creates a translation matrix
  6058. * @param x defines the translation on X axis
  6059. * @param y defines the translation on Y axis
  6060. * @param z defines the translationon Z axis
  6061. * @returns the new matrix
  6062. */
  6063. Matrix.Translation = function (x, y, z) {
  6064. var result = Matrix.Identity();
  6065. Matrix.TranslationToRef(x, y, z, result);
  6066. return result;
  6067. };
  6068. /**
  6069. * Creates a translation matrix and stores it in a given matrix
  6070. * @param x defines the translation on X axis
  6071. * @param y defines the translation on Y axis
  6072. * @param z defines the translationon Z axis
  6073. * @param result defines the target matrix
  6074. */
  6075. Matrix.TranslationToRef = function (x, y, z, result) {
  6076. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6077. };
  6078. /**
  6079. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6080. * @param startValue defines the start value
  6081. * @param endValue defines the end value
  6082. * @param gradient defines the gradient factor
  6083. * @returns the new matrix
  6084. */
  6085. Matrix.Lerp = function (startValue, endValue, gradient) {
  6086. var result = Matrix.Zero();
  6087. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6088. return result;
  6089. };
  6090. /**
  6091. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6092. * @param startValue defines the start value
  6093. * @param endValue defines the end value
  6094. * @param gradient defines the gradient factor
  6095. * @param result defines the Matrix object where to store data
  6096. */
  6097. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6098. for (var index = 0; index < 16; index++) {
  6099. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6100. }
  6101. result._markAsUpdated();
  6102. };
  6103. /**
  6104. * Builds a new matrix whose values are computed by:
  6105. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6106. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6107. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6108. * @param startValue defines the first matrix
  6109. * @param endValue defines the second matrix
  6110. * @param gradient defines the gradient between the two matrices
  6111. * @returns the new matrix
  6112. */
  6113. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6114. var result = Matrix.Zero();
  6115. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6116. return result;
  6117. };
  6118. /**
  6119. * Update a matrix to values which are computed by:
  6120. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6121. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6122. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6123. * @param startValue defines the first matrix
  6124. * @param endValue defines the second matrix
  6125. * @param gradient defines the gradient between the two matrices
  6126. * @param result defines the target matrix
  6127. */
  6128. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6129. var startScale = MathTmp.Vector3[0];
  6130. var startRotation = MathTmp.Quaternion[0];
  6131. var startTranslation = MathTmp.Vector3[1];
  6132. startValue.decompose(startScale, startRotation, startTranslation);
  6133. var endScale = MathTmp.Vector3[2];
  6134. var endRotation = MathTmp.Quaternion[1];
  6135. var endTranslation = MathTmp.Vector3[3];
  6136. endValue.decompose(endScale, endRotation, endTranslation);
  6137. var resultScale = MathTmp.Vector3[4];
  6138. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6139. var resultRotation = MathTmp.Quaternion[2];
  6140. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6141. var resultTranslation = MathTmp.Vector3[5];
  6142. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6143. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6144. };
  6145. /**
  6146. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6147. * This function works in left handed mode
  6148. * @param eye defines the final position of the entity
  6149. * @param target defines where the entity should look at
  6150. * @param up defines the up vector for the entity
  6151. * @returns the new matrix
  6152. */
  6153. Matrix.LookAtLH = function (eye, target, up) {
  6154. var result = Matrix.Zero();
  6155. Matrix.LookAtLHToRef(eye, target, up, result);
  6156. return result;
  6157. };
  6158. /**
  6159. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6160. * This function works in left handed mode
  6161. * @param eye defines the final position of the entity
  6162. * @param target defines where the entity should look at
  6163. * @param up defines the up vector for the entity
  6164. * @param result defines the target matrix
  6165. */
  6166. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6167. // Z axis
  6168. target.subtractToRef(eye, this._zAxis);
  6169. this._zAxis.normalize();
  6170. // X axis
  6171. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6172. if (this._xAxis.lengthSquared() === 0) {
  6173. this._xAxis.x = 1.0;
  6174. }
  6175. else {
  6176. this._xAxis.normalize();
  6177. }
  6178. // Y axis
  6179. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6180. this._yAxis.normalize();
  6181. // Eye angles
  6182. var ex = -Vector3.Dot(this._xAxis, eye);
  6183. var ey = -Vector3.Dot(this._yAxis, eye);
  6184. var ez = -Vector3.Dot(this._zAxis, eye);
  6185. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6186. };
  6187. /**
  6188. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6189. * This function works in right handed mode
  6190. * @param eye defines the final position of the entity
  6191. * @param target defines where the entity should look at
  6192. * @param up defines the up vector for the entity
  6193. * @returns the new matrix
  6194. */
  6195. Matrix.LookAtRH = function (eye, target, up) {
  6196. var result = Matrix.Zero();
  6197. Matrix.LookAtRHToRef(eye, target, up, result);
  6198. return result;
  6199. };
  6200. /**
  6201. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6202. * This function works in right handed mode
  6203. * @param eye defines the final position of the entity
  6204. * @param target defines where the entity should look at
  6205. * @param up defines the up vector for the entity
  6206. * @param result defines the target matrix
  6207. */
  6208. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6209. // Z axis
  6210. eye.subtractToRef(target, this._zAxis);
  6211. this._zAxis.normalize();
  6212. // X axis
  6213. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6214. if (this._xAxis.lengthSquared() === 0) {
  6215. this._xAxis.x = 1.0;
  6216. }
  6217. else {
  6218. this._xAxis.normalize();
  6219. }
  6220. // Y axis
  6221. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6222. this._yAxis.normalize();
  6223. // Eye angles
  6224. var ex = -Vector3.Dot(this._xAxis, eye);
  6225. var ey = -Vector3.Dot(this._yAxis, eye);
  6226. var ez = -Vector3.Dot(this._zAxis, eye);
  6227. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6228. };
  6229. /**
  6230. * Create a left-handed orthographic projection matrix
  6231. * @param width defines the viewport width
  6232. * @param height defines the viewport height
  6233. * @param znear defines the near clip plane
  6234. * @param zfar defines the far clip plane
  6235. * @returns a new matrix as a left-handed orthographic projection matrix
  6236. */
  6237. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6238. var matrix = Matrix.Zero();
  6239. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6240. return matrix;
  6241. };
  6242. /**
  6243. * Store a left-handed orthographic projection to a given matrix
  6244. * @param width defines the viewport width
  6245. * @param height defines the viewport height
  6246. * @param znear defines the near clip plane
  6247. * @param zfar defines the far clip plane
  6248. * @param result defines the target matrix
  6249. */
  6250. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6251. var n = znear;
  6252. var f = zfar;
  6253. var a = 2.0 / width;
  6254. var b = 2.0 / height;
  6255. var c = 2.0 / (f - n);
  6256. var d = -(f + n) / (f - n);
  6257. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6258. };
  6259. /**
  6260. * Create a left-handed orthographic projection matrix
  6261. * @param left defines the viewport left coordinate
  6262. * @param right defines the viewport right coordinate
  6263. * @param bottom defines the viewport bottom coordinate
  6264. * @param top defines the viewport top coordinate
  6265. * @param znear defines the near clip plane
  6266. * @param zfar defines the far clip plane
  6267. * @returns a new matrix as a left-handed orthographic projection matrix
  6268. */
  6269. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6270. var matrix = Matrix.Zero();
  6271. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6272. return matrix;
  6273. };
  6274. /**
  6275. * Stores a left-handed orthographic projection into a given matrix
  6276. * @param left defines the viewport left coordinate
  6277. * @param right defines the viewport right coordinate
  6278. * @param bottom defines the viewport bottom coordinate
  6279. * @param top defines the viewport top coordinate
  6280. * @param znear defines the near clip plane
  6281. * @param zfar defines the far clip plane
  6282. * @param result defines the target matrix
  6283. */
  6284. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6285. var n = znear;
  6286. var f = zfar;
  6287. var a = 2.0 / (right - left);
  6288. var b = 2.0 / (top - bottom);
  6289. var c = 2.0 / (f - n);
  6290. var d = -(f + n) / (f - n);
  6291. var i0 = (left + right) / (left - right);
  6292. var i1 = (top + bottom) / (bottom - top);
  6293. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6294. };
  6295. /**
  6296. * Creates a right-handed orthographic projection matrix
  6297. * @param left defines the viewport left coordinate
  6298. * @param right defines the viewport right coordinate
  6299. * @param bottom defines the viewport bottom coordinate
  6300. * @param top defines the viewport top coordinate
  6301. * @param znear defines the near clip plane
  6302. * @param zfar defines the far clip plane
  6303. * @returns a new matrix as a right-handed orthographic projection matrix
  6304. */
  6305. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6306. var matrix = Matrix.Zero();
  6307. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6308. return matrix;
  6309. };
  6310. /**
  6311. * Stores a right-handed orthographic projection into a given matrix
  6312. * @param left defines the viewport left coordinate
  6313. * @param right defines the viewport right coordinate
  6314. * @param bottom defines the viewport bottom coordinate
  6315. * @param top defines the viewport top coordinate
  6316. * @param znear defines the near clip plane
  6317. * @param zfar defines the far clip plane
  6318. * @param result defines the target matrix
  6319. */
  6320. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6321. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6322. result.m[10] *= -1.0;
  6323. };
  6324. /**
  6325. * Creates a left-handed perspective projection matrix
  6326. * @param width defines the viewport width
  6327. * @param height defines the viewport height
  6328. * @param znear defines the near clip plane
  6329. * @param zfar defines the far clip plane
  6330. * @returns a new matrix as a left-handed perspective projection matrix
  6331. */
  6332. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6333. var matrix = Matrix.Zero();
  6334. var n = znear;
  6335. var f = zfar;
  6336. var a = 2.0 * n / width;
  6337. var b = 2.0 * n / height;
  6338. var c = (f + n) / (f - n);
  6339. var d = -2.0 * f * n / (f - n);
  6340. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6341. return matrix;
  6342. };
  6343. /**
  6344. * Creates a left-handed perspective projection matrix
  6345. * @param fov defines the horizontal field of view
  6346. * @param aspect defines the aspect ratio
  6347. * @param znear defines the near clip plane
  6348. * @param zfar defines the far clip plane
  6349. * @returns a new matrix as a left-handed perspective projection matrix
  6350. */
  6351. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6352. var matrix = Matrix.Zero();
  6353. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6354. return matrix;
  6355. };
  6356. /**
  6357. * Stores a left-handed perspective projection into a given matrix
  6358. * @param fov defines the horizontal field of view
  6359. * @param aspect defines the aspect ratio
  6360. * @param znear defines the near clip plane
  6361. * @param zfar defines the far clip plane
  6362. * @param result defines the target matrix
  6363. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6364. */
  6365. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6366. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6367. var n = znear;
  6368. var f = zfar;
  6369. var t = 1.0 / (Math.tan(fov * 0.5));
  6370. var a = isVerticalFovFixed ? (t / aspect) : t;
  6371. var b = isVerticalFovFixed ? t : (t * aspect);
  6372. var c = (f + n) / (f - n);
  6373. var d = -2.0 * f * n / (f - n);
  6374. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6375. };
  6376. /**
  6377. * Creates a right-handed perspective projection matrix
  6378. * @param fov defines the horizontal field of view
  6379. * @param aspect defines the aspect ratio
  6380. * @param znear defines the near clip plane
  6381. * @param zfar defines the far clip plane
  6382. * @returns a new matrix as a right-handed perspective projection matrix
  6383. */
  6384. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6385. var matrix = Matrix.Zero();
  6386. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6387. return matrix;
  6388. };
  6389. /**
  6390. * Stores a right-handed perspective projection into a given matrix
  6391. * @param fov defines the horizontal field of view
  6392. * @param aspect defines the aspect ratio
  6393. * @param znear defines the near clip plane
  6394. * @param zfar defines the far clip plane
  6395. * @param result defines the target matrix
  6396. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6397. */
  6398. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6399. //alternatively this could be expressed as:
  6400. // m = PerspectiveFovLHToRef
  6401. // m[10] *= -1.0;
  6402. // m[11] *= -1.0;
  6403. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6404. var n = znear;
  6405. var f = zfar;
  6406. var t = 1.0 / (Math.tan(fov * 0.5));
  6407. var a = isVerticalFovFixed ? (t / aspect) : t;
  6408. var b = isVerticalFovFixed ? t : (t * aspect);
  6409. var c = -(f + n) / (f - n);
  6410. var d = -2 * f * n / (f - n);
  6411. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6412. };
  6413. /**
  6414. * Stores a perspective projection for WebVR info a given matrix
  6415. * @param fov defines the field of view
  6416. * @param znear defines the near clip plane
  6417. * @param zfar defines the far clip plane
  6418. * @param result defines the target matrix
  6419. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6420. */
  6421. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6422. if (rightHanded === void 0) { rightHanded = false; }
  6423. var rightHandedFactor = rightHanded ? -1 : 1;
  6424. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6425. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6426. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6427. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6428. var xScale = 2.0 / (leftTan + rightTan);
  6429. var yScale = 2.0 / (upTan + downTan);
  6430. result.m[0] = xScale;
  6431. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6432. result.m[5] = yScale;
  6433. result.m[6] = result.m[7] = 0.0;
  6434. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6435. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6436. result.m[10] = -zfar / (znear - zfar);
  6437. result.m[11] = 1.0 * rightHandedFactor;
  6438. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6439. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6440. result._markAsUpdated();
  6441. };
  6442. /**
  6443. * Computes a complete transformation matrix
  6444. * @param viewport defines the viewport to use
  6445. * @param world defines the world matrix
  6446. * @param view defines the view matrix
  6447. * @param projection defines the projection matrix
  6448. * @param zmin defines the near clip plane
  6449. * @param zmax defines the far clip plane
  6450. * @returns the transformation matrix
  6451. */
  6452. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6453. var cw = viewport.width;
  6454. var ch = viewport.height;
  6455. var cx = viewport.x;
  6456. var cy = viewport.y;
  6457. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6458. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6459. };
  6460. /**
  6461. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6462. * @param matrix defines the matrix to use
  6463. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6464. */
  6465. Matrix.GetAsMatrix2x2 = function (matrix) {
  6466. return new Float32Array([
  6467. matrix.m[0], matrix.m[1],
  6468. matrix.m[4], matrix.m[5]
  6469. ]);
  6470. };
  6471. /**
  6472. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6473. * @param matrix defines the matrix to use
  6474. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6475. */
  6476. Matrix.GetAsMatrix3x3 = function (matrix) {
  6477. return new Float32Array([
  6478. matrix.m[0], matrix.m[1], matrix.m[2],
  6479. matrix.m[4], matrix.m[5], matrix.m[6],
  6480. matrix.m[8], matrix.m[9], matrix.m[10]
  6481. ]);
  6482. };
  6483. /**
  6484. * Compute the transpose of a given matrix
  6485. * @param matrix defines the matrix to transpose
  6486. * @returns the new matrix
  6487. */
  6488. Matrix.Transpose = function (matrix) {
  6489. var result = new Matrix();
  6490. Matrix.TransposeToRef(matrix, result);
  6491. return result;
  6492. };
  6493. /**
  6494. * Compute the transpose of a matrix and store it in a target matrix
  6495. * @param matrix defines the matrix to transpose
  6496. * @param result defines the target matrix
  6497. */
  6498. Matrix.TransposeToRef = function (matrix, result) {
  6499. result.m[0] = matrix.m[0];
  6500. result.m[1] = matrix.m[4];
  6501. result.m[2] = matrix.m[8];
  6502. result.m[3] = matrix.m[12];
  6503. result.m[4] = matrix.m[1];
  6504. result.m[5] = matrix.m[5];
  6505. result.m[6] = matrix.m[9];
  6506. result.m[7] = matrix.m[13];
  6507. result.m[8] = matrix.m[2];
  6508. result.m[9] = matrix.m[6];
  6509. result.m[10] = matrix.m[10];
  6510. result.m[11] = matrix.m[14];
  6511. result.m[12] = matrix.m[3];
  6512. result.m[13] = matrix.m[7];
  6513. result.m[14] = matrix.m[11];
  6514. result.m[15] = matrix.m[15];
  6515. };
  6516. /**
  6517. * Computes a reflection matrix from a plane
  6518. * @param plane defines the reflection plane
  6519. * @returns a new matrix
  6520. */
  6521. Matrix.Reflection = function (plane) {
  6522. var matrix = new Matrix();
  6523. Matrix.ReflectionToRef(plane, matrix);
  6524. return matrix;
  6525. };
  6526. /**
  6527. * Computes a reflection matrix from a plane
  6528. * @param plane defines the reflection plane
  6529. * @param result defines the target matrix
  6530. */
  6531. Matrix.ReflectionToRef = function (plane, result) {
  6532. plane.normalize();
  6533. var x = plane.normal.x;
  6534. var y = plane.normal.y;
  6535. var z = plane.normal.z;
  6536. var temp = -2 * x;
  6537. var temp2 = -2 * y;
  6538. var temp3 = -2 * z;
  6539. result.m[0] = (temp * x) + 1;
  6540. result.m[1] = temp2 * x;
  6541. result.m[2] = temp3 * x;
  6542. result.m[3] = 0.0;
  6543. result.m[4] = temp * y;
  6544. result.m[5] = (temp2 * y) + 1;
  6545. result.m[6] = temp3 * y;
  6546. result.m[7] = 0.0;
  6547. result.m[8] = temp * z;
  6548. result.m[9] = temp2 * z;
  6549. result.m[10] = (temp3 * z) + 1;
  6550. result.m[11] = 0.0;
  6551. result.m[12] = temp * plane.d;
  6552. result.m[13] = temp2 * plane.d;
  6553. result.m[14] = temp3 * plane.d;
  6554. result.m[15] = 1.0;
  6555. result._markAsUpdated();
  6556. };
  6557. /**
  6558. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6559. * @param xaxis defines the value of the 1st axis
  6560. * @param yaxis defines the value of the 2nd axis
  6561. * @param zaxis defines the value of the 3rd axis
  6562. * @param result defines the target matrix
  6563. */
  6564. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6565. result.m[0] = xaxis.x;
  6566. result.m[1] = xaxis.y;
  6567. result.m[2] = xaxis.z;
  6568. result.m[3] = 0.0;
  6569. result.m[4] = yaxis.x;
  6570. result.m[5] = yaxis.y;
  6571. result.m[6] = yaxis.z;
  6572. result.m[7] = 0.0;
  6573. result.m[8] = zaxis.x;
  6574. result.m[9] = zaxis.y;
  6575. result.m[10] = zaxis.z;
  6576. result.m[11] = 0.0;
  6577. result.m[12] = 0.0;
  6578. result.m[13] = 0.0;
  6579. result.m[14] = 0.0;
  6580. result.m[15] = 1.0;
  6581. result._markAsUpdated();
  6582. };
  6583. /**
  6584. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6585. * @param quat defines the quaternion to use
  6586. * @param result defines the target matrix
  6587. */
  6588. Matrix.FromQuaternionToRef = function (quat, result) {
  6589. var xx = quat.x * quat.x;
  6590. var yy = quat.y * quat.y;
  6591. var zz = quat.z * quat.z;
  6592. var xy = quat.x * quat.y;
  6593. var zw = quat.z * quat.w;
  6594. var zx = quat.z * quat.x;
  6595. var yw = quat.y * quat.w;
  6596. var yz = quat.y * quat.z;
  6597. var xw = quat.x * quat.w;
  6598. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6599. result.m[1] = 2.0 * (xy + zw);
  6600. result.m[2] = 2.0 * (zx - yw);
  6601. result.m[3] = 0.0;
  6602. result.m[4] = 2.0 * (xy - zw);
  6603. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6604. result.m[6] = 2.0 * (yz + xw);
  6605. result.m[7] = 0.0;
  6606. result.m[8] = 2.0 * (zx + yw);
  6607. result.m[9] = 2.0 * (yz - xw);
  6608. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6609. result.m[11] = 0.0;
  6610. result.m[12] = 0.0;
  6611. result.m[13] = 0.0;
  6612. result.m[14] = 0.0;
  6613. result.m[15] = 1.0;
  6614. result._markAsUpdated();
  6615. };
  6616. Matrix._tempQuaternion = new Quaternion();
  6617. Matrix._xAxis = Vector3.Zero();
  6618. Matrix._yAxis = Vector3.Zero();
  6619. Matrix._zAxis = Vector3.Zero();
  6620. Matrix._updateFlagSeed = 0;
  6621. Matrix._identityReadOnly = Matrix.Identity();
  6622. return Matrix;
  6623. }());
  6624. BABYLON.Matrix = Matrix;
  6625. var Plane = /** @class */ (function () {
  6626. /**
  6627. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6628. */
  6629. function Plane(a, b, c, d) {
  6630. this.normal = new Vector3(a, b, c);
  6631. this.d = d;
  6632. }
  6633. /**
  6634. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6635. */
  6636. Plane.prototype.asArray = function () {
  6637. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6638. };
  6639. // Methods
  6640. /**
  6641. * Returns a new plane copied from the current Plane.
  6642. */
  6643. Plane.prototype.clone = function () {
  6644. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6645. };
  6646. /**
  6647. * Returns the string "Plane".
  6648. */
  6649. Plane.prototype.getClassName = function () {
  6650. return "Plane";
  6651. };
  6652. /**
  6653. * Returns the Plane hash code.
  6654. */
  6655. Plane.prototype.getHashCode = function () {
  6656. var hash = this.normal.getHashCode();
  6657. hash = (hash * 397) ^ (this.d || 0);
  6658. return hash;
  6659. };
  6660. /**
  6661. * Normalize the current Plane in place.
  6662. * Returns the updated Plane.
  6663. */
  6664. Plane.prototype.normalize = function () {
  6665. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6666. var magnitude = 0.0;
  6667. if (norm !== 0) {
  6668. magnitude = 1.0 / norm;
  6669. }
  6670. this.normal.x *= magnitude;
  6671. this.normal.y *= magnitude;
  6672. this.normal.z *= magnitude;
  6673. this.d *= magnitude;
  6674. return this;
  6675. };
  6676. /**
  6677. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6678. */
  6679. Plane.prototype.transform = function (transformation) {
  6680. var transposedMatrix = Matrix.Transpose(transformation);
  6681. var x = this.normal.x;
  6682. var y = this.normal.y;
  6683. var z = this.normal.z;
  6684. var d = this.d;
  6685. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6686. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6687. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6688. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6689. return new Plane(normalX, normalY, normalZ, finalD);
  6690. };
  6691. /**
  6692. * Returns the dot product (float) of the point coordinates and the plane normal.
  6693. */
  6694. Plane.prototype.dotCoordinate = function (point) {
  6695. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6696. };
  6697. /**
  6698. * Updates the current Plane from the plane defined by the three given points.
  6699. * Returns the updated Plane.
  6700. */
  6701. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6702. var x1 = point2.x - point1.x;
  6703. var y1 = point2.y - point1.y;
  6704. var z1 = point2.z - point1.z;
  6705. var x2 = point3.x - point1.x;
  6706. var y2 = point3.y - point1.y;
  6707. var z2 = point3.z - point1.z;
  6708. var yz = (y1 * z2) - (z1 * y2);
  6709. var xz = (z1 * x2) - (x1 * z2);
  6710. var xy = (x1 * y2) - (y1 * x2);
  6711. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6712. var invPyth;
  6713. if (pyth !== 0) {
  6714. invPyth = 1.0 / pyth;
  6715. }
  6716. else {
  6717. invPyth = 0.0;
  6718. }
  6719. this.normal.x = yz * invPyth;
  6720. this.normal.y = xz * invPyth;
  6721. this.normal.z = xy * invPyth;
  6722. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6723. return this;
  6724. };
  6725. /**
  6726. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6727. */
  6728. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6729. var dot = Vector3.Dot(this.normal, direction);
  6730. return (dot <= epsilon);
  6731. };
  6732. /**
  6733. * Returns the signed distance (float) from the given point to the Plane.
  6734. */
  6735. Plane.prototype.signedDistanceTo = function (point) {
  6736. return Vector3.Dot(point, this.normal) + this.d;
  6737. };
  6738. // Statics
  6739. /**
  6740. * Returns a new Plane from the given array.
  6741. */
  6742. Plane.FromArray = function (array) {
  6743. return new Plane(array[0], array[1], array[2], array[3]);
  6744. };
  6745. /**
  6746. * Returns a new Plane defined by the three given points.
  6747. */
  6748. Plane.FromPoints = function (point1, point2, point3) {
  6749. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6750. result.copyFromPoints(point1, point2, point3);
  6751. return result;
  6752. };
  6753. /**
  6754. * Returns a new Plane the normal vector to this plane at the given origin point.
  6755. * Note : the vector "normal" is updated because normalized.
  6756. */
  6757. Plane.FromPositionAndNormal = function (origin, normal) {
  6758. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6759. normal.normalize();
  6760. result.normal = normal;
  6761. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6766. */
  6767. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6768. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6769. return Vector3.Dot(point, normal) + d;
  6770. };
  6771. return Plane;
  6772. }());
  6773. BABYLON.Plane = Plane;
  6774. var Viewport = /** @class */ (function () {
  6775. /**
  6776. * Creates a Viewport object located at (x, y) and sized (width, height).
  6777. */
  6778. function Viewport(x, y, width, height) {
  6779. this.x = x;
  6780. this.y = y;
  6781. this.width = width;
  6782. this.height = height;
  6783. }
  6784. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6785. if (renderWidthOrEngine.getRenderWidth) {
  6786. var engine = renderWidthOrEngine;
  6787. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6788. }
  6789. var renderWidth = renderWidthOrEngine;
  6790. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6791. };
  6792. /**
  6793. * Returns a new Viewport copied from the current one.
  6794. */
  6795. Viewport.prototype.clone = function () {
  6796. return new Viewport(this.x, this.y, this.width, this.height);
  6797. };
  6798. return Viewport;
  6799. }());
  6800. BABYLON.Viewport = Viewport;
  6801. var Frustum = /** @class */ (function () {
  6802. function Frustum() {
  6803. }
  6804. /**
  6805. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6806. */
  6807. Frustum.GetPlanes = function (transform) {
  6808. var frustumPlanes = [];
  6809. for (var index = 0; index < 6; index++) {
  6810. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6811. }
  6812. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6813. return frustumPlanes;
  6814. };
  6815. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6816. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6817. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6818. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6819. frustumPlane.d = transform.m[15] + transform.m[14];
  6820. frustumPlane.normalize();
  6821. };
  6822. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6823. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6824. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6825. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6826. frustumPlane.d = transform.m[15] - transform.m[14];
  6827. frustumPlane.normalize();
  6828. };
  6829. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6830. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6831. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6832. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6833. frustumPlane.d = transform.m[15] + transform.m[12];
  6834. frustumPlane.normalize();
  6835. };
  6836. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6837. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6838. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6839. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6840. frustumPlane.d = transform.m[15] - transform.m[12];
  6841. frustumPlane.normalize();
  6842. };
  6843. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6844. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6845. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6846. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6847. frustumPlane.d = transform.m[15] - transform.m[13];
  6848. frustumPlane.normalize();
  6849. };
  6850. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6851. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6852. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6853. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6854. frustumPlane.d = transform.m[15] + transform.m[13];
  6855. frustumPlane.normalize();
  6856. };
  6857. /**
  6858. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6859. */
  6860. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6861. // Near
  6862. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6863. // Far
  6864. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6865. // Left
  6866. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6867. // Right
  6868. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6869. // Top
  6870. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6871. // Bottom
  6872. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6873. };
  6874. return Frustum;
  6875. }());
  6876. BABYLON.Frustum = Frustum;
  6877. /** Defines supported spaces */
  6878. var Space;
  6879. (function (Space) {
  6880. /** Local (object) space */
  6881. Space[Space["LOCAL"] = 0] = "LOCAL";
  6882. /** World space */
  6883. Space[Space["WORLD"] = 1] = "WORLD";
  6884. /** Bone space */
  6885. Space[Space["BONE"] = 2] = "BONE";
  6886. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6887. /** Defines the 3 main axes */
  6888. var Axis = /** @class */ (function () {
  6889. function Axis() {
  6890. }
  6891. /** X axis */
  6892. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6893. /** Y axis */
  6894. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6895. /** Z axis */
  6896. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6897. return Axis;
  6898. }());
  6899. BABYLON.Axis = Axis;
  6900. ;
  6901. var BezierCurve = /** @class */ (function () {
  6902. function BezierCurve() {
  6903. }
  6904. /**
  6905. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6906. */
  6907. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6908. // Extract X (which is equal to time here)
  6909. var f0 = 1 - 3 * x2 + 3 * x1;
  6910. var f1 = 3 * x2 - 6 * x1;
  6911. var f2 = 3 * x1;
  6912. var refinedT = t;
  6913. for (var i = 0; i < 5; i++) {
  6914. var refinedT2 = refinedT * refinedT;
  6915. var refinedT3 = refinedT2 * refinedT;
  6916. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6917. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6918. refinedT -= (x - t) * slope;
  6919. refinedT = Math.min(1, Math.max(0, refinedT));
  6920. }
  6921. // Resolve cubic bezier for the given x
  6922. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6923. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6924. Math.pow(refinedT, 3);
  6925. };
  6926. return BezierCurve;
  6927. }());
  6928. BABYLON.BezierCurve = BezierCurve;
  6929. /**
  6930. * Defines potential orientation for back face culling
  6931. */
  6932. var Orientation;
  6933. (function (Orientation) {
  6934. /**
  6935. * Clockwise
  6936. */
  6937. Orientation[Orientation["CW"] = 0] = "CW";
  6938. /** Counter clockwise */
  6939. Orientation[Orientation["CCW"] = 1] = "CCW";
  6940. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6941. /**
  6942. * Defines angle representation
  6943. */
  6944. var Angle = /** @class */ (function () {
  6945. /**
  6946. * Creates an Angle object of "radians" radians (float).
  6947. */
  6948. function Angle(radians) {
  6949. this._radians = radians;
  6950. if (this._radians < 0.0)
  6951. this._radians += (2.0 * Math.PI);
  6952. }
  6953. /**
  6954. * Get value in degrees
  6955. * @returns the Angle value in degrees (float)
  6956. */
  6957. Angle.prototype.degrees = function () {
  6958. return this._radians * 180.0 / Math.PI;
  6959. };
  6960. /**
  6961. * Get value in radians
  6962. * @returns the Angle value in radians (float)
  6963. */
  6964. Angle.prototype.radians = function () {
  6965. return this._radians;
  6966. };
  6967. /**
  6968. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6969. * @param a defines first vector
  6970. * @param b defines second vector
  6971. * @returns a new Angle
  6972. */
  6973. Angle.BetweenTwoPoints = function (a, b) {
  6974. var delta = b.subtract(a);
  6975. var theta = Math.atan2(delta.y, delta.x);
  6976. return new Angle(theta);
  6977. };
  6978. /**
  6979. * Gets a new Angle object from the given float in radians
  6980. * @param radians defines the angle value in radians
  6981. * @returns a new Angle
  6982. */
  6983. Angle.FromRadians = function (radians) {
  6984. return new Angle(radians);
  6985. };
  6986. /**
  6987. * Gets a new Angle object from the given float in degrees
  6988. * @param degrees defines the angle value in degrees
  6989. * @returns a new Angle
  6990. */
  6991. Angle.FromDegrees = function (degrees) {
  6992. return new Angle(degrees * Math.PI / 180.0);
  6993. };
  6994. return Angle;
  6995. }());
  6996. BABYLON.Angle = Angle;
  6997. var Arc2 = /** @class */ (function () {
  6998. /**
  6999. * Creates an Arc object from the three given points : start, middle and end.
  7000. */
  7001. function Arc2(startPoint, midPoint, endPoint) {
  7002. this.startPoint = startPoint;
  7003. this.midPoint = midPoint;
  7004. this.endPoint = endPoint;
  7005. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7006. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7007. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7008. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7009. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  7010. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7011. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7012. var a1 = this.startAngle.degrees();
  7013. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7014. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7015. // angles correction
  7016. if (a2 - a1 > +180.0)
  7017. a2 -= 360.0;
  7018. if (a2 - a1 < -180.0)
  7019. a2 += 360.0;
  7020. if (a3 - a2 > +180.0)
  7021. a3 -= 360.0;
  7022. if (a3 - a2 < -180.0)
  7023. a3 += 360.0;
  7024. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7025. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7026. }
  7027. return Arc2;
  7028. }());
  7029. BABYLON.Arc2 = Arc2;
  7030. var Path2 = /** @class */ (function () {
  7031. /**
  7032. * Creates a Path2 object from the starting 2D coordinates x and y.
  7033. */
  7034. function Path2(x, y) {
  7035. this._points = new Array();
  7036. this._length = 0.0;
  7037. this.closed = false;
  7038. this._points.push(new Vector2(x, y));
  7039. }
  7040. /**
  7041. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7042. * Returns the updated Path2.
  7043. */
  7044. Path2.prototype.addLineTo = function (x, y) {
  7045. if (this.closed) {
  7046. return this;
  7047. }
  7048. var newPoint = new Vector2(x, y);
  7049. var previousPoint = this._points[this._points.length - 1];
  7050. this._points.push(newPoint);
  7051. this._length += newPoint.subtract(previousPoint).length();
  7052. return this;
  7053. };
  7054. /**
  7055. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7056. * Returns the updated Path2.
  7057. */
  7058. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7059. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7060. if (this.closed) {
  7061. return this;
  7062. }
  7063. var startPoint = this._points[this._points.length - 1];
  7064. var midPoint = new Vector2(midX, midY);
  7065. var endPoint = new Vector2(endX, endY);
  7066. var arc = new Arc2(startPoint, midPoint, endPoint);
  7067. var increment = arc.angle.radians() / numberOfSegments;
  7068. if (arc.orientation === Orientation.CW)
  7069. increment *= -1;
  7070. var currentAngle = arc.startAngle.radians() + increment;
  7071. for (var i = 0; i < numberOfSegments; i++) {
  7072. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7073. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7074. this.addLineTo(x, y);
  7075. currentAngle += increment;
  7076. }
  7077. return this;
  7078. };
  7079. /**
  7080. * Closes the Path2.
  7081. * Returns the Path2.
  7082. */
  7083. Path2.prototype.close = function () {
  7084. this.closed = true;
  7085. return this;
  7086. };
  7087. /**
  7088. * Returns the Path2 total length (float).
  7089. */
  7090. Path2.prototype.length = function () {
  7091. var result = this._length;
  7092. if (!this.closed) {
  7093. var lastPoint = this._points[this._points.length - 1];
  7094. var firstPoint = this._points[0];
  7095. result += (firstPoint.subtract(lastPoint).length());
  7096. }
  7097. return result;
  7098. };
  7099. /**
  7100. * Returns the Path2 internal array of points.
  7101. */
  7102. Path2.prototype.getPoints = function () {
  7103. return this._points;
  7104. };
  7105. /**
  7106. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7107. */
  7108. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7109. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7110. return Vector2.Zero();
  7111. }
  7112. var lengthPosition = normalizedLengthPosition * this.length();
  7113. var previousOffset = 0;
  7114. for (var i = 0; i < this._points.length; i++) {
  7115. var j = (i + 1) % this._points.length;
  7116. var a = this._points[i];
  7117. var b = this._points[j];
  7118. var bToA = b.subtract(a);
  7119. var nextOffset = (bToA.length() + previousOffset);
  7120. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7121. var dir = bToA.normalize();
  7122. var localOffset = lengthPosition - previousOffset;
  7123. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7124. }
  7125. previousOffset = nextOffset;
  7126. }
  7127. return Vector2.Zero();
  7128. };
  7129. /**
  7130. * Returns a new Path2 starting at the coordinates (x, y).
  7131. */
  7132. Path2.StartingAt = function (x, y) {
  7133. return new Path2(x, y);
  7134. };
  7135. return Path2;
  7136. }());
  7137. BABYLON.Path2 = Path2;
  7138. var Path3D = /** @class */ (function () {
  7139. /**
  7140. * new Path3D(path, normal, raw)
  7141. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7142. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7143. * path : an array of Vector3, the curve axis of the Path3D
  7144. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7145. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7146. */
  7147. function Path3D(path, firstNormal, raw) {
  7148. if (firstNormal === void 0) { firstNormal = null; }
  7149. this.path = path;
  7150. this._curve = new Array();
  7151. this._distances = new Array();
  7152. this._tangents = new Array();
  7153. this._normals = new Array();
  7154. this._binormals = new Array();
  7155. for (var p = 0; p < path.length; p++) {
  7156. this._curve[p] = path[p].clone(); // hard copy
  7157. }
  7158. this._raw = raw || false;
  7159. this._compute(firstNormal);
  7160. }
  7161. /**
  7162. * Returns the Path3D array of successive Vector3 designing its curve.
  7163. */
  7164. Path3D.prototype.getCurve = function () {
  7165. return this._curve;
  7166. };
  7167. /**
  7168. * Returns an array populated with tangent vectors on each Path3D curve point.
  7169. */
  7170. Path3D.prototype.getTangents = function () {
  7171. return this._tangents;
  7172. };
  7173. /**
  7174. * Returns an array populated with normal vectors on each Path3D curve point.
  7175. */
  7176. Path3D.prototype.getNormals = function () {
  7177. return this._normals;
  7178. };
  7179. /**
  7180. * Returns an array populated with binormal vectors on each Path3D curve point.
  7181. */
  7182. Path3D.prototype.getBinormals = function () {
  7183. return this._binormals;
  7184. };
  7185. /**
  7186. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7187. */
  7188. Path3D.prototype.getDistances = function () {
  7189. return this._distances;
  7190. };
  7191. /**
  7192. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7193. * Returns the same object updated.
  7194. */
  7195. Path3D.prototype.update = function (path, firstNormal) {
  7196. if (firstNormal === void 0) { firstNormal = null; }
  7197. for (var p = 0; p < path.length; p++) {
  7198. this._curve[p].x = path[p].x;
  7199. this._curve[p].y = path[p].y;
  7200. this._curve[p].z = path[p].z;
  7201. }
  7202. this._compute(firstNormal);
  7203. return this;
  7204. };
  7205. // private function compute() : computes tangents, normals and binormals
  7206. Path3D.prototype._compute = function (firstNormal) {
  7207. var l = this._curve.length;
  7208. // first and last tangents
  7209. this._tangents[0] = this._getFirstNonNullVector(0);
  7210. if (!this._raw) {
  7211. this._tangents[0].normalize();
  7212. }
  7213. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7214. if (!this._raw) {
  7215. this._tangents[l - 1].normalize();
  7216. }
  7217. // normals and binormals at first point : arbitrary vector with _normalVector()
  7218. var tg0 = this._tangents[0];
  7219. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7220. this._normals[0] = pp0;
  7221. if (!this._raw) {
  7222. this._normals[0].normalize();
  7223. }
  7224. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7225. if (!this._raw) {
  7226. this._binormals[0].normalize();
  7227. }
  7228. this._distances[0] = 0.0;
  7229. // normals and binormals : next points
  7230. var prev; // previous vector (segment)
  7231. var cur; // current vector (segment)
  7232. var curTang; // current tangent
  7233. // previous normal
  7234. var prevBinor; // previous binormal
  7235. for (var i = 1; i < l; i++) {
  7236. // tangents
  7237. prev = this._getLastNonNullVector(i);
  7238. if (i < l - 1) {
  7239. cur = this._getFirstNonNullVector(i);
  7240. this._tangents[i] = prev.add(cur);
  7241. this._tangents[i].normalize();
  7242. }
  7243. this._distances[i] = this._distances[i - 1] + prev.length();
  7244. // normals and binormals
  7245. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7246. curTang = this._tangents[i];
  7247. prevBinor = this._binormals[i - 1];
  7248. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7249. if (!this._raw) {
  7250. this._normals[i].normalize();
  7251. }
  7252. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7253. if (!this._raw) {
  7254. this._binormals[i].normalize();
  7255. }
  7256. }
  7257. };
  7258. // private function getFirstNonNullVector(index)
  7259. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7260. Path3D.prototype._getFirstNonNullVector = function (index) {
  7261. var i = 1;
  7262. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7263. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7264. i++;
  7265. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7266. }
  7267. return nNVector;
  7268. };
  7269. // private function getLastNonNullVector(index)
  7270. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7271. Path3D.prototype._getLastNonNullVector = function (index) {
  7272. var i = 1;
  7273. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7274. while (nLVector.length() === 0 && index > i + 1) {
  7275. i++;
  7276. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7277. }
  7278. return nLVector;
  7279. };
  7280. // private function normalVector(v0, vt, va) :
  7281. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7282. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7283. Path3D.prototype._normalVector = function (v0, vt, va) {
  7284. var normal0;
  7285. var tgl = vt.length();
  7286. if (tgl === 0.0) {
  7287. tgl = 1.0;
  7288. }
  7289. if (va === undefined || va === null) {
  7290. var point;
  7291. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7292. point = new Vector3(0.0, -1.0, 0.0);
  7293. }
  7294. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7295. point = new Vector3(1.0, 0.0, 0.0);
  7296. }
  7297. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7298. point = new Vector3(0.0, 0.0, 1.0);
  7299. }
  7300. else {
  7301. point = Vector3.Zero();
  7302. }
  7303. normal0 = Vector3.Cross(vt, point);
  7304. }
  7305. else {
  7306. normal0 = Vector3.Cross(vt, va);
  7307. Vector3.CrossToRef(normal0, vt, normal0);
  7308. }
  7309. normal0.normalize();
  7310. return normal0;
  7311. };
  7312. return Path3D;
  7313. }());
  7314. BABYLON.Path3D = Path3D;
  7315. var Curve3 = /** @class */ (function () {
  7316. /**
  7317. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7318. * A Curve3 is designed from a series of successive Vector3.
  7319. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7320. */
  7321. function Curve3(points) {
  7322. this._length = 0.0;
  7323. this._points = points;
  7324. this._length = this._computeLength(points);
  7325. }
  7326. /**
  7327. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7328. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7329. * @param v1 (Vector3) the control point
  7330. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7331. * @param nbPoints (integer) the wanted number of points in the curve
  7332. */
  7333. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7334. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7335. var bez = new Array();
  7336. var equation = function (t, val0, val1, val2) {
  7337. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7338. return res;
  7339. };
  7340. for (var i = 0; i <= nbPoints; i++) {
  7341. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7342. }
  7343. return new Curve3(bez);
  7344. };
  7345. /**
  7346. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7347. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7348. * @param v1 (Vector3) the first control point
  7349. * @param v2 (Vector3) the second control point
  7350. * @param v3 (Vector3) the end point of the Cubic Bezier
  7351. * @param nbPoints (integer) the wanted number of points in the curve
  7352. */
  7353. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7354. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7355. var bez = new Array();
  7356. var equation = function (t, val0, val1, val2, val3) {
  7357. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7358. return res;
  7359. };
  7360. for (var i = 0; i <= nbPoints; i++) {
  7361. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7362. }
  7363. return new Curve3(bez);
  7364. };
  7365. /**
  7366. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7367. * @param p1 (Vector3) the origin point of the Hermite Spline
  7368. * @param t1 (Vector3) the tangent vector at the origin point
  7369. * @param p2 (Vector3) the end point of the Hermite Spline
  7370. * @param t2 (Vector3) the tangent vector at the end point
  7371. * @param nbPoints (integer) the wanted number of points in the curve
  7372. */
  7373. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7374. var hermite = new Array();
  7375. var step = 1.0 / nbPoints;
  7376. for (var i = 0; i <= nbPoints; i++) {
  7377. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7378. }
  7379. return new Curve3(hermite);
  7380. };
  7381. /**
  7382. * Returns a Curve3 object along a CatmullRom Spline curve :
  7383. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7384. * @param nbPoints (integer) the wanted number of points between each curve control points
  7385. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7386. */
  7387. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7388. var catmullRom = new Array();
  7389. var step = 1.0 / nbPoints;
  7390. var amount = 0.0;
  7391. if (closed) {
  7392. var pointsCount = points.length;
  7393. for (var i = 0; i < pointsCount; i++) {
  7394. amount = 0;
  7395. for (var c = 0; c < nbPoints; c++) {
  7396. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7397. amount += step;
  7398. }
  7399. }
  7400. catmullRom.push(catmullRom[0]);
  7401. }
  7402. else {
  7403. var totalPoints = new Array();
  7404. totalPoints.push(points[0].clone());
  7405. Array.prototype.push.apply(totalPoints, points);
  7406. totalPoints.push(points[points.length - 1].clone());
  7407. for (var i = 0; i < totalPoints.length - 3; i++) {
  7408. amount = 0;
  7409. for (var c = 0; c < nbPoints; c++) {
  7410. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7411. amount += step;
  7412. }
  7413. }
  7414. i--;
  7415. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7416. }
  7417. return new Curve3(catmullRom);
  7418. };
  7419. /**
  7420. * Returns the Curve3 stored array of successive Vector3
  7421. */
  7422. Curve3.prototype.getPoints = function () {
  7423. return this._points;
  7424. };
  7425. /**
  7426. * Returns the computed length (float) of the curve.
  7427. */
  7428. Curve3.prototype.length = function () {
  7429. return this._length;
  7430. };
  7431. /**
  7432. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7433. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7434. * curveA and curveB keep unchanged.
  7435. */
  7436. Curve3.prototype.continue = function (curve) {
  7437. var lastPoint = this._points[this._points.length - 1];
  7438. var continuedPoints = this._points.slice();
  7439. var curvePoints = curve.getPoints();
  7440. for (var i = 1; i < curvePoints.length; i++) {
  7441. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7442. }
  7443. var continuedCurve = new Curve3(continuedPoints);
  7444. return continuedCurve;
  7445. };
  7446. Curve3.prototype._computeLength = function (path) {
  7447. var l = 0;
  7448. for (var i = 1; i < path.length; i++) {
  7449. l += (path[i].subtract(path[i - 1])).length();
  7450. }
  7451. return l;
  7452. };
  7453. return Curve3;
  7454. }());
  7455. BABYLON.Curve3 = Curve3;
  7456. // Vertex formats
  7457. var PositionNormalVertex = /** @class */ (function () {
  7458. function PositionNormalVertex(position, normal) {
  7459. if (position === void 0) { position = Vector3.Zero(); }
  7460. if (normal === void 0) { normal = Vector3.Up(); }
  7461. this.position = position;
  7462. this.normal = normal;
  7463. }
  7464. PositionNormalVertex.prototype.clone = function () {
  7465. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7466. };
  7467. return PositionNormalVertex;
  7468. }());
  7469. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7470. var PositionNormalTextureVertex = /** @class */ (function () {
  7471. function PositionNormalTextureVertex(position, normal, uv) {
  7472. if (position === void 0) { position = Vector3.Zero(); }
  7473. if (normal === void 0) { normal = Vector3.Up(); }
  7474. if (uv === void 0) { uv = Vector2.Zero(); }
  7475. this.position = position;
  7476. this.normal = normal;
  7477. this.uv = uv;
  7478. }
  7479. PositionNormalTextureVertex.prototype.clone = function () {
  7480. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7481. };
  7482. return PositionNormalTextureVertex;
  7483. }());
  7484. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7485. // Temporary pre-allocated objects for engine internal use
  7486. // usage in any internal function :
  7487. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7488. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7489. var Tmp = /** @class */ (function () {
  7490. function Tmp() {
  7491. }
  7492. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7493. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7494. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7495. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7496. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7497. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7498. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7499. Matrix.Zero(), Matrix.Zero(),
  7500. Matrix.Zero(), Matrix.Zero(),
  7501. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7502. return Tmp;
  7503. }());
  7504. BABYLON.Tmp = Tmp;
  7505. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7506. var MathTmp = /** @class */ (function () {
  7507. function MathTmp() {
  7508. }
  7509. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7510. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7511. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7512. return MathTmp;
  7513. }());
  7514. })(BABYLON || (BABYLON = {}));
  7515. //# sourceMappingURL=babylon.math.js.map
  7516. var BABYLON;
  7517. (function (BABYLON) {
  7518. var Scalar = /** @class */ (function () {
  7519. function Scalar() {
  7520. }
  7521. /**
  7522. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7523. */
  7524. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7525. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7526. var num = a - b;
  7527. return -epsilon <= num && num <= epsilon;
  7528. };
  7529. /**
  7530. * Returns a string : the upper case translation of the number i to hexadecimal.
  7531. */
  7532. Scalar.ToHex = function (i) {
  7533. var str = i.toString(16);
  7534. if (i <= 15) {
  7535. return ("0" + str).toUpperCase();
  7536. }
  7537. return str.toUpperCase();
  7538. };
  7539. /**
  7540. * Returns -1 if value is negative and +1 is value is positive.
  7541. * Returns the value itself if it's equal to zero.
  7542. */
  7543. Scalar.Sign = function (value) {
  7544. value = +value; // convert to a number
  7545. if (value === 0 || isNaN(value))
  7546. return value;
  7547. return value > 0 ? 1 : -1;
  7548. };
  7549. /**
  7550. * Returns the value itself if it's between min and max.
  7551. * Returns min if the value is lower than min.
  7552. * Returns max if the value is greater than max.
  7553. */
  7554. Scalar.Clamp = function (value, min, max) {
  7555. if (min === void 0) { min = 0; }
  7556. if (max === void 0) { max = 1; }
  7557. return Math.min(max, Math.max(min, value));
  7558. };
  7559. /**
  7560. * Returns the log2 of value.
  7561. */
  7562. Scalar.Log2 = function (value) {
  7563. return Math.log(value) * Math.LOG2E;
  7564. };
  7565. /**
  7566. * Loops the value, so that it is never larger than length and never smaller than 0.
  7567. *
  7568. * This is similar to the modulo operator but it works with floating point numbers.
  7569. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7570. * With t = 5 and length = 2.5, the result would be 0.0.
  7571. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7572. */
  7573. Scalar.Repeat = function (value, length) {
  7574. return value - Math.floor(value / length) * length;
  7575. };
  7576. /**
  7577. * Normalize the value between 0.0 and 1.0 using min and max values
  7578. */
  7579. Scalar.Normalize = function (value, min, max) {
  7580. return (value - min) / (max - min);
  7581. };
  7582. /**
  7583. * Denormalize the value from 0.0 and 1.0 using min and max values
  7584. */
  7585. Scalar.Denormalize = function (normalized, min, max) {
  7586. return (normalized * (max - min) + min);
  7587. };
  7588. /**
  7589. * Calculates the shortest difference between two given angles given in degrees.
  7590. */
  7591. Scalar.DeltaAngle = function (current, target) {
  7592. var num = Scalar.Repeat(target - current, 360.0);
  7593. if (num > 180.0) {
  7594. num -= 360.0;
  7595. }
  7596. return num;
  7597. };
  7598. /**
  7599. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7600. *
  7601. * The returned value will move back and forth between 0 and length
  7602. */
  7603. Scalar.PingPong = function (tx, length) {
  7604. var t = Scalar.Repeat(tx, length * 2.0);
  7605. return length - Math.abs(t - length);
  7606. };
  7607. /**
  7608. * Interpolates between min and max with smoothing at the limits.
  7609. *
  7610. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7611. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7612. */
  7613. Scalar.SmoothStep = function (from, to, tx) {
  7614. var t = Scalar.Clamp(tx);
  7615. t = -2.0 * t * t * t + 3.0 * t * t;
  7616. return to * t + from * (1.0 - t);
  7617. };
  7618. /**
  7619. * Moves a value current towards target.
  7620. *
  7621. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7622. * Negative values of maxDelta pushes the value away from target.
  7623. */
  7624. Scalar.MoveTowards = function (current, target, maxDelta) {
  7625. var result = 0;
  7626. if (Math.abs(target - current) <= maxDelta) {
  7627. result = target;
  7628. }
  7629. else {
  7630. result = current + Scalar.Sign(target - current) * maxDelta;
  7631. }
  7632. return result;
  7633. };
  7634. /**
  7635. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7636. *
  7637. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7638. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7639. */
  7640. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7641. var num = Scalar.DeltaAngle(current, target);
  7642. var result = 0;
  7643. if (-maxDelta < num && num < maxDelta) {
  7644. result = target;
  7645. }
  7646. else {
  7647. target = current + num;
  7648. result = Scalar.MoveTowards(current, target, maxDelta);
  7649. }
  7650. return result;
  7651. };
  7652. /**
  7653. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7654. */
  7655. Scalar.Lerp = function (start, end, amount) {
  7656. return start + ((end - start) * amount);
  7657. };
  7658. /**
  7659. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7660. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7661. */
  7662. Scalar.LerpAngle = function (start, end, amount) {
  7663. var num = Scalar.Repeat(end - start, 360.0);
  7664. if (num > 180.0) {
  7665. num -= 360.0;
  7666. }
  7667. return start + num * Scalar.Clamp(amount);
  7668. };
  7669. /**
  7670. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7671. */
  7672. Scalar.InverseLerp = function (a, b, value) {
  7673. var result = 0;
  7674. if (a != b) {
  7675. result = Scalar.Clamp((value - a) / (b - a));
  7676. }
  7677. else {
  7678. result = 0.0;
  7679. }
  7680. return result;
  7681. };
  7682. /**
  7683. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7684. */
  7685. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7686. var squared = amount * amount;
  7687. var cubed = amount * squared;
  7688. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7689. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7690. var part3 = (cubed - (2.0 * squared)) + amount;
  7691. var part4 = cubed - squared;
  7692. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7693. };
  7694. /**
  7695. * Returns a random float number between and min and max values
  7696. */
  7697. Scalar.RandomRange = function (min, max) {
  7698. if (min === max)
  7699. return min;
  7700. return ((Math.random() * (max - min)) + min);
  7701. };
  7702. /**
  7703. * This function returns percentage of a number in a given range.
  7704. *
  7705. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7706. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7707. */
  7708. Scalar.RangeToPercent = function (number, min, max) {
  7709. return ((number - min) / (max - min));
  7710. };
  7711. /**
  7712. * This function returns number that corresponds to the percentage in a given range.
  7713. *
  7714. * PercentToRange(0.34,0,100) will return 34.
  7715. */
  7716. Scalar.PercentToRange = function (percent, min, max) {
  7717. return ((max - min) * percent + min);
  7718. };
  7719. /**
  7720. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7721. * @param angle The angle to normalize in radian.
  7722. * @return The converted angle.
  7723. */
  7724. Scalar.NormalizeRadians = function (angle) {
  7725. // More precise but slower version kept for reference.
  7726. // angle = angle % Tools.TwoPi;
  7727. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7728. //if (angle > Math.PI) {
  7729. // angle -= Tools.TwoPi;
  7730. //}
  7731. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7732. return angle;
  7733. };
  7734. /**
  7735. * Two pi constants convenient for computation.
  7736. */
  7737. Scalar.TwoPi = Math.PI * 2;
  7738. return Scalar;
  7739. }());
  7740. BABYLON.Scalar = Scalar;
  7741. })(BABYLON || (BABYLON = {}));
  7742. //# sourceMappingURL=babylon.math.scalar.js.map
  7743. //# sourceMappingURL=babylon.mixins.js.map
  7744. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7745. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7746. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7747. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7748. //# sourceMappingURL=babylon.webgl2.js.map
  7749. var BABYLON;
  7750. (function (BABYLON) {
  7751. var __decoratorInitialStore = {};
  7752. var __mergedStore = {};
  7753. var _copySource = function (creationFunction, source, instanciate) {
  7754. var destination = creationFunction();
  7755. // Tags
  7756. if (BABYLON.Tags) {
  7757. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7758. }
  7759. var classStore = getMergedStore(destination);
  7760. // Properties
  7761. for (var property in classStore) {
  7762. var propertyDescriptor = classStore[property];
  7763. var sourceProperty = source[property];
  7764. var propertyType = propertyDescriptor.type;
  7765. if (sourceProperty !== undefined && sourceProperty !== null) {
  7766. switch (propertyType) {
  7767. case 0: // Value
  7768. case 6: // Mesh reference
  7769. case 11: // Camera reference
  7770. destination[property] = sourceProperty;
  7771. break;
  7772. case 1: // Texture
  7773. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7774. break;
  7775. case 2: // Color3
  7776. case 3: // FresnelParameters
  7777. case 4: // Vector2
  7778. case 5: // Vector3
  7779. case 7: // Color Curves
  7780. case 10: // Quaternion
  7781. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7782. break;
  7783. }
  7784. }
  7785. }
  7786. return destination;
  7787. };
  7788. function getDirectStore(target) {
  7789. var classKey = target.getClassName();
  7790. if (!__decoratorInitialStore[classKey]) {
  7791. __decoratorInitialStore[classKey] = {};
  7792. }
  7793. return __decoratorInitialStore[classKey];
  7794. }
  7795. /**
  7796. * Return the list of properties flagged as serializable
  7797. * @param target: host object
  7798. */
  7799. function getMergedStore(target) {
  7800. var classKey = target.getClassName();
  7801. if (__mergedStore[classKey]) {
  7802. return __mergedStore[classKey];
  7803. }
  7804. __mergedStore[classKey] = {};
  7805. var store = __mergedStore[classKey];
  7806. var currentTarget = target;
  7807. var currentKey = classKey;
  7808. while (currentKey) {
  7809. var initialStore = __decoratorInitialStore[currentKey];
  7810. for (var property in initialStore) {
  7811. store[property] = initialStore[property];
  7812. }
  7813. var parent_1 = void 0;
  7814. var done = false;
  7815. do {
  7816. parent_1 = Object.getPrototypeOf(currentTarget);
  7817. if (!parent_1.getClassName) {
  7818. done = true;
  7819. break;
  7820. }
  7821. if (parent_1.getClassName() !== currentKey) {
  7822. break;
  7823. }
  7824. currentTarget = parent_1;
  7825. } while (parent_1);
  7826. if (done) {
  7827. break;
  7828. }
  7829. currentKey = parent_1.getClassName();
  7830. currentTarget = parent_1;
  7831. }
  7832. return store;
  7833. }
  7834. function generateSerializableMember(type, sourceName) {
  7835. return function (target, propertyKey) {
  7836. var classStore = getDirectStore(target);
  7837. if (!classStore[propertyKey]) {
  7838. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7839. }
  7840. };
  7841. }
  7842. function generateExpandMember(setCallback, targetKey) {
  7843. if (targetKey === void 0) { targetKey = null; }
  7844. return function (target, propertyKey) {
  7845. var key = targetKey || ("_" + propertyKey);
  7846. Object.defineProperty(target, propertyKey, {
  7847. get: function () {
  7848. return this[key];
  7849. },
  7850. set: function (value) {
  7851. if (this[key] === value) {
  7852. return;
  7853. }
  7854. this[key] = value;
  7855. target[setCallback].apply(this);
  7856. },
  7857. enumerable: true,
  7858. configurable: true
  7859. });
  7860. };
  7861. }
  7862. function expandToProperty(callback, targetKey) {
  7863. if (targetKey === void 0) { targetKey = null; }
  7864. return generateExpandMember(callback, targetKey);
  7865. }
  7866. BABYLON.expandToProperty = expandToProperty;
  7867. function serialize(sourceName) {
  7868. return generateSerializableMember(0, sourceName); // value member
  7869. }
  7870. BABYLON.serialize = serialize;
  7871. function serializeAsTexture(sourceName) {
  7872. return generateSerializableMember(1, sourceName); // texture member
  7873. }
  7874. BABYLON.serializeAsTexture = serializeAsTexture;
  7875. function serializeAsColor3(sourceName) {
  7876. return generateSerializableMember(2, sourceName); // color3 member
  7877. }
  7878. BABYLON.serializeAsColor3 = serializeAsColor3;
  7879. function serializeAsFresnelParameters(sourceName) {
  7880. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7881. }
  7882. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7883. function serializeAsVector2(sourceName) {
  7884. return generateSerializableMember(4, sourceName); // vector2 member
  7885. }
  7886. BABYLON.serializeAsVector2 = serializeAsVector2;
  7887. function serializeAsVector3(sourceName) {
  7888. return generateSerializableMember(5, sourceName); // vector3 member
  7889. }
  7890. BABYLON.serializeAsVector3 = serializeAsVector3;
  7891. function serializeAsMeshReference(sourceName) {
  7892. return generateSerializableMember(6, sourceName); // mesh reference member
  7893. }
  7894. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7895. function serializeAsColorCurves(sourceName) {
  7896. return generateSerializableMember(7, sourceName); // color curves
  7897. }
  7898. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7899. function serializeAsColor4(sourceName) {
  7900. return generateSerializableMember(8, sourceName); // color 4
  7901. }
  7902. BABYLON.serializeAsColor4 = serializeAsColor4;
  7903. function serializeAsImageProcessingConfiguration(sourceName) {
  7904. return generateSerializableMember(9, sourceName); // image processing
  7905. }
  7906. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7907. function serializeAsQuaternion(sourceName) {
  7908. return generateSerializableMember(10, sourceName); // quaternion member
  7909. }
  7910. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7911. /**
  7912. * Decorator used to define property that can be serialized as reference to a camera
  7913. * @param sourceName defines the name of the property to decorate
  7914. */
  7915. function serializeAsCameraReference(sourceName) {
  7916. return generateSerializableMember(11, sourceName); // camera reference member
  7917. }
  7918. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7919. var SerializationHelper = /** @class */ (function () {
  7920. function SerializationHelper() {
  7921. }
  7922. SerializationHelper.Serialize = function (entity, serializationObject) {
  7923. if (!serializationObject) {
  7924. serializationObject = {};
  7925. }
  7926. // Tags
  7927. if (BABYLON.Tags) {
  7928. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7929. }
  7930. var serializedProperties = getMergedStore(entity);
  7931. // Properties
  7932. for (var property in serializedProperties) {
  7933. var propertyDescriptor = serializedProperties[property];
  7934. var targetPropertyName = propertyDescriptor.sourceName || property;
  7935. var propertyType = propertyDescriptor.type;
  7936. var sourceProperty = entity[property];
  7937. if (sourceProperty !== undefined && sourceProperty !== null) {
  7938. switch (propertyType) {
  7939. case 0: // Value
  7940. serializationObject[targetPropertyName] = sourceProperty;
  7941. break;
  7942. case 1: // Texture
  7943. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7944. break;
  7945. case 2: // Color3
  7946. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7947. break;
  7948. case 3: // FresnelParameters
  7949. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7950. break;
  7951. case 4: // Vector2
  7952. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7953. break;
  7954. case 5: // Vector3
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 6: // Mesh reference
  7958. serializationObject[targetPropertyName] = sourceProperty.id;
  7959. break;
  7960. case 7: // Color Curves
  7961. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7962. break;
  7963. case 8: // Color 4
  7964. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7965. break;
  7966. case 9: // Image Processing
  7967. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7968. break;
  7969. case 10: // Quaternion
  7970. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7971. break;
  7972. case 11: // Camera reference
  7973. serializationObject[targetPropertyName] = sourceProperty.id;
  7974. break;
  7975. }
  7976. }
  7977. }
  7978. return serializationObject;
  7979. };
  7980. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7981. if (rootUrl === void 0) { rootUrl = null; }
  7982. var destination = creationFunction();
  7983. if (!rootUrl) {
  7984. rootUrl = "";
  7985. }
  7986. // Tags
  7987. if (BABYLON.Tags) {
  7988. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7989. }
  7990. var classStore = getMergedStore(destination);
  7991. // Properties
  7992. for (var property in classStore) {
  7993. var propertyDescriptor = classStore[property];
  7994. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7995. var propertyType = propertyDescriptor.type;
  7996. if (sourceProperty !== undefined && sourceProperty !== null) {
  7997. var dest = destination;
  7998. switch (propertyType) {
  7999. case 0: // Value
  8000. dest[property] = sourceProperty;
  8001. break;
  8002. case 1: // Texture
  8003. if (scene) {
  8004. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8005. }
  8006. break;
  8007. case 2: // Color3
  8008. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8009. break;
  8010. case 3: // FresnelParameters
  8011. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8012. break;
  8013. case 4: // Vector2
  8014. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8015. break;
  8016. case 5: // Vector3
  8017. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8018. break;
  8019. case 6: // Mesh reference
  8020. if (scene) {
  8021. dest[property] = scene.getLastMeshByID(sourceProperty);
  8022. }
  8023. break;
  8024. case 7: // Color Curves
  8025. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8026. break;
  8027. case 8: // Color 4
  8028. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8029. break;
  8030. case 9: // Image Processing
  8031. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8032. break;
  8033. case 10: // Quaternion
  8034. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8035. break;
  8036. case 11: // Camera reference
  8037. if (scene) {
  8038. dest[property] = scene.getCameraByID(sourceProperty);
  8039. }
  8040. break;
  8041. }
  8042. }
  8043. }
  8044. return destination;
  8045. };
  8046. SerializationHelper.Clone = function (creationFunction, source) {
  8047. return _copySource(creationFunction, source, false);
  8048. };
  8049. SerializationHelper.Instanciate = function (creationFunction, source) {
  8050. return _copySource(creationFunction, source, true);
  8051. };
  8052. return SerializationHelper;
  8053. }());
  8054. BABYLON.SerializationHelper = SerializationHelper;
  8055. })(BABYLON || (BABYLON = {}));
  8056. //# sourceMappingURL=babylon.decorators.js.map
  8057. var BABYLON;
  8058. (function (BABYLON) {
  8059. /**
  8060. * Wrapper class for promise with external resolve and reject.
  8061. */
  8062. var Deferred = /** @class */ (function () {
  8063. /**
  8064. * Constructor for this deferred object.
  8065. */
  8066. function Deferred() {
  8067. var _this = this;
  8068. this.promise = new Promise(function (resolve, reject) {
  8069. _this._resolve = resolve;
  8070. _this._reject = reject;
  8071. });
  8072. }
  8073. Object.defineProperty(Deferred.prototype, "resolve", {
  8074. /**
  8075. * The resolve method of the promise associated with this deferred object.
  8076. */
  8077. get: function () {
  8078. return this._resolve;
  8079. },
  8080. enumerable: true,
  8081. configurable: true
  8082. });
  8083. Object.defineProperty(Deferred.prototype, "reject", {
  8084. /**
  8085. * The reject method of the promise associated with this deferred object.
  8086. */
  8087. get: function () {
  8088. return this._reject;
  8089. },
  8090. enumerable: true,
  8091. configurable: true
  8092. });
  8093. return Deferred;
  8094. }());
  8095. BABYLON.Deferred = Deferred;
  8096. })(BABYLON || (BABYLON = {}));
  8097. //# sourceMappingURL=babylon.deferred.js.map
  8098. var BABYLON;
  8099. (function (BABYLON) {
  8100. /**
  8101. * A class serves as a medium between the observable and its observers
  8102. */
  8103. var EventState = /** @class */ (function () {
  8104. /**
  8105. * Create a new EventState
  8106. * @param mask defines the mask associated with this state
  8107. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8108. * @param target defines the original target of the state
  8109. * @param currentTarget defines the current target of the state
  8110. */
  8111. function EventState(mask, skipNextObservers, target, currentTarget) {
  8112. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8113. this.initalize(mask, skipNextObservers, target, currentTarget);
  8114. }
  8115. /**
  8116. * Initialize the current event state
  8117. * @param mask defines the mask associated with this state
  8118. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8119. * @param target defines the original target of the state
  8120. * @param currentTarget defines the current target of the state
  8121. * @returns the current event state
  8122. */
  8123. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8124. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8125. this.mask = mask;
  8126. this.skipNextObservers = skipNextObservers;
  8127. this.target = target;
  8128. this.currentTarget = currentTarget;
  8129. return this;
  8130. };
  8131. return EventState;
  8132. }());
  8133. BABYLON.EventState = EventState;
  8134. /**
  8135. * Represent an Observer registered to a given Observable object.
  8136. */
  8137. var Observer = /** @class */ (function () {
  8138. /**
  8139. * Creates a new observer
  8140. * @param callback defines the callback to call when the observer is notified
  8141. * @param mask defines the mask of the observer (used to filter notifications)
  8142. * @param scope defines the current scope used to restore the JS context
  8143. */
  8144. function Observer(
  8145. /**
  8146. * Defines the callback to call when the observer is notified
  8147. */
  8148. callback,
  8149. /**
  8150. * Defines the mask of the observer (used to filter notifications)
  8151. */
  8152. mask,
  8153. /**
  8154. * Defines the current scope used to restore the JS context
  8155. */
  8156. scope) {
  8157. if (scope === void 0) { scope = null; }
  8158. this.callback = callback;
  8159. this.mask = mask;
  8160. this.scope = scope;
  8161. /** @hidden */
  8162. this._willBeUnregistered = false;
  8163. /**
  8164. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8165. */
  8166. this.unregisterOnNextCall = false;
  8167. }
  8168. return Observer;
  8169. }());
  8170. BABYLON.Observer = Observer;
  8171. /**
  8172. * Represent a list of observers registered to multiple Observables object.
  8173. */
  8174. var MultiObserver = /** @class */ (function () {
  8175. function MultiObserver() {
  8176. }
  8177. /**
  8178. * Release associated resources
  8179. */
  8180. MultiObserver.prototype.dispose = function () {
  8181. if (this._observers && this._observables) {
  8182. for (var index = 0; index < this._observers.length; index++) {
  8183. this._observables[index].remove(this._observers[index]);
  8184. }
  8185. }
  8186. this._observers = null;
  8187. this._observables = null;
  8188. };
  8189. /**
  8190. * Raise a callback when one of the observable will notify
  8191. * @param observables defines a list of observables to watch
  8192. * @param callback defines the callback to call on notification
  8193. * @param mask defines the mask used to filter notifications
  8194. * @param scope defines the current scope used to restore the JS context
  8195. * @returns the new MultiObserver
  8196. */
  8197. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8198. if (mask === void 0) { mask = -1; }
  8199. if (scope === void 0) { scope = null; }
  8200. var result = new MultiObserver();
  8201. result._observers = new Array();
  8202. result._observables = observables;
  8203. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8204. var observable = observables_1[_i];
  8205. var observer = observable.add(callback, mask, false, scope);
  8206. if (observer) {
  8207. result._observers.push(observer);
  8208. }
  8209. }
  8210. return result;
  8211. };
  8212. return MultiObserver;
  8213. }());
  8214. BABYLON.MultiObserver = MultiObserver;
  8215. /**
  8216. * The Observable class is a simple implementation of the Observable pattern.
  8217. *
  8218. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8219. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8220. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8221. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8222. */
  8223. var Observable = /** @class */ (function () {
  8224. /**
  8225. * Creates a new observable
  8226. * @param onObserverAdded defines a callback to call when a new observer is added
  8227. */
  8228. function Observable(onObserverAdded) {
  8229. this._observers = new Array();
  8230. this._eventState = new EventState(0);
  8231. if (onObserverAdded) {
  8232. this._onObserverAdded = onObserverAdded;
  8233. }
  8234. }
  8235. /**
  8236. * Create a new Observer with the specified callback
  8237. * @param callback the callback that will be executed for that Observer
  8238. * @param mask the mask used to filter observers
  8239. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8240. * @param scope optional scope for the callback to be called from
  8241. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8242. * @returns the new observer created for the callback
  8243. */
  8244. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8245. if (mask === void 0) { mask = -1; }
  8246. if (insertFirst === void 0) { insertFirst = false; }
  8247. if (scope === void 0) { scope = null; }
  8248. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8249. if (!callback) {
  8250. return null;
  8251. }
  8252. var observer = new Observer(callback, mask, scope);
  8253. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8254. if (insertFirst) {
  8255. this._observers.unshift(observer);
  8256. }
  8257. else {
  8258. this._observers.push(observer);
  8259. }
  8260. if (this._onObserverAdded) {
  8261. this._onObserverAdded(observer);
  8262. }
  8263. return observer;
  8264. };
  8265. /**
  8266. * Remove an Observer from the Observable object
  8267. * @param observer the instance of the Observer to remove
  8268. * @returns false if it doesn't belong to this Observable
  8269. */
  8270. Observable.prototype.remove = function (observer) {
  8271. if (!observer) {
  8272. return false;
  8273. }
  8274. var index = this._observers.indexOf(observer);
  8275. if (index !== -1) {
  8276. this._observers.splice(index, 1);
  8277. return true;
  8278. }
  8279. return false;
  8280. };
  8281. /**
  8282. * Remove a callback from the Observable object
  8283. * @param callback the callback to remove
  8284. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8285. * @returns false if it doesn't belong to this Observable
  8286. */
  8287. Observable.prototype.removeCallback = function (callback, scope) {
  8288. for (var index = 0; index < this._observers.length; index++) {
  8289. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8290. this._observers.splice(index, 1);
  8291. return true;
  8292. }
  8293. }
  8294. return false;
  8295. };
  8296. Observable.prototype._deferUnregister = function (observer) {
  8297. var _this = this;
  8298. observer.unregisterOnNextCall = false;
  8299. observer._willBeUnregistered = true;
  8300. BABYLON.Tools.SetImmediate(function () {
  8301. _this.remove(observer);
  8302. });
  8303. };
  8304. /**
  8305. * Notify all Observers by calling their respective callback with the given data
  8306. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8307. * @param eventData defines the data to send to all observers
  8308. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8309. * @param target defines the original target of the state
  8310. * @param currentTarget defines the current target of the state
  8311. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8312. */
  8313. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8314. if (mask === void 0) { mask = -1; }
  8315. if (!this._observers.length) {
  8316. return true;
  8317. }
  8318. var state = this._eventState;
  8319. state.mask = mask;
  8320. state.target = target;
  8321. state.currentTarget = currentTarget;
  8322. state.skipNextObservers = false;
  8323. state.lastReturnValue = eventData;
  8324. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8325. var obs = _a[_i];
  8326. if (obs._willBeUnregistered) {
  8327. continue;
  8328. }
  8329. if (obs.mask & mask) {
  8330. if (obs.scope) {
  8331. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8332. }
  8333. else {
  8334. state.lastReturnValue = obs.callback(eventData, state);
  8335. }
  8336. if (obs.unregisterOnNextCall) {
  8337. this._deferUnregister(obs);
  8338. }
  8339. }
  8340. if (state.skipNextObservers) {
  8341. return false;
  8342. }
  8343. }
  8344. return true;
  8345. };
  8346. /**
  8347. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8348. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8349. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8350. * and it is crucial that all callbacks will be executed.
  8351. * The order of the callbacks is kept, callbacks are not executed parallel.
  8352. *
  8353. * @param eventData The data to be sent to each callback
  8354. * @param mask is used to filter observers defaults to -1
  8355. * @param target defines the callback target (see EventState)
  8356. * @param currentTarget defines he current object in the bubbling phase
  8357. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8358. */
  8359. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8360. var _this = this;
  8361. if (mask === void 0) { mask = -1; }
  8362. // create an empty promise
  8363. var p = Promise.resolve(eventData);
  8364. // no observers? return this promise.
  8365. if (!this._observers.length) {
  8366. return p;
  8367. }
  8368. var state = this._eventState;
  8369. state.mask = mask;
  8370. state.target = target;
  8371. state.currentTarget = currentTarget;
  8372. state.skipNextObservers = false;
  8373. // execute one callback after another (not using Promise.all, the order is important)
  8374. this._observers.forEach(function (obs) {
  8375. if (state.skipNextObservers) {
  8376. return;
  8377. }
  8378. if (obs._willBeUnregistered) {
  8379. return;
  8380. }
  8381. if (obs.mask & mask) {
  8382. if (obs.scope) {
  8383. p = p.then(function (lastReturnedValue) {
  8384. state.lastReturnValue = lastReturnedValue;
  8385. return obs.callback.apply(obs.scope, [eventData, state]);
  8386. });
  8387. }
  8388. else {
  8389. p = p.then(function (lastReturnedValue) {
  8390. state.lastReturnValue = lastReturnedValue;
  8391. return obs.callback(eventData, state);
  8392. });
  8393. }
  8394. if (obs.unregisterOnNextCall) {
  8395. _this._deferUnregister(obs);
  8396. }
  8397. }
  8398. });
  8399. // return the eventData
  8400. return p.then(function () { return eventData; });
  8401. };
  8402. /**
  8403. * Notify a specific observer
  8404. * @param observer defines the observer to notify
  8405. * @param eventData defines the data to be sent to each callback
  8406. * @param mask is used to filter observers defaults to -1
  8407. */
  8408. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8409. if (mask === void 0) { mask = -1; }
  8410. var state = this._eventState;
  8411. state.mask = mask;
  8412. state.skipNextObservers = false;
  8413. observer.callback(eventData, state);
  8414. };
  8415. /**
  8416. * Gets a boolean indicating if the observable has at least one observer
  8417. * @returns true is the Observable has at least one Observer registered
  8418. */
  8419. Observable.prototype.hasObservers = function () {
  8420. return this._observers.length > 0;
  8421. };
  8422. /**
  8423. * Clear the list of observers
  8424. */
  8425. Observable.prototype.clear = function () {
  8426. this._observers = new Array();
  8427. this._onObserverAdded = null;
  8428. };
  8429. /**
  8430. * Clone the current observable
  8431. * @returns a new observable
  8432. */
  8433. Observable.prototype.clone = function () {
  8434. var result = new Observable();
  8435. result._observers = this._observers.slice(0);
  8436. return result;
  8437. };
  8438. /**
  8439. * Does this observable handles observer registered with a given mask
  8440. * @param mask defines the mask to be tested
  8441. * @return whether or not one observer registered with the given mask is handeled
  8442. **/
  8443. Observable.prototype.hasSpecificMask = function (mask) {
  8444. if (mask === void 0) { mask = -1; }
  8445. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8446. var obs = _a[_i];
  8447. if (obs.mask & mask || obs.mask === mask) {
  8448. return true;
  8449. }
  8450. }
  8451. return false;
  8452. };
  8453. return Observable;
  8454. }());
  8455. BABYLON.Observable = Observable;
  8456. })(BABYLON || (BABYLON = {}));
  8457. //# sourceMappingURL=babylon.observable.js.map
  8458. var BABYLON;
  8459. (function (BABYLON) {
  8460. var SmartArray = /** @class */ (function () {
  8461. function SmartArray(capacity) {
  8462. this.length = 0;
  8463. this.data = new Array(capacity);
  8464. this._id = SmartArray._GlobalId++;
  8465. }
  8466. SmartArray.prototype.push = function (value) {
  8467. this.data[this.length++] = value;
  8468. if (this.length > this.data.length) {
  8469. this.data.length *= 2;
  8470. }
  8471. };
  8472. SmartArray.prototype.forEach = function (func) {
  8473. for (var index = 0; index < this.length; index++) {
  8474. func(this.data[index]);
  8475. }
  8476. };
  8477. SmartArray.prototype.sort = function (compareFn) {
  8478. this.data.sort(compareFn);
  8479. };
  8480. SmartArray.prototype.reset = function () {
  8481. this.length = 0;
  8482. };
  8483. SmartArray.prototype.dispose = function () {
  8484. this.reset();
  8485. if (this.data) {
  8486. this.data.length = 0;
  8487. this.data = [];
  8488. }
  8489. };
  8490. SmartArray.prototype.concat = function (array) {
  8491. if (array.length === 0) {
  8492. return;
  8493. }
  8494. if (this.length + array.length > this.data.length) {
  8495. this.data.length = (this.length + array.length) * 2;
  8496. }
  8497. for (var index = 0; index < array.length; index++) {
  8498. this.data[this.length++] = (array.data || array)[index];
  8499. }
  8500. };
  8501. SmartArray.prototype.indexOf = function (value) {
  8502. var position = this.data.indexOf(value);
  8503. if (position >= this.length) {
  8504. return -1;
  8505. }
  8506. return position;
  8507. };
  8508. SmartArray.prototype.contains = function (value) {
  8509. return this.data.indexOf(value) !== -1;
  8510. };
  8511. // Statics
  8512. SmartArray._GlobalId = 0;
  8513. return SmartArray;
  8514. }());
  8515. BABYLON.SmartArray = SmartArray;
  8516. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8517. __extends(SmartArrayNoDuplicate, _super);
  8518. function SmartArrayNoDuplicate() {
  8519. var _this = _super !== null && _super.apply(this, arguments) || this;
  8520. _this._duplicateId = 0;
  8521. return _this;
  8522. }
  8523. SmartArrayNoDuplicate.prototype.push = function (value) {
  8524. _super.prototype.push.call(this, value);
  8525. if (!value.__smartArrayFlags) {
  8526. value.__smartArrayFlags = {};
  8527. }
  8528. value.__smartArrayFlags[this._id] = this._duplicateId;
  8529. };
  8530. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8531. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8532. return false;
  8533. }
  8534. this.push(value);
  8535. return true;
  8536. };
  8537. SmartArrayNoDuplicate.prototype.reset = function () {
  8538. _super.prototype.reset.call(this);
  8539. this._duplicateId++;
  8540. };
  8541. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8542. if (array.length === 0) {
  8543. return;
  8544. }
  8545. if (this.length + array.length > this.data.length) {
  8546. this.data.length = (this.length + array.length) * 2;
  8547. }
  8548. for (var index = 0; index < array.length; index++) {
  8549. var item = (array.data || array)[index];
  8550. this.pushNoDuplicate(item);
  8551. }
  8552. };
  8553. return SmartArrayNoDuplicate;
  8554. }(SmartArray));
  8555. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8556. })(BABYLON || (BABYLON = {}));
  8557. //# sourceMappingURL=babylon.smartArray.js.map
  8558. var BABYLON;
  8559. (function (BABYLON) {
  8560. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8561. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8562. var LoadFileError = /** @class */ (function (_super) {
  8563. __extends(LoadFileError, _super);
  8564. function LoadFileError(message, request) {
  8565. var _this = _super.call(this, message) || this;
  8566. _this.request = request;
  8567. _this.name = "LoadFileError";
  8568. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8569. return _this;
  8570. }
  8571. // Polyfill for Object.setPrototypeOf if necessary.
  8572. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8573. return LoadFileError;
  8574. }(Error));
  8575. BABYLON.LoadFileError = LoadFileError;
  8576. var RetryStrategy = /** @class */ (function () {
  8577. function RetryStrategy() {
  8578. }
  8579. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8580. if (maxRetries === void 0) { maxRetries = 3; }
  8581. if (baseInterval === void 0) { baseInterval = 500; }
  8582. return function (url, request, retryIndex) {
  8583. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8584. return -1;
  8585. }
  8586. return Math.pow(2, retryIndex) * baseInterval;
  8587. };
  8588. };
  8589. return RetryStrategy;
  8590. }());
  8591. BABYLON.RetryStrategy = RetryStrategy;
  8592. // Screenshots
  8593. var screenshotCanvas;
  8594. var cloneValue = function (source, destinationObject) {
  8595. if (!source)
  8596. return null;
  8597. if (source instanceof BABYLON.Mesh) {
  8598. return null;
  8599. }
  8600. if (source instanceof BABYLON.SubMesh) {
  8601. return source.clone(destinationObject);
  8602. }
  8603. else if (source.clone) {
  8604. return source.clone();
  8605. }
  8606. return null;
  8607. };
  8608. var Tools = /** @class */ (function () {
  8609. function Tools() {
  8610. }
  8611. /**
  8612. * Interpolates between a and b via alpha
  8613. * @param a The lower value (returned when alpha = 0)
  8614. * @param b The upper value (returned when alpha = 1)
  8615. * @param alpha The interpolation-factor
  8616. * @return The mixed value
  8617. */
  8618. Tools.Mix = function (a, b, alpha) {
  8619. return a * (1 - alpha) + b * alpha;
  8620. };
  8621. Tools.Instantiate = function (className) {
  8622. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8623. return Tools.RegisteredExternalClasses[className];
  8624. }
  8625. var arr = className.split(".");
  8626. var fn = (window || this);
  8627. for (var i = 0, len = arr.length; i < len; i++) {
  8628. fn = fn[arr[i]];
  8629. }
  8630. if (typeof fn !== "function") {
  8631. return null;
  8632. }
  8633. return fn;
  8634. };
  8635. /**
  8636. * Provides a slice function that will work even on IE
  8637. * @param data defines the array to slice
  8638. * @param start defines the start of the data (optional)
  8639. * @param end defines the end of the data (optional)
  8640. * @returns the new sliced array
  8641. */
  8642. Tools.Slice = function (data, start, end) {
  8643. if (data.slice) {
  8644. return data.slice(start, end);
  8645. }
  8646. return Array.prototype.slice.call(data, start, end);
  8647. };
  8648. Tools.SetImmediate = function (action) {
  8649. if (window.setImmediate) {
  8650. window.setImmediate(action);
  8651. }
  8652. else {
  8653. setTimeout(action, 1);
  8654. }
  8655. };
  8656. Tools.IsExponentOfTwo = function (value) {
  8657. var count = 1;
  8658. do {
  8659. count *= 2;
  8660. } while (count < value);
  8661. return count === value;
  8662. };
  8663. /**
  8664. * Returns the nearest 32-bit single precision float representation of a Number
  8665. * @param value A Number. If the parameter is of a different type, it will get converted
  8666. * to a number or to NaN if it cannot be converted
  8667. * @returns number
  8668. */
  8669. Tools.FloatRound = function (value) {
  8670. if (Math.fround) {
  8671. return Math.fround(value);
  8672. }
  8673. return (Tools._tmpFloatArray[0] = value);
  8674. };
  8675. /**
  8676. * Find the next highest power of two.
  8677. * @param x Number to start search from.
  8678. * @return Next highest power of two.
  8679. */
  8680. Tools.CeilingPOT = function (x) {
  8681. x--;
  8682. x |= x >> 1;
  8683. x |= x >> 2;
  8684. x |= x >> 4;
  8685. x |= x >> 8;
  8686. x |= x >> 16;
  8687. x++;
  8688. return x;
  8689. };
  8690. /**
  8691. * Find the next lowest power of two.
  8692. * @param x Number to start search from.
  8693. * @return Next lowest power of two.
  8694. */
  8695. Tools.FloorPOT = function (x) {
  8696. x = x | (x >> 1);
  8697. x = x | (x >> 2);
  8698. x = x | (x >> 4);
  8699. x = x | (x >> 8);
  8700. x = x | (x >> 16);
  8701. return x - (x >> 1);
  8702. };
  8703. /**
  8704. * Find the nearest power of two.
  8705. * @param x Number to start search from.
  8706. * @return Next nearest power of two.
  8707. */
  8708. Tools.NearestPOT = function (x) {
  8709. var c = Tools.CeilingPOT(x);
  8710. var f = Tools.FloorPOT(x);
  8711. return (c - x) > (x - f) ? f : c;
  8712. };
  8713. Tools.GetExponentOfTwo = function (value, max, mode) {
  8714. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8715. var pot;
  8716. switch (mode) {
  8717. case BABYLON.Engine.SCALEMODE_FLOOR:
  8718. pot = Tools.FloorPOT(value);
  8719. break;
  8720. case BABYLON.Engine.SCALEMODE_NEAREST:
  8721. pot = Tools.NearestPOT(value);
  8722. break;
  8723. case BABYLON.Engine.SCALEMODE_CEILING:
  8724. default:
  8725. pot = Tools.CeilingPOT(value);
  8726. break;
  8727. }
  8728. return Math.min(pot, max);
  8729. };
  8730. Tools.GetFilename = function (path) {
  8731. var index = path.lastIndexOf("/");
  8732. if (index < 0)
  8733. return path;
  8734. return path.substring(index + 1);
  8735. };
  8736. /**
  8737. * Extracts the "folder" part of a path (everything before the filename).
  8738. * @param uri The URI to extract the info from
  8739. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8740. * @returns The "folder" part of the path
  8741. */
  8742. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8743. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8744. var index = uri.lastIndexOf("/");
  8745. if (index < 0) {
  8746. if (returnUnchangedIfNoSlash) {
  8747. return uri;
  8748. }
  8749. return "";
  8750. }
  8751. return uri.substring(0, index + 1);
  8752. };
  8753. Tools.GetDOMTextContent = function (element) {
  8754. var result = "";
  8755. var child = element.firstChild;
  8756. while (child) {
  8757. if (child.nodeType === 3) {
  8758. result += child.textContent;
  8759. }
  8760. child = child.nextSibling;
  8761. }
  8762. return result;
  8763. };
  8764. Tools.ToDegrees = function (angle) {
  8765. return angle * 180 / Math.PI;
  8766. };
  8767. Tools.ToRadians = function (angle) {
  8768. return angle * Math.PI / 180;
  8769. };
  8770. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8771. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8772. var output = "";
  8773. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8774. var i = 0;
  8775. var bytes = new Uint8Array(buffer);
  8776. while (i < bytes.length) {
  8777. chr1 = bytes[i++];
  8778. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8779. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8780. enc1 = chr1 >> 2;
  8781. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8782. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8783. enc4 = chr3 & 63;
  8784. if (isNaN(chr2)) {
  8785. enc3 = enc4 = 64;
  8786. }
  8787. else if (isNaN(chr3)) {
  8788. enc4 = 64;
  8789. }
  8790. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8791. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8792. }
  8793. return "data:image/png;base64," + output;
  8794. };
  8795. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8796. if (bias === void 0) { bias = null; }
  8797. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8798. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8799. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8800. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8801. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8802. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8803. }
  8804. if (bias) {
  8805. minimum.x -= minimum.x * bias.x + bias.y;
  8806. minimum.y -= minimum.y * bias.x + bias.y;
  8807. minimum.z -= minimum.z * bias.x + bias.y;
  8808. maximum.x += maximum.x * bias.x + bias.y;
  8809. maximum.y += maximum.y * bias.x + bias.y;
  8810. maximum.z += maximum.z * bias.x + bias.y;
  8811. }
  8812. return {
  8813. minimum: minimum,
  8814. maximum: maximum
  8815. };
  8816. };
  8817. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8818. if (bias === void 0) { bias = null; }
  8819. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8820. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8821. if (!stride) {
  8822. stride = 3;
  8823. }
  8824. for (var index = start; index < start + count; index++) {
  8825. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8826. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8827. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8828. }
  8829. if (bias) {
  8830. minimum.x -= minimum.x * bias.x + bias.y;
  8831. minimum.y -= minimum.y * bias.x + bias.y;
  8832. minimum.z -= minimum.z * bias.x + bias.y;
  8833. maximum.x += maximum.x * bias.x + bias.y;
  8834. maximum.y += maximum.y * bias.x + bias.y;
  8835. maximum.z += maximum.z * bias.x + bias.y;
  8836. }
  8837. return {
  8838. minimum: minimum,
  8839. maximum: maximum
  8840. };
  8841. };
  8842. Tools.Vector2ArrayFeeder = function (array) {
  8843. return function (index) {
  8844. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8845. var length = isFloatArray ? array.length / 2 : array.length;
  8846. if (index >= length) {
  8847. return null;
  8848. }
  8849. if (isFloatArray) {
  8850. var fa = array;
  8851. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8852. }
  8853. var a = array;
  8854. return a[index];
  8855. };
  8856. };
  8857. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8858. if (bias === void 0) { bias = null; }
  8859. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8860. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8861. var i = 0;
  8862. var cur = feeder(i++);
  8863. while (cur) {
  8864. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8865. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8866. cur = feeder(i++);
  8867. }
  8868. if (bias) {
  8869. minimum.x -= minimum.x * bias.x + bias.y;
  8870. minimum.y -= minimum.y * bias.x + bias.y;
  8871. maximum.x += maximum.x * bias.x + bias.y;
  8872. maximum.y += maximum.y * bias.x + bias.y;
  8873. }
  8874. return {
  8875. minimum: minimum,
  8876. maximum: maximum
  8877. };
  8878. };
  8879. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8880. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8881. return null;
  8882. return Array.isArray(obj) ? obj : [obj];
  8883. };
  8884. // Misc.
  8885. Tools.GetPointerPrefix = function () {
  8886. var eventPrefix = "pointer";
  8887. // Check if pointer events are supported
  8888. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8889. eventPrefix = "mouse";
  8890. }
  8891. return eventPrefix;
  8892. };
  8893. /**
  8894. * @param func - the function to be called
  8895. * @param requester - the object that will request the next frame. Falls back to window.
  8896. */
  8897. Tools.QueueNewFrame = function (func, requester) {
  8898. if (!Tools.IsWindowObjectExist()) {
  8899. return setTimeout(func, 16);
  8900. }
  8901. if (!requester) {
  8902. requester = window;
  8903. }
  8904. if (requester.requestAnimationFrame) {
  8905. return requester.requestAnimationFrame(func);
  8906. }
  8907. else if (requester.msRequestAnimationFrame) {
  8908. return requester.msRequestAnimationFrame(func);
  8909. }
  8910. else if (requester.webkitRequestAnimationFrame) {
  8911. return requester.webkitRequestAnimationFrame(func);
  8912. }
  8913. else if (requester.mozRequestAnimationFrame) {
  8914. return requester.mozRequestAnimationFrame(func);
  8915. }
  8916. else if (requester.oRequestAnimationFrame) {
  8917. return requester.oRequestAnimationFrame(func);
  8918. }
  8919. else {
  8920. return window.setTimeout(func, 16);
  8921. }
  8922. };
  8923. Tools.RequestFullscreen = function (element) {
  8924. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8925. if (!requestFunction)
  8926. return;
  8927. requestFunction.call(element);
  8928. };
  8929. Tools.ExitFullscreen = function () {
  8930. if (document.exitFullscreen) {
  8931. document.exitFullscreen();
  8932. }
  8933. else if (document.mozCancelFullScreen) {
  8934. document.mozCancelFullScreen();
  8935. }
  8936. else if (document.webkitCancelFullScreen) {
  8937. document.webkitCancelFullScreen();
  8938. }
  8939. else if (document.msCancelFullScreen) {
  8940. document.msCancelFullScreen();
  8941. }
  8942. };
  8943. Tools.SetCorsBehavior = function (url, element) {
  8944. if (url && url.indexOf("data:") === 0) {
  8945. return;
  8946. }
  8947. if (Tools.CorsBehavior) {
  8948. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8949. element.crossOrigin = Tools.CorsBehavior;
  8950. }
  8951. else {
  8952. var result = Tools.CorsBehavior(url);
  8953. if (result) {
  8954. element.crossOrigin = result;
  8955. }
  8956. }
  8957. }
  8958. };
  8959. // External files
  8960. Tools.CleanUrl = function (url) {
  8961. url = url.replace(/#/mg, "%23");
  8962. return url;
  8963. };
  8964. Tools.LoadImage = function (url, onLoad, onError, database) {
  8965. if (url instanceof ArrayBuffer) {
  8966. url = Tools.EncodeArrayBufferTobase64(url);
  8967. }
  8968. url = Tools.CleanUrl(url);
  8969. url = Tools.PreprocessUrl(url);
  8970. var img = new Image();
  8971. Tools.SetCorsBehavior(url, img);
  8972. var loadHandler = function () {
  8973. img.removeEventListener("load", loadHandler);
  8974. img.removeEventListener("error", errorHandler);
  8975. onLoad(img);
  8976. };
  8977. var errorHandler = function (err) {
  8978. img.removeEventListener("load", loadHandler);
  8979. img.removeEventListener("error", errorHandler);
  8980. Tools.Error("Error while trying to load image: " + url);
  8981. if (onError) {
  8982. onError("Error while trying to load image: " + url, err);
  8983. }
  8984. };
  8985. img.addEventListener("load", loadHandler);
  8986. img.addEventListener("error", errorHandler);
  8987. var noIndexedDB = function () {
  8988. img.src = url;
  8989. };
  8990. var loadFromIndexedDB = function () {
  8991. if (database) {
  8992. database.loadImageFromDB(url, img);
  8993. }
  8994. };
  8995. //ANY database to do!
  8996. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8997. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8998. }
  8999. else {
  9000. if (url.indexOf("file:") !== -1) {
  9001. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9002. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9003. try {
  9004. var blobURL;
  9005. try {
  9006. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9007. }
  9008. catch (ex) {
  9009. // Chrome doesn't support oneTimeOnly parameter
  9010. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9011. }
  9012. img.src = blobURL;
  9013. }
  9014. catch (e) {
  9015. img.src = "";
  9016. }
  9017. return img;
  9018. }
  9019. }
  9020. noIndexedDB();
  9021. }
  9022. return img;
  9023. };
  9024. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9025. url = Tools.CleanUrl(url);
  9026. url = Tools.PreprocessUrl(url);
  9027. // If file and file input are set
  9028. if (url.indexOf("file:") !== -1) {
  9029. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9030. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9031. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9032. }
  9033. }
  9034. var loadUrl = Tools.BaseUrl + url;
  9035. var aborted = false;
  9036. var fileRequest = {
  9037. onCompleteObservable: new BABYLON.Observable(),
  9038. abort: function () { return aborted = true; },
  9039. };
  9040. var requestFile = function () {
  9041. var request = new XMLHttpRequest();
  9042. var retryHandle = null;
  9043. fileRequest.abort = function () {
  9044. aborted = true;
  9045. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9046. request.abort();
  9047. }
  9048. if (retryHandle !== null) {
  9049. clearTimeout(retryHandle);
  9050. retryHandle = null;
  9051. }
  9052. };
  9053. var retryLoop = function (retryIndex) {
  9054. request.open('GET', loadUrl, true);
  9055. if (useArrayBuffer) {
  9056. request.responseType = "arraybuffer";
  9057. }
  9058. if (onProgress) {
  9059. request.addEventListener("progress", onProgress);
  9060. }
  9061. var onLoadEnd = function () {
  9062. request.removeEventListener("loadend", onLoadEnd);
  9063. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9064. fileRequest.onCompleteObservable.clear();
  9065. };
  9066. request.addEventListener("loadend", onLoadEnd);
  9067. var onReadyStateChange = function () {
  9068. if (aborted) {
  9069. return;
  9070. }
  9071. // In case of undefined state in some browsers.
  9072. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9073. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9074. request.removeEventListener("readystatechange", onReadyStateChange);
  9075. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9076. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9077. return;
  9078. }
  9079. var retryStrategy = Tools.DefaultRetryStrategy;
  9080. if (retryStrategy) {
  9081. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9082. if (waitTime !== -1) {
  9083. // Prevent the request from completing for retry.
  9084. request.removeEventListener("loadend", onLoadEnd);
  9085. request = new XMLHttpRequest();
  9086. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9087. return;
  9088. }
  9089. }
  9090. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9091. if (onError) {
  9092. onError(request, e);
  9093. }
  9094. else {
  9095. throw e;
  9096. }
  9097. }
  9098. };
  9099. request.addEventListener("readystatechange", onReadyStateChange);
  9100. request.send();
  9101. };
  9102. retryLoop(0);
  9103. };
  9104. // Caching all files
  9105. if (database && database.enableSceneOffline) {
  9106. var noIndexedDB_1 = function () {
  9107. if (!aborted) {
  9108. requestFile();
  9109. }
  9110. };
  9111. var loadFromIndexedDB = function () {
  9112. // TODO: database needs to support aborting and should return a IFileRequest
  9113. if (aborted) {
  9114. return;
  9115. }
  9116. if (database) {
  9117. database.loadFileFromDB(url, function (data) {
  9118. if (!aborted) {
  9119. onSuccess(data);
  9120. }
  9121. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9122. }, onProgress ? function (event) {
  9123. if (!aborted) {
  9124. onProgress(event);
  9125. }
  9126. } : undefined, noIndexedDB_1, useArrayBuffer);
  9127. }
  9128. };
  9129. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9130. }
  9131. else {
  9132. requestFile();
  9133. }
  9134. return fileRequest;
  9135. };
  9136. /**
  9137. * Load a script (identified by an url). When the url returns, the
  9138. * content of this file is added into a new script element, attached to the DOM (body element)
  9139. */
  9140. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9141. var head = document.getElementsByTagName('head')[0];
  9142. var script = document.createElement('script');
  9143. script.type = 'text/javascript';
  9144. script.src = scriptUrl;
  9145. script.onload = function () {
  9146. if (onSuccess) {
  9147. onSuccess();
  9148. }
  9149. };
  9150. script.onerror = function (e) {
  9151. if (onError) {
  9152. onError("Unable to load script '" + scriptUrl + "'", e);
  9153. }
  9154. };
  9155. head.appendChild(script);
  9156. };
  9157. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9158. var reader = new FileReader();
  9159. var request = {
  9160. onCompleteObservable: new BABYLON.Observable(),
  9161. abort: function () { return reader.abort(); },
  9162. };
  9163. reader.onloadend = function (e) {
  9164. request.onCompleteObservable.notifyObservers(request);
  9165. };
  9166. reader.onload = function (e) {
  9167. //target doesn't have result from ts 1.3
  9168. callback(e.target['result']);
  9169. };
  9170. reader.onprogress = progressCallback;
  9171. reader.readAsDataURL(fileToLoad);
  9172. return request;
  9173. };
  9174. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9175. var reader = new FileReader();
  9176. var request = {
  9177. onCompleteObservable: new BABYLON.Observable(),
  9178. abort: function () { return reader.abort(); },
  9179. };
  9180. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9181. reader.onerror = function (e) {
  9182. Tools.Log("Error while reading file: " + fileToLoad.name);
  9183. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9184. };
  9185. reader.onload = function (e) {
  9186. //target doesn't have result from ts 1.3
  9187. callback(e.target['result']);
  9188. };
  9189. if (progressCallBack) {
  9190. reader.onprogress = progressCallBack;
  9191. }
  9192. if (!useArrayBuffer) {
  9193. // Asynchronous read
  9194. reader.readAsText(fileToLoad);
  9195. }
  9196. else {
  9197. reader.readAsArrayBuffer(fileToLoad);
  9198. }
  9199. return request;
  9200. };
  9201. //returns a downloadable url to a file content.
  9202. Tools.FileAsURL = function (content) {
  9203. var fileBlob = new Blob([content]);
  9204. var url = window.URL || window.webkitURL;
  9205. var link = url.createObjectURL(fileBlob);
  9206. return link;
  9207. };
  9208. // Misc.
  9209. Tools.Format = function (value, decimals) {
  9210. if (decimals === void 0) { decimals = 2; }
  9211. return value.toFixed(decimals);
  9212. };
  9213. Tools.CheckExtends = function (v, min, max) {
  9214. if (v.x < min.x)
  9215. min.x = v.x;
  9216. if (v.y < min.y)
  9217. min.y = v.y;
  9218. if (v.z < min.z)
  9219. min.z = v.z;
  9220. if (v.x > max.x)
  9221. max.x = v.x;
  9222. if (v.y > max.y)
  9223. max.y = v.y;
  9224. if (v.z > max.z)
  9225. max.z = v.z;
  9226. };
  9227. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9228. for (var prop in source) {
  9229. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9230. continue;
  9231. }
  9232. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9233. continue;
  9234. }
  9235. var sourceValue = source[prop];
  9236. var typeOfSourceValue = typeof sourceValue;
  9237. if (typeOfSourceValue === "function") {
  9238. continue;
  9239. }
  9240. try {
  9241. if (typeOfSourceValue === "object") {
  9242. if (sourceValue instanceof Array) {
  9243. destination[prop] = [];
  9244. if (sourceValue.length > 0) {
  9245. if (typeof sourceValue[0] == "object") {
  9246. for (var index = 0; index < sourceValue.length; index++) {
  9247. var clonedValue = cloneValue(sourceValue[index], destination);
  9248. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9249. destination[prop].push(clonedValue);
  9250. }
  9251. }
  9252. }
  9253. else {
  9254. destination[prop] = sourceValue.slice(0);
  9255. }
  9256. }
  9257. }
  9258. else {
  9259. destination[prop] = cloneValue(sourceValue, destination);
  9260. }
  9261. }
  9262. else {
  9263. destination[prop] = sourceValue;
  9264. }
  9265. }
  9266. catch (e) {
  9267. // Just ignore error (it could be because of a read-only property)
  9268. }
  9269. }
  9270. };
  9271. Tools.IsEmpty = function (obj) {
  9272. for (var i in obj) {
  9273. if (obj.hasOwnProperty(i)) {
  9274. return false;
  9275. }
  9276. }
  9277. return true;
  9278. };
  9279. Tools.RegisterTopRootEvents = function (events) {
  9280. for (var index = 0; index < events.length; index++) {
  9281. var event = events[index];
  9282. window.addEventListener(event.name, event.handler, false);
  9283. try {
  9284. if (window.parent) {
  9285. window.parent.addEventListener(event.name, event.handler, false);
  9286. }
  9287. }
  9288. catch (e) {
  9289. // Silently fails...
  9290. }
  9291. }
  9292. };
  9293. Tools.UnregisterTopRootEvents = function (events) {
  9294. for (var index = 0; index < events.length; index++) {
  9295. var event = events[index];
  9296. window.removeEventListener(event.name, event.handler);
  9297. try {
  9298. if (window.parent) {
  9299. window.parent.removeEventListener(event.name, event.handler);
  9300. }
  9301. }
  9302. catch (e) {
  9303. // Silently fails...
  9304. }
  9305. }
  9306. };
  9307. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9308. if (mimeType === void 0) { mimeType = "image/png"; }
  9309. // Read the contents of the framebuffer
  9310. var numberOfChannelsByLine = width * 4;
  9311. var halfHeight = height / 2;
  9312. //Reading datas from WebGL
  9313. var data = engine.readPixels(0, 0, width, height);
  9314. //To flip image on Y axis.
  9315. for (var i = 0; i < halfHeight; i++) {
  9316. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9317. var currentCell = j + i * numberOfChannelsByLine;
  9318. var targetLine = height - i - 1;
  9319. var targetCell = j + targetLine * numberOfChannelsByLine;
  9320. var temp = data[currentCell];
  9321. data[currentCell] = data[targetCell];
  9322. data[targetCell] = temp;
  9323. }
  9324. }
  9325. // Create a 2D canvas to store the result
  9326. if (!screenshotCanvas) {
  9327. screenshotCanvas = document.createElement('canvas');
  9328. }
  9329. screenshotCanvas.width = width;
  9330. screenshotCanvas.height = height;
  9331. var context = screenshotCanvas.getContext('2d');
  9332. if (context) {
  9333. // Copy the pixels to a 2D canvas
  9334. var imageData = context.createImageData(width, height);
  9335. var castData = (imageData.data);
  9336. castData.set(data);
  9337. context.putImageData(imageData, 0, 0);
  9338. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9339. }
  9340. };
  9341. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9342. if (mimeType === void 0) { mimeType = "image/png"; }
  9343. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9344. if (successCallback) {
  9345. successCallback(base64Image);
  9346. }
  9347. else {
  9348. // We need HTMLCanvasElement.toBlob for HD screenshots
  9349. if (!screenshotCanvas.toBlob) {
  9350. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9351. screenshotCanvas.toBlob = function (callback, type, quality) {
  9352. var _this = this;
  9353. setTimeout(function () {
  9354. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9355. for (var i = 0; i < len; i++) {
  9356. arr[i] = binStr.charCodeAt(i);
  9357. }
  9358. callback(new Blob([arr], { type: type || 'image/png' }));
  9359. });
  9360. };
  9361. }
  9362. screenshotCanvas.toBlob(function (blob) {
  9363. var url = URL.createObjectURL(blob);
  9364. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9365. if (("download" in document.createElement("a"))) {
  9366. var a = window.document.createElement("a");
  9367. a.href = url;
  9368. if (fileName) {
  9369. a.setAttribute("download", fileName);
  9370. }
  9371. else {
  9372. var date = new Date();
  9373. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9374. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9375. }
  9376. window.document.body.appendChild(a);
  9377. a.addEventListener("click", function () {
  9378. if (a.parentElement) {
  9379. a.parentElement.removeChild(a);
  9380. }
  9381. });
  9382. a.click();
  9383. }
  9384. else {
  9385. var newWindow = window.open("");
  9386. if (!newWindow)
  9387. return;
  9388. var img = newWindow.document.createElement("img");
  9389. img.onload = function () {
  9390. // no longer need to read the blob so it's revoked
  9391. URL.revokeObjectURL(url);
  9392. };
  9393. img.src = url;
  9394. newWindow.document.body.appendChild(img);
  9395. }
  9396. });
  9397. }
  9398. };
  9399. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9400. if (mimeType === void 0) { mimeType = "image/png"; }
  9401. var width;
  9402. var height;
  9403. // If a precision value is specified
  9404. if (size.precision) {
  9405. width = Math.round(engine.getRenderWidth() * size.precision);
  9406. height = Math.round(width / engine.getAspectRatio(camera));
  9407. }
  9408. else if (size.width && size.height) {
  9409. width = size.width;
  9410. height = size.height;
  9411. }
  9412. //If passing only width, computing height to keep display canvas ratio.
  9413. else if (size.width && !size.height) {
  9414. width = size.width;
  9415. height = Math.round(width / engine.getAspectRatio(camera));
  9416. }
  9417. //If passing only height, computing width to keep display canvas ratio.
  9418. else if (size.height && !size.width) {
  9419. height = size.height;
  9420. width = Math.round(height * engine.getAspectRatio(camera));
  9421. }
  9422. //Assuming here that "size" parameter is a number
  9423. else if (!isNaN(size)) {
  9424. height = size;
  9425. width = size;
  9426. }
  9427. else {
  9428. Tools.Error("Invalid 'size' parameter !");
  9429. return;
  9430. }
  9431. if (!screenshotCanvas) {
  9432. screenshotCanvas = document.createElement('canvas');
  9433. }
  9434. screenshotCanvas.width = width;
  9435. screenshotCanvas.height = height;
  9436. var renderContext = screenshotCanvas.getContext("2d");
  9437. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9438. var newWidth = width;
  9439. var newHeight = newWidth / ratio;
  9440. if (newHeight > height) {
  9441. newHeight = height;
  9442. newWidth = newHeight * ratio;
  9443. }
  9444. var offsetX = Math.max(0, width - newWidth) / 2;
  9445. var offsetY = Math.max(0, height - newHeight) / 2;
  9446. var renderingCanvas = engine.getRenderingCanvas();
  9447. if (renderContext && renderingCanvas) {
  9448. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9449. }
  9450. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9451. };
  9452. /**
  9453. * Generates an image screenshot from the specified camera.
  9454. *
  9455. * @param engine The engine to use for rendering
  9456. * @param camera The camera to use for rendering
  9457. * @param size This parameter can be set to a single number or to an object with the
  9458. * following (optional) properties: precision, width, height. If a single number is passed,
  9459. * it will be used for both width and height. If an object is passed, the screenshot size
  9460. * will be derived from the parameters. The precision property is a multiplier allowing
  9461. * rendering at a higher or lower resolution.
  9462. * @param successCallback The callback receives a single parameter which contains the
  9463. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9464. * src parameter of an <img> to display it.
  9465. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9466. * Check your browser for supported MIME types.
  9467. * @param samples Texture samples (default: 1)
  9468. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9469. * @param fileName A name for for the downloaded file.
  9470. * @constructor
  9471. */
  9472. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9473. if (mimeType === void 0) { mimeType = "image/png"; }
  9474. if (samples === void 0) { samples = 1; }
  9475. if (antialiasing === void 0) { antialiasing = false; }
  9476. var width;
  9477. var height;
  9478. //If a precision value is specified
  9479. if (size.precision) {
  9480. width = Math.round(engine.getRenderWidth() * size.precision);
  9481. height = Math.round(width / engine.getAspectRatio(camera));
  9482. size = { width: width, height: height };
  9483. }
  9484. else if (size.width && size.height) {
  9485. width = size.width;
  9486. height = size.height;
  9487. }
  9488. //If passing only width, computing height to keep display canvas ratio.
  9489. else if (size.width && !size.height) {
  9490. width = size.width;
  9491. height = Math.round(width / engine.getAspectRatio(camera));
  9492. size = { width: width, height: height };
  9493. }
  9494. //If passing only height, computing width to keep display canvas ratio.
  9495. else if (size.height && !size.width) {
  9496. height = size.height;
  9497. width = Math.round(height * engine.getAspectRatio(camera));
  9498. size = { width: width, height: height };
  9499. }
  9500. //Assuming here that "size" parameter is a number
  9501. else if (!isNaN(size)) {
  9502. height = size;
  9503. width = size;
  9504. }
  9505. else {
  9506. Tools.Error("Invalid 'size' parameter !");
  9507. return;
  9508. }
  9509. var scene = camera.getScene();
  9510. var previousCamera = null;
  9511. if (scene.activeCamera !== camera) {
  9512. previousCamera = scene.activeCamera;
  9513. scene.activeCamera = camera;
  9514. }
  9515. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9516. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9517. texture.renderList = null;
  9518. texture.samples = samples;
  9519. if (antialiasing) {
  9520. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9521. }
  9522. texture.onAfterRenderObservable.add(function () {
  9523. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9524. });
  9525. scene.incrementRenderId();
  9526. scene.resetCachedMaterial();
  9527. texture.render(true);
  9528. texture.dispose();
  9529. if (previousCamera) {
  9530. scene.activeCamera = previousCamera;
  9531. }
  9532. camera.getProjectionMatrix(true); // Force cache refresh;
  9533. };
  9534. // XHR response validator for local file scenario
  9535. Tools.ValidateXHRData = function (xhr, dataType) {
  9536. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9537. if (dataType === void 0) { dataType = 7; }
  9538. try {
  9539. if (dataType & 1) {
  9540. if (xhr.responseText && xhr.responseText.length > 0) {
  9541. return true;
  9542. }
  9543. else if (dataType === 1) {
  9544. return false;
  9545. }
  9546. }
  9547. if (dataType & 2) {
  9548. // Check header width and height since there is no "TGA" magic number
  9549. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9550. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9551. return true;
  9552. }
  9553. else if (dataType === 2) {
  9554. return false;
  9555. }
  9556. }
  9557. if (dataType & 4) {
  9558. // Check for the "DDS" magic number
  9559. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9560. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9561. return true;
  9562. }
  9563. else {
  9564. return false;
  9565. }
  9566. }
  9567. }
  9568. catch (e) {
  9569. // Global protection
  9570. }
  9571. return false;
  9572. };
  9573. /**
  9574. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9575. * Be aware Math.random() could cause collisions, but:
  9576. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9577. */
  9578. Tools.RandomId = function () {
  9579. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9580. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9581. return v.toString(16);
  9582. });
  9583. };
  9584. /**
  9585. * Test if the given uri is a base64 string.
  9586. * @param uri The uri to test
  9587. * @return True if the uri is a base64 string or false otherwise.
  9588. */
  9589. Tools.IsBase64 = function (uri) {
  9590. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9591. };
  9592. /**
  9593. * Decode the given base64 uri.
  9594. * @param uri The uri to decode
  9595. * @return The decoded base64 data.
  9596. */
  9597. Tools.DecodeBase64 = function (uri) {
  9598. var decodedString = atob(uri.split(",")[1]);
  9599. var bufferLength = decodedString.length;
  9600. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9601. for (var i = 0; i < bufferLength; i++) {
  9602. bufferView[i] = decodedString.charCodeAt(i);
  9603. }
  9604. return bufferView.buffer;
  9605. };
  9606. Object.defineProperty(Tools, "NoneLogLevel", {
  9607. get: function () {
  9608. return Tools._NoneLogLevel;
  9609. },
  9610. enumerable: true,
  9611. configurable: true
  9612. });
  9613. Object.defineProperty(Tools, "MessageLogLevel", {
  9614. get: function () {
  9615. return Tools._MessageLogLevel;
  9616. },
  9617. enumerable: true,
  9618. configurable: true
  9619. });
  9620. Object.defineProperty(Tools, "WarningLogLevel", {
  9621. get: function () {
  9622. return Tools._WarningLogLevel;
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. Object.defineProperty(Tools, "ErrorLogLevel", {
  9628. get: function () {
  9629. return Tools._ErrorLogLevel;
  9630. },
  9631. enumerable: true,
  9632. configurable: true
  9633. });
  9634. Object.defineProperty(Tools, "AllLogLevel", {
  9635. get: function () {
  9636. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9637. },
  9638. enumerable: true,
  9639. configurable: true
  9640. });
  9641. Tools._AddLogEntry = function (entry) {
  9642. Tools._LogCache = entry + Tools._LogCache;
  9643. if (Tools.OnNewCacheEntry) {
  9644. Tools.OnNewCacheEntry(entry);
  9645. }
  9646. };
  9647. Tools._FormatMessage = function (message) {
  9648. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9649. var date = new Date();
  9650. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9651. };
  9652. Tools._LogDisabled = function (message) {
  9653. // nothing to do
  9654. };
  9655. Tools._LogEnabled = function (message) {
  9656. var formattedMessage = Tools._FormatMessage(message);
  9657. console.log("BJS - " + formattedMessage);
  9658. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9659. Tools._AddLogEntry(entry);
  9660. };
  9661. Tools._WarnDisabled = function (message) {
  9662. // nothing to do
  9663. };
  9664. Tools._WarnEnabled = function (message) {
  9665. var formattedMessage = Tools._FormatMessage(message);
  9666. console.warn("BJS - " + formattedMessage);
  9667. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9668. Tools._AddLogEntry(entry);
  9669. };
  9670. Tools._ErrorDisabled = function (message) {
  9671. // nothing to do
  9672. };
  9673. Tools._ErrorEnabled = function (message) {
  9674. Tools.errorsCount++;
  9675. var formattedMessage = Tools._FormatMessage(message);
  9676. console.error("BJS - " + formattedMessage);
  9677. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9678. Tools._AddLogEntry(entry);
  9679. };
  9680. Object.defineProperty(Tools, "LogCache", {
  9681. get: function () {
  9682. return Tools._LogCache;
  9683. },
  9684. enumerable: true,
  9685. configurable: true
  9686. });
  9687. Tools.ClearLogCache = function () {
  9688. Tools._LogCache = "";
  9689. Tools.errorsCount = 0;
  9690. };
  9691. Object.defineProperty(Tools, "LogLevels", {
  9692. set: function (level) {
  9693. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9694. Tools.Log = Tools._LogEnabled;
  9695. }
  9696. else {
  9697. Tools.Log = Tools._LogDisabled;
  9698. }
  9699. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9700. Tools.Warn = Tools._WarnEnabled;
  9701. }
  9702. else {
  9703. Tools.Warn = Tools._WarnDisabled;
  9704. }
  9705. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9706. Tools.Error = Tools._ErrorEnabled;
  9707. }
  9708. else {
  9709. Tools.Error = Tools._ErrorDisabled;
  9710. }
  9711. },
  9712. enumerable: true,
  9713. configurable: true
  9714. });
  9715. Tools.IsWindowObjectExist = function () {
  9716. return (typeof window) !== "undefined";
  9717. };
  9718. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9719. get: function () {
  9720. return Tools._PerformanceNoneLogLevel;
  9721. },
  9722. enumerable: true,
  9723. configurable: true
  9724. });
  9725. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9726. get: function () {
  9727. return Tools._PerformanceUserMarkLogLevel;
  9728. },
  9729. enumerable: true,
  9730. configurable: true
  9731. });
  9732. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9733. get: function () {
  9734. return Tools._PerformanceConsoleLogLevel;
  9735. },
  9736. enumerable: true,
  9737. configurable: true
  9738. });
  9739. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9740. set: function (level) {
  9741. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9742. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9743. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9744. return;
  9745. }
  9746. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9747. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9748. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9749. return;
  9750. }
  9751. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9752. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9758. };
  9759. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9760. };
  9761. Tools._StartUserMark = function (counterName, condition) {
  9762. if (condition === void 0) { condition = true; }
  9763. if (!Tools._performance) {
  9764. if (!Tools.IsWindowObjectExist()) {
  9765. return;
  9766. }
  9767. Tools._performance = window.performance;
  9768. }
  9769. if (!condition || !Tools._performance.mark) {
  9770. return;
  9771. }
  9772. Tools._performance.mark(counterName + "-Begin");
  9773. };
  9774. Tools._EndUserMark = function (counterName, condition) {
  9775. if (condition === void 0) { condition = true; }
  9776. if (!condition || !Tools._performance.mark) {
  9777. return;
  9778. }
  9779. Tools._performance.mark(counterName + "-End");
  9780. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9781. };
  9782. Tools._StartPerformanceConsole = function (counterName, condition) {
  9783. if (condition === void 0) { condition = true; }
  9784. if (!condition) {
  9785. return;
  9786. }
  9787. Tools._StartUserMark(counterName, condition);
  9788. if (console.time) {
  9789. console.time(counterName);
  9790. }
  9791. };
  9792. Tools._EndPerformanceConsole = function (counterName, condition) {
  9793. if (condition === void 0) { condition = true; }
  9794. if (!condition) {
  9795. return;
  9796. }
  9797. Tools._EndUserMark(counterName, condition);
  9798. if (console.time) {
  9799. console.timeEnd(counterName);
  9800. }
  9801. };
  9802. Object.defineProperty(Tools, "Now", {
  9803. get: function () {
  9804. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9805. return window.performance.now();
  9806. }
  9807. return Date.now();
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. /**
  9813. * This method will return the name of the class used to create the instance of the given object.
  9814. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9815. * @param object the object to get the class name from
  9816. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9817. */
  9818. Tools.GetClassName = function (object, isType) {
  9819. if (isType === void 0) { isType = false; }
  9820. var name = null;
  9821. if (!isType && object.getClassName) {
  9822. name = object.getClassName();
  9823. }
  9824. else {
  9825. if (object instanceof Object) {
  9826. var classObj = isType ? object : Object.getPrototypeOf(object);
  9827. name = classObj.constructor["__bjsclassName__"];
  9828. }
  9829. if (!name) {
  9830. name = typeof object;
  9831. }
  9832. }
  9833. return name;
  9834. };
  9835. Tools.First = function (array, predicate) {
  9836. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9837. var el = array_1[_i];
  9838. if (predicate(el)) {
  9839. return el;
  9840. }
  9841. }
  9842. return null;
  9843. };
  9844. /**
  9845. * This method will return the name of the full name of the class, including its owning module (if any).
  9846. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9847. * @param object the object to get the class name from
  9848. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9849. */
  9850. Tools.getFullClassName = function (object, isType) {
  9851. if (isType === void 0) { isType = false; }
  9852. var className = null;
  9853. var moduleName = null;
  9854. if (!isType && object.getClassName) {
  9855. className = object.getClassName();
  9856. }
  9857. else {
  9858. if (object instanceof Object) {
  9859. var classObj = isType ? object : Object.getPrototypeOf(object);
  9860. className = classObj.constructor["__bjsclassName__"];
  9861. moduleName = classObj.constructor["__bjsmoduleName__"];
  9862. }
  9863. if (!className) {
  9864. className = typeof object;
  9865. }
  9866. }
  9867. if (!className) {
  9868. return null;
  9869. }
  9870. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9871. };
  9872. /**
  9873. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9874. * @param array
  9875. */
  9876. Tools.arrayOrStringFeeder = function (array) {
  9877. return function (index) {
  9878. if (index >= array.length) {
  9879. return null;
  9880. }
  9881. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9882. if (val && val.getHashCode) {
  9883. val = val.getHashCode();
  9884. }
  9885. if (typeof val === "string") {
  9886. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9887. }
  9888. return val;
  9889. };
  9890. };
  9891. /**
  9892. * Compute the hashCode of a stream of number
  9893. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9894. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9895. * @return the hash code computed
  9896. */
  9897. Tools.hashCodeFromStream = function (feeder) {
  9898. // Based from here: http://stackoverflow.com/a/7616484/802124
  9899. var hash = 0;
  9900. var index = 0;
  9901. var chr = feeder(index++);
  9902. while (chr != null) {
  9903. hash = ((hash << 5) - hash) + chr;
  9904. hash |= 0; // Convert to 32bit integer
  9905. chr = feeder(index++);
  9906. }
  9907. return hash;
  9908. };
  9909. /**
  9910. * Returns a promise that resolves after the given amount of time.
  9911. * @param delay Number of milliseconds to delay
  9912. * @returns Promise that resolves after the given amount of time
  9913. */
  9914. Tools.DelayAsync = function (delay) {
  9915. return new Promise(function (resolve) {
  9916. setTimeout(function () {
  9917. resolve();
  9918. }, delay);
  9919. });
  9920. };
  9921. Tools.BaseUrl = "";
  9922. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9923. /**
  9924. * Default behaviour for cors in the application.
  9925. * It can be a string if the expected behavior is identical in the entire app.
  9926. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9927. */
  9928. Tools.CorsBehavior = "anonymous";
  9929. Tools.UseFallbackTexture = true;
  9930. /**
  9931. * Use this object to register external classes like custom textures or material
  9932. * to allow the laoders to instantiate them
  9933. */
  9934. Tools.RegisteredExternalClasses = {};
  9935. // Used in case of a texture loading problem
  9936. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9937. Tools._tmpFloatArray = new Float32Array(1);
  9938. Tools.PreprocessUrl = function (url) {
  9939. return url;
  9940. };
  9941. // Logs
  9942. Tools._NoneLogLevel = 0;
  9943. Tools._MessageLogLevel = 1;
  9944. Tools._WarningLogLevel = 2;
  9945. Tools._ErrorLogLevel = 4;
  9946. Tools._LogCache = "";
  9947. Tools.errorsCount = 0;
  9948. Tools.Log = Tools._LogEnabled;
  9949. Tools.Warn = Tools._WarnEnabled;
  9950. Tools.Error = Tools._ErrorEnabled;
  9951. // Performances
  9952. Tools._PerformanceNoneLogLevel = 0;
  9953. Tools._PerformanceUserMarkLogLevel = 1;
  9954. Tools._PerformanceConsoleLogLevel = 2;
  9955. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9956. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9957. return Tools;
  9958. }());
  9959. BABYLON.Tools = Tools;
  9960. /**
  9961. * This class is used to track a performance counter which is number based.
  9962. * The user has access to many properties which give statistics of different nature
  9963. *
  9964. * The implementer can track two kinds of Performance Counter: time and count
  9965. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  9966. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  9967. */
  9968. var PerfCounter = /** @class */ (function () {
  9969. function PerfCounter() {
  9970. this._startMonitoringTime = 0;
  9971. this._min = 0;
  9972. this._max = 0;
  9973. this._average = 0;
  9974. this._lastSecAverage = 0;
  9975. this._current = 0;
  9976. this._totalValueCount = 0;
  9977. this._totalAccumulated = 0;
  9978. this._lastSecAccumulated = 0;
  9979. this._lastSecTime = 0;
  9980. this._lastSecValueCount = 0;
  9981. }
  9982. Object.defineProperty(PerfCounter.prototype, "min", {
  9983. /**
  9984. * Returns the smallest value ever
  9985. */
  9986. get: function () {
  9987. return this._min;
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Object.defineProperty(PerfCounter.prototype, "max", {
  9993. /**
  9994. * Returns the biggest value ever
  9995. */
  9996. get: function () {
  9997. return this._max;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Object.defineProperty(PerfCounter.prototype, "average", {
  10003. /**
  10004. * Returns the average value since the performance counter is running
  10005. */
  10006. get: function () {
  10007. return this._average;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10013. /**
  10014. * Returns the average value of the last second the counter was monitored
  10015. */
  10016. get: function () {
  10017. return this._lastSecAverage;
  10018. },
  10019. enumerable: true,
  10020. configurable: true
  10021. });
  10022. Object.defineProperty(PerfCounter.prototype, "current", {
  10023. /**
  10024. * Returns the current value
  10025. */
  10026. get: function () {
  10027. return this._current;
  10028. },
  10029. enumerable: true,
  10030. configurable: true
  10031. });
  10032. Object.defineProperty(PerfCounter.prototype, "total", {
  10033. get: function () {
  10034. return this._totalAccumulated;
  10035. },
  10036. enumerable: true,
  10037. configurable: true
  10038. });
  10039. Object.defineProperty(PerfCounter.prototype, "count", {
  10040. get: function () {
  10041. return this._totalValueCount;
  10042. },
  10043. enumerable: true,
  10044. configurable: true
  10045. });
  10046. /**
  10047. * Call this method to start monitoring a new frame.
  10048. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  10049. */
  10050. PerfCounter.prototype.fetchNewFrame = function () {
  10051. this._totalValueCount++;
  10052. this._current = 0;
  10053. this._lastSecValueCount++;
  10054. };
  10055. /**
  10056. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10057. * @param newCount the count value to add to the monitored count
  10058. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  10059. */
  10060. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10061. if (!PerfCounter.Enabled) {
  10062. return;
  10063. }
  10064. this._current += newCount;
  10065. if (fetchResult) {
  10066. this._fetchResult();
  10067. }
  10068. };
  10069. /**
  10070. * Start monitoring this performance counter
  10071. */
  10072. PerfCounter.prototype.beginMonitoring = function () {
  10073. if (!PerfCounter.Enabled) {
  10074. return;
  10075. }
  10076. this._startMonitoringTime = Tools.Now;
  10077. };
  10078. /**
  10079. * Compute the time lapsed since the previous beginMonitoring() call.
  10080. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  10081. */
  10082. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10083. if (newFrame === void 0) { newFrame = true; }
  10084. if (!PerfCounter.Enabled) {
  10085. return;
  10086. }
  10087. if (newFrame) {
  10088. this.fetchNewFrame();
  10089. }
  10090. var currentTime = Tools.Now;
  10091. this._current = currentTime - this._startMonitoringTime;
  10092. if (newFrame) {
  10093. this._fetchResult();
  10094. }
  10095. };
  10096. PerfCounter.prototype._fetchResult = function () {
  10097. this._totalAccumulated += this._current;
  10098. this._lastSecAccumulated += this._current;
  10099. // Min/Max update
  10100. this._min = Math.min(this._min, this._current);
  10101. this._max = Math.max(this._max, this._current);
  10102. this._average = this._totalAccumulated / this._totalValueCount;
  10103. // Reset last sec?
  10104. var now = Tools.Now;
  10105. if ((now - this._lastSecTime) > 1000) {
  10106. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10107. this._lastSecTime = now;
  10108. this._lastSecAccumulated = 0;
  10109. this._lastSecValueCount = 0;
  10110. }
  10111. };
  10112. PerfCounter.Enabled = true;
  10113. return PerfCounter;
  10114. }());
  10115. BABYLON.PerfCounter = PerfCounter;
  10116. /**
  10117. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10118. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10119. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10120. * @param name The name of the class, case should be preserved
  10121. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10122. */
  10123. function className(name, module) {
  10124. return function (target) {
  10125. target["__bjsclassName__"] = name;
  10126. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10127. };
  10128. }
  10129. BABYLON.className = className;
  10130. /**
  10131. * An implementation of a loop for asynchronous functions.
  10132. */
  10133. var AsyncLoop = /** @class */ (function () {
  10134. /**
  10135. * Constroctor.
  10136. * @param iterations the number of iterations.
  10137. * @param _fn the function to run each iteration
  10138. * @param _successCallback the callback that will be called upon succesful execution
  10139. * @param offset starting offset.
  10140. */
  10141. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10142. if (offset === void 0) { offset = 0; }
  10143. this.iterations = iterations;
  10144. this._fn = _fn;
  10145. this._successCallback = _successCallback;
  10146. this.index = offset - 1;
  10147. this._done = false;
  10148. }
  10149. /**
  10150. * Execute the next iteration. Must be called after the last iteration was finished.
  10151. */
  10152. AsyncLoop.prototype.executeNext = function () {
  10153. if (!this._done) {
  10154. if (this.index + 1 < this.iterations) {
  10155. ++this.index;
  10156. this._fn(this);
  10157. }
  10158. else {
  10159. this.breakLoop();
  10160. }
  10161. }
  10162. };
  10163. /**
  10164. * Break the loop and run the success callback.
  10165. */
  10166. AsyncLoop.prototype.breakLoop = function () {
  10167. this._done = true;
  10168. this._successCallback();
  10169. };
  10170. /**
  10171. * Helper function
  10172. */
  10173. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10174. if (offset === void 0) { offset = 0; }
  10175. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10176. loop.executeNext();
  10177. return loop;
  10178. };
  10179. /**
  10180. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10181. * @param iterations total number of iterations
  10182. * @param syncedIterations number of synchronous iterations in each async iteration.
  10183. * @param fn the function to call each iteration.
  10184. * @param callback a success call back that will be called when iterating stops.
  10185. * @param breakFunction a break condition (optional)
  10186. * @param timeout timeout settings for the setTimeout function. default - 0.
  10187. * @constructor
  10188. */
  10189. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10190. if (timeout === void 0) { timeout = 0; }
  10191. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10192. if (breakFunction && breakFunction())
  10193. loop.breakLoop();
  10194. else {
  10195. setTimeout(function () {
  10196. for (var i = 0; i < syncedIterations; ++i) {
  10197. var iteration = (loop.index * syncedIterations) + i;
  10198. if (iteration >= iterations)
  10199. break;
  10200. fn(iteration);
  10201. if (breakFunction && breakFunction()) {
  10202. loop.breakLoop();
  10203. break;
  10204. }
  10205. }
  10206. loop.executeNext();
  10207. }, timeout);
  10208. }
  10209. }, callback);
  10210. };
  10211. return AsyncLoop;
  10212. }());
  10213. BABYLON.AsyncLoop = AsyncLoop;
  10214. })(BABYLON || (BABYLON = {}));
  10215. //# sourceMappingURL=babylon.tools.js.map
  10216. var BABYLON;
  10217. (function (BABYLON) {
  10218. var PromiseStates;
  10219. (function (PromiseStates) {
  10220. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10221. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10222. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10223. })(PromiseStates || (PromiseStates = {}));
  10224. var FulFillmentAgregator = /** @class */ (function () {
  10225. function FulFillmentAgregator() {
  10226. this.count = 0;
  10227. this.target = 0;
  10228. this.results = [];
  10229. }
  10230. return FulFillmentAgregator;
  10231. }());
  10232. var InternalPromise = /** @class */ (function () {
  10233. function InternalPromise(resolver) {
  10234. var _this = this;
  10235. this._state = PromiseStates.Pending;
  10236. this._children = new Array();
  10237. this._rejectWasConsumed = false;
  10238. if (!resolver) {
  10239. return;
  10240. }
  10241. try {
  10242. resolver(function (value) {
  10243. _this._resolve(value);
  10244. }, function (reason) {
  10245. _this._reject(reason);
  10246. });
  10247. }
  10248. catch (e) {
  10249. this._reject(e);
  10250. }
  10251. }
  10252. Object.defineProperty(InternalPromise.prototype, "_result", {
  10253. get: function () {
  10254. return this._resultValue;
  10255. },
  10256. set: function (value) {
  10257. this._resultValue = value;
  10258. if (this._parent && this._parent._result === undefined) {
  10259. this._parent._result = value;
  10260. }
  10261. },
  10262. enumerable: true,
  10263. configurable: true
  10264. });
  10265. InternalPromise.prototype.catch = function (onRejected) {
  10266. return this.then(undefined, onRejected);
  10267. };
  10268. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10269. var _this = this;
  10270. var newPromise = new InternalPromise();
  10271. newPromise._onFulfilled = onFulfilled;
  10272. newPromise._onRejected = onRejected;
  10273. // Composition
  10274. this._children.push(newPromise);
  10275. newPromise._parent = this;
  10276. if (this._state !== PromiseStates.Pending) {
  10277. BABYLON.Tools.SetImmediate(function () {
  10278. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10279. var returnedValue = newPromise._resolve(_this._result);
  10280. if (returnedValue !== undefined && returnedValue !== null) {
  10281. if (returnedValue._state !== undefined) {
  10282. var returnedPromise = returnedValue;
  10283. newPromise._children.push(returnedPromise);
  10284. returnedPromise._parent = newPromise;
  10285. newPromise = returnedPromise;
  10286. }
  10287. else {
  10288. newPromise._result = returnedValue;
  10289. }
  10290. }
  10291. }
  10292. else {
  10293. newPromise._reject(_this._reason);
  10294. }
  10295. });
  10296. }
  10297. return newPromise;
  10298. };
  10299. InternalPromise.prototype._moveChildren = function (children) {
  10300. var _this = this;
  10301. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10302. this._children.forEach(function (child) {
  10303. child._parent = _this;
  10304. });
  10305. if (this._state === PromiseStates.Fulfilled) {
  10306. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10307. var child = _b[_i];
  10308. child._resolve(this._result);
  10309. }
  10310. }
  10311. else if (this._state === PromiseStates.Rejected) {
  10312. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10313. var child = _d[_c];
  10314. child._reject(this._reason);
  10315. }
  10316. }
  10317. var _a;
  10318. };
  10319. InternalPromise.prototype._resolve = function (value) {
  10320. try {
  10321. this._state = PromiseStates.Fulfilled;
  10322. var returnedValue = null;
  10323. if (this._onFulfilled) {
  10324. returnedValue = this._onFulfilled(value);
  10325. }
  10326. if (returnedValue !== undefined && returnedValue !== null) {
  10327. if (returnedValue._state !== undefined) {
  10328. // Transmit children
  10329. var returnedPromise = returnedValue;
  10330. returnedPromise._parent = this;
  10331. returnedPromise._moveChildren(this._children);
  10332. value = returnedPromise._result;
  10333. }
  10334. else {
  10335. value = returnedValue;
  10336. }
  10337. }
  10338. this._result = value;
  10339. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10340. var child = _a[_i];
  10341. child._resolve(value);
  10342. }
  10343. this._children.length = 0;
  10344. delete this._onFulfilled;
  10345. delete this._onRejected;
  10346. }
  10347. catch (e) {
  10348. this._reject(e, true);
  10349. }
  10350. };
  10351. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10352. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10353. this._state = PromiseStates.Rejected;
  10354. this._reason = reason;
  10355. if (this._onRejected && !onLocalThrow) {
  10356. try {
  10357. this._onRejected(reason);
  10358. this._rejectWasConsumed = true;
  10359. }
  10360. catch (e) {
  10361. reason = e;
  10362. }
  10363. }
  10364. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10365. var child = _a[_i];
  10366. if (this._rejectWasConsumed) {
  10367. child._resolve(null);
  10368. }
  10369. else {
  10370. child._reject(reason);
  10371. }
  10372. }
  10373. this._children.length = 0;
  10374. delete this._onFulfilled;
  10375. delete this._onRejected;
  10376. };
  10377. InternalPromise.resolve = function (value) {
  10378. var newPromise = new InternalPromise();
  10379. newPromise._resolve(value);
  10380. return newPromise;
  10381. };
  10382. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10383. promise.then(function (value) {
  10384. agregator.results[index] = value;
  10385. agregator.count++;
  10386. if (agregator.count === agregator.target) {
  10387. agregator.rootPromise._resolve(agregator.results);
  10388. }
  10389. return null;
  10390. }, function (reason) {
  10391. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10392. agregator.rootPromise._reject(reason);
  10393. }
  10394. });
  10395. };
  10396. InternalPromise.all = function (promises) {
  10397. var newPromise = new InternalPromise();
  10398. var agregator = new FulFillmentAgregator();
  10399. agregator.target = promises.length;
  10400. agregator.rootPromise = newPromise;
  10401. if (promises.length) {
  10402. for (var index = 0; index < promises.length; index++) {
  10403. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10404. }
  10405. }
  10406. else {
  10407. newPromise._resolve([]);
  10408. }
  10409. return newPromise;
  10410. };
  10411. InternalPromise.race = function (promises) {
  10412. var newPromise = new InternalPromise();
  10413. if (promises.length) {
  10414. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10415. var promise = promises_1[_i];
  10416. promise.then(function (value) {
  10417. if (newPromise) {
  10418. newPromise._resolve(value);
  10419. newPromise = null;
  10420. }
  10421. return null;
  10422. }, function (reason) {
  10423. if (newPromise) {
  10424. newPromise._reject(reason);
  10425. newPromise = null;
  10426. }
  10427. });
  10428. }
  10429. }
  10430. return newPromise;
  10431. };
  10432. return InternalPromise;
  10433. }());
  10434. /**
  10435. * Helper class that provides a small promise polyfill
  10436. */
  10437. var PromisePolyfill = /** @class */ (function () {
  10438. function PromisePolyfill() {
  10439. }
  10440. /**
  10441. * Static function used to check if the polyfill is required
  10442. * If this is the case then the function will inject the polyfill to window.Promise
  10443. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10444. */
  10445. PromisePolyfill.Apply = function (force) {
  10446. if (force === void 0) { force = false; }
  10447. if (force || typeof Promise === 'undefined') {
  10448. var root = window;
  10449. root.Promise = InternalPromise;
  10450. }
  10451. };
  10452. return PromisePolyfill;
  10453. }());
  10454. BABYLON.PromisePolyfill = PromisePolyfill;
  10455. })(BABYLON || (BABYLON = {}));
  10456. //# sourceMappingURL=babylon.promise.js.map
  10457. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10458. var BABYLON;
  10459. (function (BABYLON) {
  10460. /**
  10461. * Helper class to push actions to a pool of workers.
  10462. */
  10463. var WorkerPool = /** @class */ (function () {
  10464. /**
  10465. * Constructor
  10466. * @param workers Array of workers to use for actions
  10467. */
  10468. function WorkerPool(workers) {
  10469. this._pendingActions = new Array();
  10470. this._workerInfos = workers.map(function (worker) { return ({
  10471. worker: worker,
  10472. active: false
  10473. }); });
  10474. }
  10475. /**
  10476. * Terminates all workers and clears any pending actions.
  10477. */
  10478. WorkerPool.prototype.dispose = function () {
  10479. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10480. var workerInfo = _a[_i];
  10481. workerInfo.worker.terminate();
  10482. }
  10483. delete this._workerInfos;
  10484. delete this._pendingActions;
  10485. };
  10486. /**
  10487. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10488. * pended until a worker has completed its action.
  10489. * @param action The action to perform. Call onComplete when the action is complete.
  10490. */
  10491. WorkerPool.prototype.push = function (action) {
  10492. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10493. var workerInfo = _a[_i];
  10494. if (!workerInfo.active) {
  10495. this._execute(workerInfo, action);
  10496. return;
  10497. }
  10498. }
  10499. this._pendingActions.push(action);
  10500. };
  10501. WorkerPool.prototype._execute = function (workerInfo, action) {
  10502. var _this = this;
  10503. workerInfo.active = true;
  10504. action(workerInfo.worker, function () {
  10505. workerInfo.active = false;
  10506. var nextAction = _this._pendingActions.shift();
  10507. if (nextAction) {
  10508. _this._execute(workerInfo, nextAction);
  10509. }
  10510. });
  10511. };
  10512. return WorkerPool;
  10513. }());
  10514. BABYLON.WorkerPool = WorkerPool;
  10515. })(BABYLON || (BABYLON = {}));
  10516. //# sourceMappingURL=babylon.workerPool.js.map
  10517. var BABYLON;
  10518. (function (BABYLON) {
  10519. /**
  10520. * @hidden
  10521. **/
  10522. var _AlphaState = /** @class */ (function () {
  10523. /**
  10524. * Initializes the state.
  10525. */
  10526. function _AlphaState() {
  10527. this._isAlphaBlendDirty = false;
  10528. this._isBlendFunctionParametersDirty = false;
  10529. this._isBlendEquationParametersDirty = false;
  10530. this._isBlendConstantsDirty = false;
  10531. this._alphaBlend = false;
  10532. this._blendFunctionParameters = new Array(4);
  10533. this._blendEquationParameters = new Array(2);
  10534. this._blendConstants = new Array(4);
  10535. this.reset();
  10536. }
  10537. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10538. get: function () {
  10539. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10540. },
  10541. enumerable: true,
  10542. configurable: true
  10543. });
  10544. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10545. get: function () {
  10546. return this._alphaBlend;
  10547. },
  10548. set: function (value) {
  10549. if (this._alphaBlend === value) {
  10550. return;
  10551. }
  10552. this._alphaBlend = value;
  10553. this._isAlphaBlendDirty = true;
  10554. },
  10555. enumerable: true,
  10556. configurable: true
  10557. });
  10558. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10559. if (this._blendConstants[0] === r &&
  10560. this._blendConstants[1] === g &&
  10561. this._blendConstants[2] === b &&
  10562. this._blendConstants[3] === a) {
  10563. return;
  10564. }
  10565. this._blendConstants[0] = r;
  10566. this._blendConstants[1] = g;
  10567. this._blendConstants[2] = b;
  10568. this._blendConstants[3] = a;
  10569. this._isBlendConstantsDirty = true;
  10570. };
  10571. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10572. if (this._blendFunctionParameters[0] === value0 &&
  10573. this._blendFunctionParameters[1] === value1 &&
  10574. this._blendFunctionParameters[2] === value2 &&
  10575. this._blendFunctionParameters[3] === value3) {
  10576. return;
  10577. }
  10578. this._blendFunctionParameters[0] = value0;
  10579. this._blendFunctionParameters[1] = value1;
  10580. this._blendFunctionParameters[2] = value2;
  10581. this._blendFunctionParameters[3] = value3;
  10582. this._isBlendFunctionParametersDirty = true;
  10583. };
  10584. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10585. if (this._blendEquationParameters[0] === rgb &&
  10586. this._blendEquationParameters[1] === alpha) {
  10587. return;
  10588. }
  10589. this._blendEquationParameters[0] = rgb;
  10590. this._blendEquationParameters[1] = alpha;
  10591. this._isBlendEquationParametersDirty = true;
  10592. };
  10593. _AlphaState.prototype.reset = function () {
  10594. this._alphaBlend = false;
  10595. this._blendFunctionParameters[0] = null;
  10596. this._blendFunctionParameters[1] = null;
  10597. this._blendFunctionParameters[2] = null;
  10598. this._blendFunctionParameters[3] = null;
  10599. this._blendEquationParameters[0] = null;
  10600. this._blendEquationParameters[1] = null;
  10601. this._blendConstants[0] = null;
  10602. this._blendConstants[1] = null;
  10603. this._blendConstants[2] = null;
  10604. this._blendConstants[3] = null;
  10605. this._isAlphaBlendDirty = true;
  10606. this._isBlendFunctionParametersDirty = false;
  10607. this._isBlendEquationParametersDirty = false;
  10608. this._isBlendConstantsDirty = false;
  10609. };
  10610. _AlphaState.prototype.apply = function (gl) {
  10611. if (!this.isDirty) {
  10612. return;
  10613. }
  10614. // Alpha blend
  10615. if (this._isAlphaBlendDirty) {
  10616. if (this._alphaBlend) {
  10617. gl.enable(gl.BLEND);
  10618. }
  10619. else {
  10620. gl.disable(gl.BLEND);
  10621. }
  10622. this._isAlphaBlendDirty = false;
  10623. }
  10624. // Alpha function
  10625. if (this._isBlendFunctionParametersDirty) {
  10626. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10627. this._isBlendFunctionParametersDirty = false;
  10628. }
  10629. // Alpha equation
  10630. if (this._isBlendEquationParametersDirty) {
  10631. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10632. this._isBlendEquationParametersDirty = false;
  10633. }
  10634. // Constants
  10635. if (this._isBlendConstantsDirty) {
  10636. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10637. this._isBlendConstantsDirty = false;
  10638. }
  10639. };
  10640. return _AlphaState;
  10641. }());
  10642. BABYLON._AlphaState = _AlphaState;
  10643. })(BABYLON || (BABYLON = {}));
  10644. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10645. var BABYLON;
  10646. (function (BABYLON) {
  10647. /**
  10648. * @hidden
  10649. **/
  10650. var _DepthCullingState = /** @class */ (function () {
  10651. /**
  10652. * Initializes the state.
  10653. */
  10654. function _DepthCullingState() {
  10655. this._isDepthTestDirty = false;
  10656. this._isDepthMaskDirty = false;
  10657. this._isDepthFuncDirty = false;
  10658. this._isCullFaceDirty = false;
  10659. this._isCullDirty = false;
  10660. this._isZOffsetDirty = false;
  10661. this._isFrontFaceDirty = false;
  10662. this.reset();
  10663. }
  10664. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10665. get: function () {
  10666. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10667. },
  10668. enumerable: true,
  10669. configurable: true
  10670. });
  10671. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10672. get: function () {
  10673. return this._zOffset;
  10674. },
  10675. set: function (value) {
  10676. if (this._zOffset === value) {
  10677. return;
  10678. }
  10679. this._zOffset = value;
  10680. this._isZOffsetDirty = true;
  10681. },
  10682. enumerable: true,
  10683. configurable: true
  10684. });
  10685. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10686. get: function () {
  10687. return this._cullFace;
  10688. },
  10689. set: function (value) {
  10690. if (this._cullFace === value) {
  10691. return;
  10692. }
  10693. this._cullFace = value;
  10694. this._isCullFaceDirty = true;
  10695. },
  10696. enumerable: true,
  10697. configurable: true
  10698. });
  10699. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10700. get: function () {
  10701. return this._cull;
  10702. },
  10703. set: function (value) {
  10704. if (this._cull === value) {
  10705. return;
  10706. }
  10707. this._cull = value;
  10708. this._isCullDirty = true;
  10709. },
  10710. enumerable: true,
  10711. configurable: true
  10712. });
  10713. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10714. get: function () {
  10715. return this._depthFunc;
  10716. },
  10717. set: function (value) {
  10718. if (this._depthFunc === value) {
  10719. return;
  10720. }
  10721. this._depthFunc = value;
  10722. this._isDepthFuncDirty = true;
  10723. },
  10724. enumerable: true,
  10725. configurable: true
  10726. });
  10727. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10728. get: function () {
  10729. return this._depthMask;
  10730. },
  10731. set: function (value) {
  10732. if (this._depthMask === value) {
  10733. return;
  10734. }
  10735. this._depthMask = value;
  10736. this._isDepthMaskDirty = true;
  10737. },
  10738. enumerable: true,
  10739. configurable: true
  10740. });
  10741. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10742. get: function () {
  10743. return this._depthTest;
  10744. },
  10745. set: function (value) {
  10746. if (this._depthTest === value) {
  10747. return;
  10748. }
  10749. this._depthTest = value;
  10750. this._isDepthTestDirty = true;
  10751. },
  10752. enumerable: true,
  10753. configurable: true
  10754. });
  10755. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10756. get: function () {
  10757. return this._frontFace;
  10758. },
  10759. set: function (value) {
  10760. if (this._frontFace === value) {
  10761. return;
  10762. }
  10763. this._frontFace = value;
  10764. this._isFrontFaceDirty = true;
  10765. },
  10766. enumerable: true,
  10767. configurable: true
  10768. });
  10769. _DepthCullingState.prototype.reset = function () {
  10770. this._depthMask = true;
  10771. this._depthTest = true;
  10772. this._depthFunc = null;
  10773. this._cullFace = null;
  10774. this._cull = null;
  10775. this._zOffset = 0;
  10776. this._frontFace = null;
  10777. this._isDepthTestDirty = true;
  10778. this._isDepthMaskDirty = true;
  10779. this._isDepthFuncDirty = false;
  10780. this._isCullFaceDirty = false;
  10781. this._isCullDirty = false;
  10782. this._isZOffsetDirty = false;
  10783. this._isFrontFaceDirty = false;
  10784. };
  10785. _DepthCullingState.prototype.apply = function (gl) {
  10786. if (!this.isDirty) {
  10787. return;
  10788. }
  10789. // Cull
  10790. if (this._isCullDirty) {
  10791. if (this.cull) {
  10792. gl.enable(gl.CULL_FACE);
  10793. }
  10794. else {
  10795. gl.disable(gl.CULL_FACE);
  10796. }
  10797. this._isCullDirty = false;
  10798. }
  10799. // Cull face
  10800. if (this._isCullFaceDirty) {
  10801. gl.cullFace(this.cullFace);
  10802. this._isCullFaceDirty = false;
  10803. }
  10804. // Depth mask
  10805. if (this._isDepthMaskDirty) {
  10806. gl.depthMask(this.depthMask);
  10807. this._isDepthMaskDirty = false;
  10808. }
  10809. // Depth test
  10810. if (this._isDepthTestDirty) {
  10811. if (this.depthTest) {
  10812. gl.enable(gl.DEPTH_TEST);
  10813. }
  10814. else {
  10815. gl.disable(gl.DEPTH_TEST);
  10816. }
  10817. this._isDepthTestDirty = false;
  10818. }
  10819. // Depth func
  10820. if (this._isDepthFuncDirty) {
  10821. gl.depthFunc(this.depthFunc);
  10822. this._isDepthFuncDirty = false;
  10823. }
  10824. // zOffset
  10825. if (this._isZOffsetDirty) {
  10826. if (this.zOffset) {
  10827. gl.enable(gl.POLYGON_OFFSET_FILL);
  10828. gl.polygonOffset(this.zOffset, 0);
  10829. }
  10830. else {
  10831. gl.disable(gl.POLYGON_OFFSET_FILL);
  10832. }
  10833. this._isZOffsetDirty = false;
  10834. }
  10835. // Front face
  10836. if (this._isFrontFaceDirty) {
  10837. gl.frontFace(this.frontFace);
  10838. this._isFrontFaceDirty = false;
  10839. }
  10840. };
  10841. return _DepthCullingState;
  10842. }());
  10843. BABYLON._DepthCullingState = _DepthCullingState;
  10844. })(BABYLON || (BABYLON = {}));
  10845. //# sourceMappingURL=babylon.depthCullingState.js.map
  10846. var BABYLON;
  10847. (function (BABYLON) {
  10848. /**
  10849. * @hidden
  10850. **/
  10851. var _StencilState = /** @class */ (function () {
  10852. function _StencilState() {
  10853. this._isStencilTestDirty = false;
  10854. this._isStencilMaskDirty = false;
  10855. this._isStencilFuncDirty = false;
  10856. this._isStencilOpDirty = false;
  10857. this.reset();
  10858. }
  10859. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10860. get: function () {
  10861. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10862. },
  10863. enumerable: true,
  10864. configurable: true
  10865. });
  10866. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10867. get: function () {
  10868. return this._stencilFunc;
  10869. },
  10870. set: function (value) {
  10871. if (this._stencilFunc === value) {
  10872. return;
  10873. }
  10874. this._stencilFunc = value;
  10875. this._isStencilFuncDirty = true;
  10876. },
  10877. enumerable: true,
  10878. configurable: true
  10879. });
  10880. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10881. get: function () {
  10882. return this._stencilFuncRef;
  10883. },
  10884. set: function (value) {
  10885. if (this._stencilFuncRef === value) {
  10886. return;
  10887. }
  10888. this._stencilFuncRef = value;
  10889. this._isStencilFuncDirty = true;
  10890. },
  10891. enumerable: true,
  10892. configurable: true
  10893. });
  10894. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10895. get: function () {
  10896. return this._stencilFuncMask;
  10897. },
  10898. set: function (value) {
  10899. if (this._stencilFuncMask === value) {
  10900. return;
  10901. }
  10902. this._stencilFuncMask = value;
  10903. this._isStencilFuncDirty = true;
  10904. },
  10905. enumerable: true,
  10906. configurable: true
  10907. });
  10908. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10909. get: function () {
  10910. return this._stencilOpStencilFail;
  10911. },
  10912. set: function (value) {
  10913. if (this._stencilOpStencilFail === value) {
  10914. return;
  10915. }
  10916. this._stencilOpStencilFail = value;
  10917. this._isStencilOpDirty = true;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10923. get: function () {
  10924. return this._stencilOpDepthFail;
  10925. },
  10926. set: function (value) {
  10927. if (this._stencilOpDepthFail === value) {
  10928. return;
  10929. }
  10930. this._stencilOpDepthFail = value;
  10931. this._isStencilOpDirty = true;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10937. get: function () {
  10938. return this._stencilOpStencilDepthPass;
  10939. },
  10940. set: function (value) {
  10941. if (this._stencilOpStencilDepthPass === value) {
  10942. return;
  10943. }
  10944. this._stencilOpStencilDepthPass = value;
  10945. this._isStencilOpDirty = true;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10951. get: function () {
  10952. return this._stencilMask;
  10953. },
  10954. set: function (value) {
  10955. if (this._stencilMask === value) {
  10956. return;
  10957. }
  10958. this._stencilMask = value;
  10959. this._isStencilMaskDirty = true;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10965. get: function () {
  10966. return this._stencilTest;
  10967. },
  10968. set: function (value) {
  10969. if (this._stencilTest === value) {
  10970. return;
  10971. }
  10972. this._stencilTest = value;
  10973. this._isStencilTestDirty = true;
  10974. },
  10975. enumerable: true,
  10976. configurable: true
  10977. });
  10978. _StencilState.prototype.reset = function () {
  10979. this._stencilTest = false;
  10980. this._stencilMask = 0xFF;
  10981. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10982. this._stencilFuncRef = 1;
  10983. this._stencilFuncMask = 0xFF;
  10984. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10985. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10986. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10987. this._isStencilTestDirty = true;
  10988. this._isStencilMaskDirty = true;
  10989. this._isStencilFuncDirty = true;
  10990. this._isStencilOpDirty = true;
  10991. };
  10992. _StencilState.prototype.apply = function (gl) {
  10993. if (!this.isDirty) {
  10994. return;
  10995. }
  10996. // Stencil test
  10997. if (this._isStencilTestDirty) {
  10998. if (this.stencilTest) {
  10999. gl.enable(gl.STENCIL_TEST);
  11000. }
  11001. else {
  11002. gl.disable(gl.STENCIL_TEST);
  11003. }
  11004. this._isStencilTestDirty = false;
  11005. }
  11006. // Stencil mask
  11007. if (this._isStencilMaskDirty) {
  11008. gl.stencilMask(this.stencilMask);
  11009. this._isStencilMaskDirty = false;
  11010. }
  11011. // Stencil func
  11012. if (this._isStencilFuncDirty) {
  11013. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11014. this._isStencilFuncDirty = false;
  11015. }
  11016. // Stencil op
  11017. if (this._isStencilOpDirty) {
  11018. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11019. this._isStencilOpDirty = false;
  11020. }
  11021. };
  11022. return _StencilState;
  11023. }());
  11024. BABYLON._StencilState = _StencilState;
  11025. })(BABYLON || (BABYLON = {}));
  11026. //# sourceMappingURL=babylon.stencilState.js.map
  11027. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11028. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11029. s = arguments[i];
  11030. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11031. t[p] = s[p];
  11032. }
  11033. return t;
  11034. };
  11035. var BABYLON;
  11036. (function (BABYLON) {
  11037. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11038. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11039. };
  11040. var compileRawShader = function (gl, source, type) {
  11041. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11042. gl.shaderSource(shader, source);
  11043. gl.compileShader(shader);
  11044. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11045. var log = gl.getShaderInfoLog(shader);
  11046. if (log) {
  11047. throw new Error(log);
  11048. }
  11049. }
  11050. if (!shader) {
  11051. throw new Error("Something went wrong while compile the shader.");
  11052. }
  11053. return shader;
  11054. };
  11055. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11056. var magFilter = gl.NEAREST;
  11057. var minFilter = gl.NEAREST;
  11058. switch (samplingMode) {
  11059. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11060. magFilter = gl.LINEAR;
  11061. if (generateMipMaps) {
  11062. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11063. }
  11064. else {
  11065. minFilter = gl.LINEAR;
  11066. }
  11067. break;
  11068. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11069. magFilter = gl.LINEAR;
  11070. if (generateMipMaps) {
  11071. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11072. }
  11073. else {
  11074. minFilter = gl.LINEAR;
  11075. }
  11076. break;
  11077. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11078. magFilter = gl.NEAREST;
  11079. if (generateMipMaps) {
  11080. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11081. }
  11082. else {
  11083. minFilter = gl.NEAREST;
  11084. }
  11085. break;
  11086. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11087. magFilter = gl.NEAREST;
  11088. if (generateMipMaps) {
  11089. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11090. }
  11091. else {
  11092. minFilter = gl.NEAREST;
  11093. }
  11094. break;
  11095. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11096. magFilter = gl.NEAREST;
  11097. if (generateMipMaps) {
  11098. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11099. }
  11100. else {
  11101. minFilter = gl.LINEAR;
  11102. }
  11103. break;
  11104. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11105. magFilter = gl.NEAREST;
  11106. if (generateMipMaps) {
  11107. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11108. }
  11109. else {
  11110. minFilter = gl.LINEAR;
  11111. }
  11112. break;
  11113. case BABYLON.Texture.NEAREST_LINEAR:
  11114. magFilter = gl.NEAREST;
  11115. minFilter = gl.LINEAR;
  11116. break;
  11117. case BABYLON.Texture.NEAREST_NEAREST:
  11118. magFilter = gl.NEAREST;
  11119. minFilter = gl.NEAREST;
  11120. break;
  11121. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11122. magFilter = gl.LINEAR;
  11123. if (generateMipMaps) {
  11124. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11125. }
  11126. else {
  11127. minFilter = gl.NEAREST;
  11128. }
  11129. break;
  11130. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11131. magFilter = gl.LINEAR;
  11132. if (generateMipMaps) {
  11133. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11134. }
  11135. else {
  11136. minFilter = gl.NEAREST;
  11137. }
  11138. break;
  11139. case BABYLON.Texture.LINEAR_LINEAR:
  11140. magFilter = gl.LINEAR;
  11141. minFilter = gl.LINEAR;
  11142. break;
  11143. case BABYLON.Texture.LINEAR_NEAREST:
  11144. magFilter = gl.LINEAR;
  11145. minFilter = gl.NEAREST;
  11146. break;
  11147. }
  11148. return {
  11149. min: minFilter,
  11150. mag: magFilter
  11151. };
  11152. };
  11153. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11154. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11155. var img;
  11156. var onload = function () {
  11157. loadedImages[index] = img;
  11158. loadedImages._internalCount++;
  11159. if (scene) {
  11160. scene._removePendingData(img);
  11161. }
  11162. if (loadedImages._internalCount === 6) {
  11163. onfinish(loadedImages);
  11164. }
  11165. };
  11166. var onerror = function (message, exception) {
  11167. if (scene) {
  11168. scene._removePendingData(img);
  11169. }
  11170. if (onErrorCallBack) {
  11171. onErrorCallBack(message, exception);
  11172. }
  11173. };
  11174. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11175. if (scene) {
  11176. scene._addPendingData(img);
  11177. }
  11178. };
  11179. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11180. if (onError === void 0) { onError = null; }
  11181. var loadedImages = [];
  11182. loadedImages._internalCount = 0;
  11183. for (var index = 0; index < 6; index++) {
  11184. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11185. }
  11186. };
  11187. var BufferPointer = /** @class */ (function () {
  11188. function BufferPointer() {
  11189. }
  11190. return BufferPointer;
  11191. }());
  11192. /**
  11193. * Interface for attribute information associated with buffer instanciation
  11194. */
  11195. var InstancingAttributeInfo = /** @class */ (function () {
  11196. function InstancingAttributeInfo() {
  11197. }
  11198. return InstancingAttributeInfo;
  11199. }());
  11200. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11201. /**
  11202. * Define options used to create a render target texture
  11203. */
  11204. var RenderTargetCreationOptions = /** @class */ (function () {
  11205. function RenderTargetCreationOptions() {
  11206. }
  11207. return RenderTargetCreationOptions;
  11208. }());
  11209. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11210. /**
  11211. * Define options used to create a depth texture
  11212. */
  11213. var DepthTextureCreationOptions = /** @class */ (function () {
  11214. function DepthTextureCreationOptions() {
  11215. }
  11216. return DepthTextureCreationOptions;
  11217. }());
  11218. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11219. /**
  11220. * Class used to describe the capabilities of the engine relatively to the current browser
  11221. */
  11222. var EngineCapabilities = /** @class */ (function () {
  11223. function EngineCapabilities() {
  11224. }
  11225. return EngineCapabilities;
  11226. }());
  11227. BABYLON.EngineCapabilities = EngineCapabilities;
  11228. /**
  11229. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11230. */
  11231. var Engine = /** @class */ (function () {
  11232. /**
  11233. * Creates a new engine
  11234. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11235. * @param antialias defines enable antialiasing (default: false)
  11236. * @param options defines further options to be sent to the getContext() function
  11237. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11238. */
  11239. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11240. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11241. var _this = this;
  11242. // Public members
  11243. /**
  11244. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11245. */
  11246. this.forcePOTTextures = false;
  11247. /**
  11248. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11249. */
  11250. this.isFullscreen = false;
  11251. /**
  11252. * Gets a boolean indicating if the pointer is currently locked
  11253. */
  11254. this.isPointerLock = false;
  11255. /**
  11256. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11257. */
  11258. this.cullBackFaces = true;
  11259. /**
  11260. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11261. */
  11262. this.renderEvenInBackground = true;
  11263. /**
  11264. * Gets or sets a boolean indicating that cache can be kept between frames
  11265. */
  11266. this.preventCacheWipeBetweenFrames = false;
  11267. /**
  11268. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11269. **/
  11270. this.enableOfflineSupport = false;
  11271. /**
  11272. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11273. **/
  11274. this.disableManifestCheck = false;
  11275. /**
  11276. * Gets the list of created scenes
  11277. */
  11278. this.scenes = new Array();
  11279. /**
  11280. * Gets the list of created postprocesses
  11281. */
  11282. this.postProcesses = new Array();
  11283. // Observables
  11284. /**
  11285. * Observable event triggered each time the rendering canvas is resized
  11286. */
  11287. this.onResizeObservable = new BABYLON.Observable();
  11288. /**
  11289. * Observable event triggered each time the canvas loses focus
  11290. */
  11291. this.onCanvasBlurObservable = new BABYLON.Observable();
  11292. /**
  11293. * Observable event triggered each time the canvas gains focus
  11294. */
  11295. this.onCanvasFocusObservable = new BABYLON.Observable();
  11296. /**
  11297. * Observable event triggered each time the canvas receives pointerout event
  11298. */
  11299. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11300. /**
  11301. * Observable event triggered before each texture is initialized
  11302. */
  11303. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11304. //WebVR
  11305. this._vrDisplay = undefined;
  11306. this._vrSupported = false;
  11307. this._vrExclusivePointerMode = false;
  11308. // Uniform buffers list
  11309. /**
  11310. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11311. */
  11312. this.disableUniformBuffers = false;
  11313. /** @hidden */
  11314. this._uniformBuffers = new Array();
  11315. // Observables
  11316. /**
  11317. * Observable raised when the engine begins a new frame
  11318. */
  11319. this.onBeginFrameObservable = new BABYLON.Observable();
  11320. /**
  11321. * Observable raised when the engine ends the current frame
  11322. */
  11323. this.onEndFrameObservable = new BABYLON.Observable();
  11324. /**
  11325. * Observable raised when the engine is about to compile a shader
  11326. */
  11327. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11328. /**
  11329. * Observable raised when the engine has jsut compiled a shader
  11330. */
  11331. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11332. this._windowIsBackground = false;
  11333. this._webGLVersion = 1.0;
  11334. /** @hidden */
  11335. this._badOS = false;
  11336. /** @hidden */
  11337. this._badDesktopOS = false;
  11338. /**
  11339. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11340. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11341. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11342. */
  11343. this.disableTextureBindingOptimization = false;
  11344. /**
  11345. * Observable signaled when VR display mode changes
  11346. */
  11347. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11348. /**
  11349. * Observable signaled when VR request present is complete
  11350. */
  11351. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11352. /**
  11353. * Observable signaled when VR request present starts
  11354. */
  11355. this.onVRRequestPresentStart = new BABYLON.Observable();
  11356. this._colorWrite = true;
  11357. /** @hidden */
  11358. this._drawCalls = new BABYLON.PerfCounter();
  11359. /** @hidden */
  11360. this._textureCollisions = new BABYLON.PerfCounter();
  11361. this._renderingQueueLaunched = false;
  11362. this._activeRenderLoops = new Array();
  11363. // Deterministic lockstepMaxSteps
  11364. this._deterministicLockstep = false;
  11365. this._lockstepMaxSteps = 4;
  11366. // Lost context
  11367. /**
  11368. * Observable signaled when a context lost event is raised
  11369. */
  11370. this.onContextLostObservable = new BABYLON.Observable();
  11371. /**
  11372. * Observable signaled when a context restored event is raised
  11373. */
  11374. this.onContextRestoredObservable = new BABYLON.Observable();
  11375. this._contextWasLost = false;
  11376. this._doNotHandleContextLost = false;
  11377. // FPS
  11378. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11379. this._fps = 60;
  11380. this._deltaTime = 0;
  11381. /**
  11382. * Turn this value on if you want to pause FPS computation when in background
  11383. */
  11384. this.disablePerformanceMonitorInBackground = false;
  11385. // States
  11386. /** @hidden */
  11387. this._depthCullingState = new BABYLON._DepthCullingState();
  11388. /** @hidden */
  11389. this._stencilState = new BABYLON._StencilState();
  11390. /** @hidden */
  11391. this._alphaState = new BABYLON._AlphaState();
  11392. /** @hidden */
  11393. this._alphaMode = Engine.ALPHA_DISABLE;
  11394. // Cache
  11395. this._internalTexturesCache = new Array();
  11396. /** @hidden */
  11397. this._activeChannel = 0;
  11398. this._currentTextureChannel = -1;
  11399. /** @hidden */
  11400. this._boundTexturesCache = {};
  11401. this._compiledEffects = {};
  11402. this._vertexAttribArraysEnabled = [];
  11403. this._uintIndicesCurrentlySet = false;
  11404. this._currentBoundBuffer = new Array();
  11405. this._currentBufferPointers = new Array();
  11406. this._currentInstanceLocations = new Array();
  11407. this._currentInstanceBuffers = new Array();
  11408. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11409. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11410. this._vaoRecordInProgress = false;
  11411. this._mustWipeVertexAttributes = false;
  11412. this._nextFreeTextureSlots = new Array();
  11413. this._maxSimultaneousTextures = 0;
  11414. this._activeRequests = new Array();
  11415. // Hardware supported Compressed Textures
  11416. this._texturesSupported = new Array();
  11417. this._onVRFullScreenTriggered = function () {
  11418. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11419. //get the old size before we change
  11420. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11421. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11422. //get the width and height, change the render size
  11423. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11424. _this.setHardwareScalingLevel(1);
  11425. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11426. }
  11427. else {
  11428. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11429. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11430. }
  11431. };
  11432. this._boundUniforms = {};
  11433. // Register promises
  11434. BABYLON.PromisePolyfill.Apply();
  11435. var canvas = null;
  11436. Engine.Instances.push(this);
  11437. if (!canvasOrContext) {
  11438. return;
  11439. }
  11440. options = options || {};
  11441. if (canvasOrContext.getContext) {
  11442. canvas = canvasOrContext;
  11443. this._renderingCanvas = canvas;
  11444. if (antialias != null) {
  11445. options.antialias = antialias;
  11446. }
  11447. if (options.deterministicLockstep === undefined) {
  11448. options.deterministicLockstep = false;
  11449. }
  11450. if (options.lockstepMaxSteps === undefined) {
  11451. options.lockstepMaxSteps = 4;
  11452. }
  11453. if (options.preserveDrawingBuffer === undefined) {
  11454. options.preserveDrawingBuffer = false;
  11455. }
  11456. if (options.audioEngine === undefined) {
  11457. options.audioEngine = true;
  11458. }
  11459. if (options.stencil === undefined) {
  11460. options.stencil = true;
  11461. }
  11462. this._deterministicLockstep = options.deterministicLockstep;
  11463. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11464. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11465. // Exceptions
  11466. if (navigator && navigator.userAgent) {
  11467. var ua = navigator.userAgent;
  11468. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11469. var exception = _a[_i];
  11470. var key = exception.key;
  11471. var targets = exception.targets;
  11472. if (ua.indexOf(key) > -1) {
  11473. if (exception.capture && exception.captureConstraint) {
  11474. var capture = exception.capture;
  11475. var constraint = exception.captureConstraint;
  11476. var regex = new RegExp(capture);
  11477. var matches = regex.exec(ua);
  11478. if (matches && matches.length > 0) {
  11479. var capturedValue = parseInt(matches[matches.length - 1]);
  11480. if (capturedValue >= constraint) {
  11481. continue;
  11482. }
  11483. }
  11484. }
  11485. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11486. var target = targets_1[_b];
  11487. switch (target) {
  11488. case "uniformBuffer":
  11489. this.disableUniformBuffers = true;
  11490. break;
  11491. case "textureBindingOptimization":
  11492. this.disableTextureBindingOptimization = true;
  11493. break;
  11494. }
  11495. }
  11496. }
  11497. }
  11498. }
  11499. // GL
  11500. if (!options.disableWebGL2Support) {
  11501. try {
  11502. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11503. if (this._gl) {
  11504. this._webGLVersion = 2.0;
  11505. }
  11506. }
  11507. catch (e) {
  11508. // Do nothing
  11509. }
  11510. }
  11511. if (!this._gl) {
  11512. if (!canvas) {
  11513. throw new Error("The provided canvas is null or undefined.");
  11514. }
  11515. try {
  11516. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11517. }
  11518. catch (e) {
  11519. throw new Error("WebGL not supported");
  11520. }
  11521. }
  11522. if (!this._gl) {
  11523. throw new Error("WebGL not supported");
  11524. }
  11525. this._onCanvasFocus = function () {
  11526. _this.onCanvasFocusObservable.notifyObservers(_this);
  11527. };
  11528. this._onCanvasBlur = function () {
  11529. _this.onCanvasBlurObservable.notifyObservers(_this);
  11530. };
  11531. canvas.addEventListener("focus", this._onCanvasFocus);
  11532. canvas.addEventListener("blur", this._onCanvasBlur);
  11533. this._onBlur = function () {
  11534. if (_this.disablePerformanceMonitorInBackground) {
  11535. _this._performanceMonitor.disable();
  11536. }
  11537. _this._windowIsBackground = true;
  11538. };
  11539. this._onFocus = function () {
  11540. if (_this.disablePerformanceMonitorInBackground) {
  11541. _this._performanceMonitor.enable();
  11542. }
  11543. _this._windowIsBackground = false;
  11544. };
  11545. this._onCanvasPointerOut = function (ev) {
  11546. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11547. };
  11548. window.addEventListener("blur", this._onBlur);
  11549. window.addEventListener("focus", this._onFocus);
  11550. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11551. // Context lost
  11552. if (!this._doNotHandleContextLost) {
  11553. this._onContextLost = function (evt) {
  11554. evt.preventDefault();
  11555. _this._contextWasLost = true;
  11556. BABYLON.Tools.Warn("WebGL context lost.");
  11557. _this.onContextLostObservable.notifyObservers(_this);
  11558. };
  11559. this._onContextRestored = function (evt) {
  11560. // Adding a timeout to avoid race condition at browser level
  11561. setTimeout(function () {
  11562. // Rebuild gl context
  11563. _this._initGLContext();
  11564. // Rebuild effects
  11565. _this._rebuildEffects();
  11566. // Rebuild textures
  11567. _this._rebuildInternalTextures();
  11568. // Rebuild buffers
  11569. _this._rebuildBuffers();
  11570. // Cache
  11571. _this.wipeCaches(true);
  11572. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11573. _this.onContextRestoredObservable.notifyObservers(_this);
  11574. _this._contextWasLost = false;
  11575. }, 0);
  11576. };
  11577. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11578. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11579. }
  11580. }
  11581. else {
  11582. this._gl = canvasOrContext;
  11583. this._renderingCanvas = this._gl.canvas;
  11584. if (this._gl.renderbufferStorageMultisample) {
  11585. this._webGLVersion = 2.0;
  11586. }
  11587. options.stencil = this._gl.getContextAttributes().stencil;
  11588. }
  11589. // Viewport
  11590. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11591. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11592. this.resize();
  11593. this._isStencilEnable = options.stencil ? true : false;
  11594. this._initGLContext();
  11595. if (canvas) {
  11596. // Fullscreen
  11597. this._onFullscreenChange = function () {
  11598. if (document.fullscreen !== undefined) {
  11599. _this.isFullscreen = document.fullscreen;
  11600. }
  11601. else if (document.mozFullScreen !== undefined) {
  11602. _this.isFullscreen = document.mozFullScreen;
  11603. }
  11604. else if (document.webkitIsFullScreen !== undefined) {
  11605. _this.isFullscreen = document.webkitIsFullScreen;
  11606. }
  11607. else if (document.msIsFullScreen !== undefined) {
  11608. _this.isFullscreen = document.msIsFullScreen;
  11609. }
  11610. // Pointer lock
  11611. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11612. canvas.requestPointerLock = canvas.requestPointerLock ||
  11613. canvas.msRequestPointerLock ||
  11614. canvas.mozRequestPointerLock ||
  11615. canvas.webkitRequestPointerLock;
  11616. if (canvas.requestPointerLock) {
  11617. canvas.requestPointerLock();
  11618. }
  11619. }
  11620. };
  11621. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11622. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11623. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11624. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11625. // Pointer lock
  11626. this._onPointerLockChange = function () {
  11627. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11628. document.webkitPointerLockElement === canvas ||
  11629. document.msPointerLockElement === canvas ||
  11630. document.pointerLockElement === canvas);
  11631. };
  11632. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11633. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11634. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11635. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11636. this._onVRDisplayPointerRestricted = function () {
  11637. if (canvas) {
  11638. canvas.requestPointerLock();
  11639. }
  11640. };
  11641. this._onVRDisplayPointerUnrestricted = function () {
  11642. document.exitPointerLock();
  11643. };
  11644. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11645. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11646. }
  11647. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11648. Engine.audioEngine = new BABYLON.AudioEngine();
  11649. }
  11650. // Prepare buffer pointers
  11651. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11652. this._currentBufferPointers[i] = new BufferPointer();
  11653. }
  11654. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11655. // Load WebVR Devices
  11656. if (options.autoEnableWebVR) {
  11657. this.initWebVR();
  11658. }
  11659. // Detect if we are running on a faulty buggy OS.
  11660. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11661. // Detect if we are running on a faulty buggy desktop OS.
  11662. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11663. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11664. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11665. }
  11666. Object.defineProperty(Engine, "LastCreatedEngine", {
  11667. /**
  11668. * Gets the latest created engine
  11669. */
  11670. get: function () {
  11671. if (Engine.Instances.length === 0) {
  11672. return null;
  11673. }
  11674. return Engine.Instances[Engine.Instances.length - 1];
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine, "LastCreatedScene", {
  11680. /**
  11681. * Gets the latest created scene
  11682. */
  11683. get: function () {
  11684. var lastCreatedEngine = Engine.LastCreatedEngine;
  11685. if (!lastCreatedEngine) {
  11686. return null;
  11687. }
  11688. if (lastCreatedEngine.scenes.length === 0) {
  11689. return null;
  11690. }
  11691. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. /**
  11697. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11698. * @param flag defines which part of the materials must be marked as dirty
  11699. * @param predicate defines a predicate used to filter which materials should be affected
  11700. */
  11701. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11702. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11703. var engine = Engine.Instances[engineIndex];
  11704. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11705. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11706. }
  11707. }
  11708. };
  11709. Object.defineProperty(Engine, "NEVER", {
  11710. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11711. get: function () {
  11712. return Engine._NEVER;
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. Object.defineProperty(Engine, "ALWAYS", {
  11718. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  11719. get: function () {
  11720. return Engine._ALWAYS;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine, "LESS", {
  11726. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11727. get: function () {
  11728. return Engine._LESS;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine, "EQUAL", {
  11734. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11735. get: function () {
  11736. return Engine._EQUAL;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Engine, "LEQUAL", {
  11742. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  11743. get: function () {
  11744. return Engine._LEQUAL;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Engine, "GREATER", {
  11750. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11751. get: function () {
  11752. return Engine._GREATER;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Engine, "GEQUAL", {
  11758. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  11759. get: function () {
  11760. return Engine._GEQUAL;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine, "NOTEQUAL", {
  11766. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  11767. get: function () {
  11768. return Engine._NOTEQUAL;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine, "KEEP", {
  11774. /** Passed to stencilOperation to specify that stencil value must be kept */
  11775. get: function () {
  11776. return Engine._KEEP;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "REPLACE", {
  11782. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11783. get: function () {
  11784. return Engine._REPLACE;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine, "INCR", {
  11790. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11791. get: function () {
  11792. return Engine._INCR;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "DECR", {
  11798. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11799. get: function () {
  11800. return Engine._DECR;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "INVERT", {
  11806. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11807. get: function () {
  11808. return Engine._INVERT;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "INCR_WRAP", {
  11814. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11815. get: function () {
  11816. return Engine._INCR_WRAP;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "DECR_WRAP", {
  11822. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11823. get: function () {
  11824. return Engine._DECR_WRAP;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11830. // Alpha
  11831. /** Defines that alpha blending is disabled */
  11832. get: function () {
  11833. return Engine._ALPHA_DISABLE;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11839. /** Defines that alpha blending to SRC + DEST */
  11840. get: function () {
  11841. return Engine._ALPHA_ONEONE;
  11842. },
  11843. enumerable: true,
  11844. configurable: true
  11845. });
  11846. Object.defineProperty(Engine, "ALPHA_ADD", {
  11847. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11848. get: function () {
  11849. return Engine._ALPHA_ADD;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11855. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11856. get: function () {
  11857. return Engine._ALPHA_COMBINE;
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11863. /** Defines that alpha blending to DEST - SRC * DEST */
  11864. get: function () {
  11865. return Engine._ALPHA_SUBTRACT;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11871. /** Defines that alpha blending to SRC * DEST */
  11872. get: function () {
  11873. return Engine._ALPHA_MULTIPLY;
  11874. },
  11875. enumerable: true,
  11876. configurable: true
  11877. });
  11878. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11879. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11880. get: function () {
  11881. return Engine._ALPHA_MAXIMIZED;
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11887. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11888. get: function () {
  11889. return Engine._ALPHA_PREMULTIPLIED;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11895. /**
  11896. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11897. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11898. */
  11899. get: function () {
  11900. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11906. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11907. get: function () {
  11908. return Engine._ALPHA_INTERPOLATE;
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11914. /**
  11915. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11916. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11917. */
  11918. get: function () {
  11919. return Engine._ALPHA_SCREENMODE;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11925. // Delays
  11926. /** Defines that the ressource is not delayed*/
  11927. get: function () {
  11928. return Engine._DELAYLOADSTATE_NONE;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11934. /** Defines that the ressource was successfully delay loaded */
  11935. get: function () {
  11936. return Engine._DELAYLOADSTATE_LOADED;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11942. /** Defines that the ressource is currently delay loading */
  11943. get: function () {
  11944. return Engine._DELAYLOADSTATE_LOADING;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11950. /** Defines that the ressource is delayed and has not started loading */
  11951. get: function () {
  11952. return Engine._DELAYLOADSTATE_NOTLOADED;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11958. /** ALPHA */
  11959. get: function () {
  11960. return Engine._TEXTUREFORMAT_ALPHA;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11966. /** LUMINANCE */
  11967. get: function () {
  11968. return Engine._TEXTUREFORMAT_LUMINANCE;
  11969. },
  11970. enumerable: true,
  11971. configurable: true
  11972. });
  11973. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11974. /**
  11975. * R32F
  11976. */
  11977. get: function () {
  11978. return Engine._TEXTUREFORMAT_R32F;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11984. /**
  11985. * RG32F
  11986. */
  11987. get: function () {
  11988. return Engine._TEXTUREFORMAT_RG32F;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11994. /**
  11995. * RGB32F
  11996. */
  11997. get: function () {
  11998. return Engine._TEXTUREFORMAT_RGB32F;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  12004. /**
  12005. * RGBA32F
  12006. */
  12007. get: function () {
  12008. return Engine._TEXTUREFORMAT_RGBA32F;
  12009. },
  12010. enumerable: true,
  12011. configurable: true
  12012. });
  12013. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12014. /** LUMINANCE_ALPHA */
  12015. get: function () {
  12016. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12022. /** RGB */
  12023. get: function () {
  12024. return Engine._TEXTUREFORMAT_RGB;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12030. /** RGBA */
  12031. get: function () {
  12032. return Engine._TEXTUREFORMAT_RGBA;
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12038. /** UNSIGNED_INT */
  12039. get: function () {
  12040. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12046. /** FLOAT */
  12047. get: function () {
  12048. return Engine._TEXTURETYPE_FLOAT;
  12049. },
  12050. enumerable: true,
  12051. configurable: true
  12052. });
  12053. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12054. /** HALF_FLOAT */
  12055. get: function () {
  12056. return Engine._TEXTURETYPE_HALF_FLOAT;
  12057. },
  12058. enumerable: true,
  12059. configurable: true
  12060. });
  12061. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12062. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12063. get: function () {
  12064. return Engine._SCALEMODE_FLOOR;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12070. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12071. get: function () {
  12072. return Engine._SCALEMODE_NEAREST;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12078. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12079. get: function () {
  12080. return Engine._SCALEMODE_CEILING;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Engine, "Version", {
  12086. /**
  12087. * Returns the current version of the framework
  12088. */
  12089. get: function () {
  12090. return "3.3.0-alpha.0";
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12096. /**
  12097. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12098. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12099. */
  12100. get: function () {
  12101. return this._vrExclusivePointerMode;
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12107. /**
  12108. * Gets a boolean indicating that the engine supports uniform buffers
  12109. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12110. */
  12111. get: function () {
  12112. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12118. /**
  12119. * Gets a boolean indicating that only power of 2 textures are supported
  12120. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12121. */
  12122. get: function () {
  12123. return this._webGLVersion < 2 || this.forcePOTTextures;
  12124. },
  12125. enumerable: true,
  12126. configurable: true
  12127. });
  12128. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12129. /**
  12130. * Gets the performance monitor attached to this engine
  12131. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12132. */
  12133. get: function () {
  12134. return this._performanceMonitor;
  12135. },
  12136. enumerable: true,
  12137. configurable: true
  12138. });
  12139. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12140. /**
  12141. * Gets the list of texture formats supported
  12142. */
  12143. get: function () {
  12144. return this._texturesSupported;
  12145. },
  12146. enumerable: true,
  12147. configurable: true
  12148. });
  12149. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12150. /**
  12151. * Gets the list of texture formats in use
  12152. */
  12153. get: function () {
  12154. return this._textureFormatInUse;
  12155. },
  12156. enumerable: true,
  12157. configurable: true
  12158. });
  12159. Object.defineProperty(Engine.prototype, "currentViewport", {
  12160. /**
  12161. * Gets the current viewport
  12162. */
  12163. get: function () {
  12164. return this._cachedViewport;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12170. /**
  12171. * Gets the default empty texture
  12172. */
  12173. get: function () {
  12174. if (!this._emptyTexture) {
  12175. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12176. }
  12177. return this._emptyTexture;
  12178. },
  12179. enumerable: true,
  12180. configurable: true
  12181. });
  12182. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12183. /**
  12184. * Gets the default empty 3D texture
  12185. */
  12186. get: function () {
  12187. if (!this._emptyTexture3D) {
  12188. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12189. }
  12190. return this._emptyTexture3D;
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12196. /**
  12197. * Gets the default empty cube texture
  12198. */
  12199. get: function () {
  12200. if (!this._emptyCubeTexture) {
  12201. var faceData = new Uint8Array(4);
  12202. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12203. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12204. }
  12205. return this._emptyCubeTexture;
  12206. },
  12207. enumerable: true,
  12208. configurable: true
  12209. });
  12210. Engine.prototype._rebuildInternalTextures = function () {
  12211. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12212. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12213. var internalTexture = currentState_1[_i];
  12214. internalTexture._rebuild();
  12215. }
  12216. };
  12217. Engine.prototype._rebuildEffects = function () {
  12218. for (var key in this._compiledEffects) {
  12219. var effect = this._compiledEffects[key];
  12220. effect._prepareEffect();
  12221. }
  12222. BABYLON.Effect.ResetCache();
  12223. };
  12224. Engine.prototype._rebuildBuffers = function () {
  12225. // Index / Vertex
  12226. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12227. var scene = _a[_i];
  12228. scene.resetCachedMaterial();
  12229. scene._rebuildGeometries();
  12230. scene._rebuildTextures();
  12231. }
  12232. // Uniforms
  12233. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12234. var uniformBuffer = _c[_b];
  12235. uniformBuffer._rebuild();
  12236. }
  12237. };
  12238. Engine.prototype._initGLContext = function () {
  12239. // Caps
  12240. this._caps = new EngineCapabilities();
  12241. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12242. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12243. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12244. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12245. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12246. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12247. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12248. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12249. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12250. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12251. // Infos
  12252. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12253. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12254. if (rendererInfo != null) {
  12255. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12256. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12257. }
  12258. if (!this._glVendor) {
  12259. this._glVendor = "Unknown vendor";
  12260. }
  12261. if (!this._glRenderer) {
  12262. this._glRenderer = "Unknown renderer";
  12263. }
  12264. // Constants
  12265. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12266. if (this._gl.RGBA16F !== 0x881A) {
  12267. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12268. }
  12269. if (this._gl.RGBA32F !== 0x8814) {
  12270. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12271. }
  12272. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12273. this._gl.DEPTH24_STENCIL8 = 35056;
  12274. }
  12275. // Extensions
  12276. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12277. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12278. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12279. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12280. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12281. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12282. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12283. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  12284. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12285. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12286. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12287. this._caps.highPrecisionShaderSupported = true;
  12288. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12289. if (this._caps.timerQuery) {
  12290. if (this._webGLVersion === 1) {
  12291. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12292. }
  12293. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12294. }
  12295. // Checks if some of the format renders first to allow the use of webgl inspector.
  12296. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12297. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12298. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12299. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12300. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12301. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12302. if (this._webGLVersion > 1) {
  12303. this._gl.HALF_FLOAT_OES = 0x140B;
  12304. }
  12305. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12306. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12307. // Draw buffers
  12308. if (this._webGLVersion > 1) {
  12309. this._caps.drawBuffersExtension = true;
  12310. }
  12311. else {
  12312. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12313. if (drawBuffersExtension !== null) {
  12314. this._caps.drawBuffersExtension = true;
  12315. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12316. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12317. for (var i = 0; i < 16; i++) {
  12318. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12319. }
  12320. }
  12321. else {
  12322. this._caps.drawBuffersExtension = false;
  12323. }
  12324. }
  12325. // Depth Texture
  12326. if (this._webGLVersion > 1) {
  12327. this._caps.depthTextureExtension = true;
  12328. }
  12329. else {
  12330. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12331. if (depthTextureExtension != null) {
  12332. this._caps.depthTextureExtension = true;
  12333. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12334. }
  12335. }
  12336. // Vertex array object
  12337. if (this._webGLVersion > 1) {
  12338. this._caps.vertexArrayObject = true;
  12339. }
  12340. else {
  12341. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12342. if (vertexArrayObjectExtension != null) {
  12343. this._caps.vertexArrayObject = true;
  12344. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12345. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12346. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12347. }
  12348. else {
  12349. this._caps.vertexArrayObject = false;
  12350. }
  12351. }
  12352. // Instances count
  12353. if (this._webGLVersion > 1) {
  12354. this._caps.instancedArrays = true;
  12355. }
  12356. else {
  12357. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12358. if (instanceExtension != null) {
  12359. this._caps.instancedArrays = true;
  12360. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12361. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12362. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12363. }
  12364. else {
  12365. this._caps.instancedArrays = false;
  12366. }
  12367. }
  12368. // Intelligently add supported compressed formats in order to check for.
  12369. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12370. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12371. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12372. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12373. if (this._caps.astc)
  12374. this.texturesSupported.push('-astc.ktx');
  12375. if (this._caps.s3tc)
  12376. this.texturesSupported.push('-dxt.ktx');
  12377. if (this._caps.pvrtc)
  12378. this.texturesSupported.push('-pvrtc.ktx');
  12379. if (this._caps.etc2)
  12380. this.texturesSupported.push('-etc2.ktx');
  12381. if (this._caps.etc1)
  12382. this.texturesSupported.push('-etc1.ktx');
  12383. if (this._gl.getShaderPrecisionFormat) {
  12384. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12385. if (highp) {
  12386. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12387. }
  12388. }
  12389. // Depth buffer
  12390. this.setDepthBuffer(true);
  12391. this.setDepthFunctionToLessOrEqual();
  12392. this.setDepthWrite(true);
  12393. // Texture maps
  12394. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12395. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12396. this._nextFreeTextureSlots.push(slot);
  12397. }
  12398. };
  12399. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12400. /**
  12401. * Gets version of the current webGL context
  12402. */
  12403. get: function () {
  12404. return this._webGLVersion;
  12405. },
  12406. enumerable: true,
  12407. configurable: true
  12408. });
  12409. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12410. /**
  12411. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12412. */
  12413. get: function () {
  12414. return this._isStencilEnable;
  12415. },
  12416. enumerable: true,
  12417. configurable: true
  12418. });
  12419. Engine.prototype._prepareWorkingCanvas = function () {
  12420. if (this._workingCanvas) {
  12421. return;
  12422. }
  12423. this._workingCanvas = document.createElement("canvas");
  12424. var context = this._workingCanvas.getContext("2d");
  12425. if (context) {
  12426. this._workingContext = context;
  12427. }
  12428. };
  12429. /**
  12430. * Reset the texture cache to empty state
  12431. */
  12432. Engine.prototype.resetTextureCache = function () {
  12433. for (var key in this._boundTexturesCache) {
  12434. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12435. continue;
  12436. }
  12437. var boundTexture = this._boundTexturesCache[key];
  12438. if (boundTexture) {
  12439. this._removeDesignatedSlot(boundTexture);
  12440. }
  12441. this._boundTexturesCache[key] = null;
  12442. }
  12443. if (!this.disableTextureBindingOptimization) {
  12444. this._nextFreeTextureSlots = [];
  12445. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12446. this._nextFreeTextureSlots.push(slot);
  12447. }
  12448. }
  12449. this._currentTextureChannel = -1;
  12450. };
  12451. /**
  12452. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12453. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12454. * @returns true if engine is in deterministic lock step mode
  12455. */
  12456. Engine.prototype.isDeterministicLockStep = function () {
  12457. return this._deterministicLockstep;
  12458. };
  12459. /**
  12460. * Gets the max steps when engine is running in deterministic lock step
  12461. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12462. * @returns the max steps
  12463. */
  12464. Engine.prototype.getLockstepMaxSteps = function () {
  12465. return this._lockstepMaxSteps;
  12466. };
  12467. /**
  12468. * Gets an object containing information about the current webGL context
  12469. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12470. */
  12471. Engine.prototype.getGlInfo = function () {
  12472. return {
  12473. vendor: this._glVendor,
  12474. renderer: this._glRenderer,
  12475. version: this._glVersion
  12476. };
  12477. };
  12478. /**
  12479. * Gets current aspect ratio
  12480. * @param camera defines the camera to use to get the aspect ratio
  12481. * @param useScreen defines if screen size must be used (or the current render target if any)
  12482. * @returns a number defining the aspect ratio
  12483. */
  12484. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12485. if (useScreen === void 0) { useScreen = false; }
  12486. var viewport = camera.viewport;
  12487. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12488. };
  12489. /**
  12490. * Gets current screen aspect ratio
  12491. * @returns a number defining the aspect ratio
  12492. */
  12493. Engine.prototype.getScreenAspectRatio = function () {
  12494. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12495. };
  12496. /**
  12497. * Gets the current render width
  12498. * @param useScreen defines if screen size must be used (or the current render target if any)
  12499. * @returns a number defining the current render width
  12500. */
  12501. Engine.prototype.getRenderWidth = function (useScreen) {
  12502. if (useScreen === void 0) { useScreen = false; }
  12503. if (!useScreen && this._currentRenderTarget) {
  12504. return this._currentRenderTarget.width;
  12505. }
  12506. return this._gl.drawingBufferWidth;
  12507. };
  12508. /**
  12509. * Gets the current render height
  12510. * @param useScreen defines if screen size must be used (or the current render target if any)
  12511. * @returns a number defining the current render height
  12512. */
  12513. Engine.prototype.getRenderHeight = function (useScreen) {
  12514. if (useScreen === void 0) { useScreen = false; }
  12515. if (!useScreen && this._currentRenderTarget) {
  12516. return this._currentRenderTarget.height;
  12517. }
  12518. return this._gl.drawingBufferHeight;
  12519. };
  12520. /**
  12521. * Gets the HTML canvas attached with the current webGL context
  12522. * @returns a HTML canvas
  12523. */
  12524. Engine.prototype.getRenderingCanvas = function () {
  12525. return this._renderingCanvas;
  12526. };
  12527. /**
  12528. * Gets the client rect of the HTML canvas attached with the current webGL context
  12529. * @returns a client rectanglee
  12530. */
  12531. Engine.prototype.getRenderingCanvasClientRect = function () {
  12532. if (!this._renderingCanvas) {
  12533. return null;
  12534. }
  12535. return this._renderingCanvas.getBoundingClientRect();
  12536. };
  12537. /**
  12538. * Defines the hardware scaling level.
  12539. * By default the hardware scaling level is computed from the window device ratio.
  12540. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12541. * @param level defines the level to use
  12542. */
  12543. Engine.prototype.setHardwareScalingLevel = function (level) {
  12544. this._hardwareScalingLevel = level;
  12545. this.resize();
  12546. };
  12547. /**
  12548. * Gets the current hardware scaling level.
  12549. * By default the hardware scaling level is computed from the window device ratio.
  12550. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12551. * @returns a number indicating the current hardware scaling level
  12552. */
  12553. Engine.prototype.getHardwareScalingLevel = function () {
  12554. return this._hardwareScalingLevel;
  12555. };
  12556. /**
  12557. * Gets the list of loaded textures
  12558. * @returns an array containing all loaded textures
  12559. */
  12560. Engine.prototype.getLoadedTexturesCache = function () {
  12561. return this._internalTexturesCache;
  12562. };
  12563. /**
  12564. * Gets the object containing all engine capabilities
  12565. * @returns the EngineCapabilities object
  12566. */
  12567. Engine.prototype.getCaps = function () {
  12568. return this._caps;
  12569. };
  12570. Object.defineProperty(Engine.prototype, "drawCalls", {
  12571. /** @hidden */
  12572. get: function () {
  12573. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12574. return 0;
  12575. },
  12576. enumerable: true,
  12577. configurable: true
  12578. });
  12579. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12580. /** @hidden */
  12581. get: function () {
  12582. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12583. return null;
  12584. },
  12585. enumerable: true,
  12586. configurable: true
  12587. });
  12588. /**
  12589. * Gets the current depth function
  12590. * @returns a number defining the depth function
  12591. */
  12592. Engine.prototype.getDepthFunction = function () {
  12593. return this._depthCullingState.depthFunc;
  12594. };
  12595. /**
  12596. * Sets the current depth function
  12597. * @param depthFunc defines the function to use
  12598. */
  12599. Engine.prototype.setDepthFunction = function (depthFunc) {
  12600. this._depthCullingState.depthFunc = depthFunc;
  12601. };
  12602. /**
  12603. * Sets the current depth function to GREATER
  12604. */
  12605. Engine.prototype.setDepthFunctionToGreater = function () {
  12606. this._depthCullingState.depthFunc = this._gl.GREATER;
  12607. };
  12608. /**
  12609. * Sets the current depth function to GEQUAL
  12610. */
  12611. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12612. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12613. };
  12614. /**
  12615. * Sets the current depth function to LESS
  12616. */
  12617. Engine.prototype.setDepthFunctionToLess = function () {
  12618. this._depthCullingState.depthFunc = this._gl.LESS;
  12619. };
  12620. /**
  12621. * Sets the current depth function to LEQUAL
  12622. */
  12623. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12624. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12625. };
  12626. /**
  12627. * Gets a boolean indicating if stencil buffer is enabled
  12628. * @returns the current stencil buffer state
  12629. */
  12630. Engine.prototype.getStencilBuffer = function () {
  12631. return this._stencilState.stencilTest;
  12632. };
  12633. /**
  12634. * Enable or disable the stencil buffer
  12635. * @param enable defines if the stencil buffer must be enabled or disabled
  12636. */
  12637. Engine.prototype.setStencilBuffer = function (enable) {
  12638. this._stencilState.stencilTest = enable;
  12639. };
  12640. /**
  12641. * Gets the current stencil mask
  12642. * @returns a number defining the new stencil mask to use
  12643. */
  12644. Engine.prototype.getStencilMask = function () {
  12645. return this._stencilState.stencilMask;
  12646. };
  12647. /**
  12648. * Sets the current stencil mask
  12649. * @param mask defines the new stencil mask to use
  12650. */
  12651. Engine.prototype.setStencilMask = function (mask) {
  12652. this._stencilState.stencilMask = mask;
  12653. };
  12654. /**
  12655. * Gets the current stencil function
  12656. * @returns a number defining the stencil function to use
  12657. */
  12658. Engine.prototype.getStencilFunction = function () {
  12659. return this._stencilState.stencilFunc;
  12660. };
  12661. /**
  12662. * Gets the current stencil reference value
  12663. * @returns a number defining the stencil reference value to use
  12664. */
  12665. Engine.prototype.getStencilFunctionReference = function () {
  12666. return this._stencilState.stencilFuncRef;
  12667. };
  12668. /**
  12669. * Gets the current stencil mask
  12670. * @returns a number defining the stencil mask to use
  12671. */
  12672. Engine.prototype.getStencilFunctionMask = function () {
  12673. return this._stencilState.stencilFuncMask;
  12674. };
  12675. /**
  12676. * Sets the current stencil function
  12677. * @param stencilFunc defines the new stencil function to use
  12678. */
  12679. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12680. this._stencilState.stencilFunc = stencilFunc;
  12681. };
  12682. /**
  12683. * Sets the current stencil reference
  12684. * @param reference defines the new stencil reference to use
  12685. */
  12686. Engine.prototype.setStencilFunctionReference = function (reference) {
  12687. this._stencilState.stencilFuncRef = reference;
  12688. };
  12689. /**
  12690. * Sets the current stencil mask
  12691. * @param mask defines the new stencil mask to use
  12692. */
  12693. Engine.prototype.setStencilFunctionMask = function (mask) {
  12694. this._stencilState.stencilFuncMask = mask;
  12695. };
  12696. /**
  12697. * Gets the current stencil operation when stencil fails
  12698. * @returns a number defining stencil operation to use when stencil fails
  12699. */
  12700. Engine.prototype.getStencilOperationFail = function () {
  12701. return this._stencilState.stencilOpStencilFail;
  12702. };
  12703. /**
  12704. * Gets the current stencil operation when depth fails
  12705. * @returns a number defining stencil operation to use when depth fails
  12706. */
  12707. Engine.prototype.getStencilOperationDepthFail = function () {
  12708. return this._stencilState.stencilOpDepthFail;
  12709. };
  12710. /**
  12711. * Gets the current stencil operation when stencil passes
  12712. * @returns a number defining stencil operation to use when stencil passes
  12713. */
  12714. Engine.prototype.getStencilOperationPass = function () {
  12715. return this._stencilState.stencilOpStencilDepthPass;
  12716. };
  12717. /**
  12718. * Sets the stencil operation to use when stencil fails
  12719. * @param operation defines the stencil operation to use when stencil fails
  12720. */
  12721. Engine.prototype.setStencilOperationFail = function (operation) {
  12722. this._stencilState.stencilOpStencilFail = operation;
  12723. };
  12724. /**
  12725. * Sets the stencil operation to use when depth fails
  12726. * @param operation defines the stencil operation to use when depth fails
  12727. */
  12728. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12729. this._stencilState.stencilOpDepthFail = operation;
  12730. };
  12731. /**
  12732. * Sets the stencil operation to use when stencil passes
  12733. * @param operation defines the stencil operation to use when stencil passes
  12734. */
  12735. Engine.prototype.setStencilOperationPass = function (operation) {
  12736. this._stencilState.stencilOpStencilDepthPass = operation;
  12737. };
  12738. /**
  12739. * Sets a boolean indicating if the dithering state is enabled or disabled
  12740. * @param value defines the dithering state
  12741. */
  12742. Engine.prototype.setDitheringState = function (value) {
  12743. if (value) {
  12744. this._gl.enable(this._gl.DITHER);
  12745. }
  12746. else {
  12747. this._gl.disable(this._gl.DITHER);
  12748. }
  12749. };
  12750. /**
  12751. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12752. * @param value defines the rasterizer state
  12753. */
  12754. Engine.prototype.setRasterizerState = function (value) {
  12755. if (value) {
  12756. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12757. }
  12758. else {
  12759. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12760. }
  12761. };
  12762. /**
  12763. * stop executing a render loop function and remove it from the execution array
  12764. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12765. */
  12766. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12767. if (!renderFunction) {
  12768. this._activeRenderLoops = [];
  12769. return;
  12770. }
  12771. var index = this._activeRenderLoops.indexOf(renderFunction);
  12772. if (index >= 0) {
  12773. this._activeRenderLoops.splice(index, 1);
  12774. }
  12775. };
  12776. /** @hidden */
  12777. Engine.prototype._renderLoop = function () {
  12778. if (!this._contextWasLost) {
  12779. var shouldRender = true;
  12780. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12781. shouldRender = false;
  12782. }
  12783. if (shouldRender) {
  12784. // Start new frame
  12785. this.beginFrame();
  12786. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12787. var renderFunction = this._activeRenderLoops[index];
  12788. renderFunction();
  12789. }
  12790. // Present
  12791. this.endFrame();
  12792. }
  12793. }
  12794. if (this._activeRenderLoops.length > 0) {
  12795. // Register new frame
  12796. var requester = null;
  12797. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12798. requester = this._vrDisplay;
  12799. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12800. }
  12801. else {
  12802. this._renderingQueueLaunched = false;
  12803. }
  12804. };
  12805. /**
  12806. * Register and execute a render loop. The engine can have more than one render function
  12807. * @param renderFunction defines the function to continuously execute
  12808. */
  12809. Engine.prototype.runRenderLoop = function (renderFunction) {
  12810. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12811. return;
  12812. }
  12813. this._activeRenderLoops.push(renderFunction);
  12814. if (!this._renderingQueueLaunched) {
  12815. this._renderingQueueLaunched = true;
  12816. this._bindedRenderFunction = this._renderLoop.bind(this);
  12817. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12818. }
  12819. };
  12820. /**
  12821. * Toggle full screen mode
  12822. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12823. * @param options defines an option object to be sent to the requestFullscreen function
  12824. */
  12825. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12826. if (this.isFullscreen) {
  12827. BABYLON.Tools.ExitFullscreen();
  12828. }
  12829. else {
  12830. this._pointerLockRequested = requestPointerLock;
  12831. if (this._renderingCanvas) {
  12832. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12833. }
  12834. }
  12835. };
  12836. /**
  12837. * Clear the current render buffer or the current render target (if any is set up)
  12838. * @param color defines the color to use
  12839. * @param backBuffer defines if the back buffer must be cleared
  12840. * @param depth defines if the depth buffer must be cleared
  12841. * @param stencil defines if the stencil buffer must be cleared
  12842. */
  12843. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12844. if (stencil === void 0) { stencil = false; }
  12845. this.applyStates();
  12846. var mode = 0;
  12847. if (backBuffer && color) {
  12848. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12849. mode |= this._gl.COLOR_BUFFER_BIT;
  12850. }
  12851. if (depth) {
  12852. this._gl.clearDepth(1.0);
  12853. mode |= this._gl.DEPTH_BUFFER_BIT;
  12854. }
  12855. if (stencil) {
  12856. this._gl.clearStencil(0);
  12857. mode |= this._gl.STENCIL_BUFFER_BIT;
  12858. }
  12859. this._gl.clear(mode);
  12860. };
  12861. /**
  12862. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12863. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12864. * @param y defines the y-coordinate of the corner of the clear rectangle
  12865. * @param width defines the width of the clear rectangle
  12866. * @param height defines the height of the clear rectangle
  12867. * @param clearColor defines the clear color
  12868. */
  12869. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12870. var gl = this._gl;
  12871. // Save state
  12872. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12873. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12874. // Change state
  12875. gl.enable(gl.SCISSOR_TEST);
  12876. gl.scissor(x, y, width, height);
  12877. // Clear
  12878. this.clear(clearColor, true, true, true);
  12879. // Restore state
  12880. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12881. if (curScissor === true) {
  12882. gl.enable(gl.SCISSOR_TEST);
  12883. }
  12884. else {
  12885. gl.disable(gl.SCISSOR_TEST);
  12886. }
  12887. };
  12888. /**
  12889. * Set the WebGL's viewport
  12890. * @param viewport defines the viewport element to be used
  12891. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12892. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12893. */
  12894. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12895. var width = requiredWidth || this.getRenderWidth();
  12896. var height = requiredHeight || this.getRenderHeight();
  12897. var x = viewport.x || 0;
  12898. var y = viewport.y || 0;
  12899. this._cachedViewport = viewport;
  12900. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12901. };
  12902. /**
  12903. * Directly set the WebGL Viewport
  12904. * @param x defines the x coordinate of the viewport (in screen space)
  12905. * @param y defines the y coordinate of the viewport (in screen space)
  12906. * @param width defines the width of the viewport (in screen space)
  12907. * @param height defines the height of the viewport (in screen space)
  12908. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  12909. */
  12910. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12911. var currentViewport = this._cachedViewport;
  12912. this._cachedViewport = null;
  12913. this._gl.viewport(x, y, width, height);
  12914. return currentViewport;
  12915. };
  12916. /**
  12917. * Begin a new frame
  12918. */
  12919. Engine.prototype.beginFrame = function () {
  12920. this.onBeginFrameObservable.notifyObservers(this);
  12921. this._measureFps();
  12922. };
  12923. /**
  12924. * Enf the current frame
  12925. */
  12926. Engine.prototype.endFrame = function () {
  12927. // Force a flush in case we are using a bad OS.
  12928. if (this._badOS) {
  12929. this.flushFramebuffer();
  12930. }
  12931. // Submit frame to the vr device, if enabled
  12932. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12933. // TODO: We should only submit the frame if we read frameData successfully.
  12934. this._vrDisplay.submitFrame();
  12935. }
  12936. this.onEndFrameObservable.notifyObservers(this);
  12937. };
  12938. /**
  12939. * Resize the view according to the canvas' size
  12940. */
  12941. Engine.prototype.resize = function () {
  12942. // We're not resizing the size of the canvas while in VR mode & presenting
  12943. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12944. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12945. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12946. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12947. }
  12948. };
  12949. /**
  12950. * Force a specific size of the canvas
  12951. * @param width defines the new canvas' width
  12952. * @param height defines the new canvas' height
  12953. */
  12954. Engine.prototype.setSize = function (width, height) {
  12955. if (!this._renderingCanvas) {
  12956. return;
  12957. }
  12958. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12959. return;
  12960. }
  12961. this._renderingCanvas.width = width;
  12962. this._renderingCanvas.height = height;
  12963. for (var index = 0; index < this.scenes.length; index++) {
  12964. var scene = this.scenes[index];
  12965. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12966. var cam = scene.cameras[camIndex];
  12967. cam._currentRenderId = 0;
  12968. }
  12969. }
  12970. if (this.onResizeObservable.hasObservers) {
  12971. this.onResizeObservable.notifyObservers(this);
  12972. }
  12973. };
  12974. // WebVR functions
  12975. /**
  12976. * Gets a boolean indicating if a webVR device was detected
  12977. * @returns true if a webVR device was detected
  12978. */
  12979. Engine.prototype.isVRDevicePresent = function () {
  12980. return !!this._vrDisplay;
  12981. };
  12982. /**
  12983. * Gets the current webVR device
  12984. * @returns the current webVR device (or null)
  12985. */
  12986. Engine.prototype.getVRDevice = function () {
  12987. return this._vrDisplay;
  12988. };
  12989. /**
  12990. * Initializes a webVR display and starts listening to display change events
  12991. * The onVRDisplayChangedObservable will be notified upon these changes
  12992. * @returns The onVRDisplayChangedObservable
  12993. */
  12994. Engine.prototype.initWebVR = function () {
  12995. this.initWebVRAsync();
  12996. return this.onVRDisplayChangedObservable;
  12997. };
  12998. /**
  12999. * Initializes a webVR display and starts listening to display change events
  13000. * The onVRDisplayChangedObservable will be notified upon these changes
  13001. * @returns A promise containing a VRDisplay and if vr is supported
  13002. */
  13003. Engine.prototype.initWebVRAsync = function () {
  13004. var _this = this;
  13005. var notifyObservers = function () {
  13006. var eventArgs = {
  13007. vrDisplay: _this._vrDisplay,
  13008. vrSupported: _this._vrSupported
  13009. };
  13010. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13011. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13012. };
  13013. if (!this._onVrDisplayConnect) {
  13014. this._onVrDisplayConnect = function (event) {
  13015. _this._vrDisplay = event.display;
  13016. notifyObservers();
  13017. };
  13018. this._onVrDisplayDisconnect = function () {
  13019. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13020. _this._vrDisplay = undefined;
  13021. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13022. notifyObservers();
  13023. };
  13024. this._onVrDisplayPresentChange = function () {
  13025. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13026. };
  13027. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13028. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13029. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13030. }
  13031. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13032. this._webVRInitPromise.then(notifyObservers);
  13033. return this._webVRInitPromise;
  13034. };
  13035. /**
  13036. * Call this function to switch to webVR mode
  13037. * Will do nothing if webVR is not supported or if there is no webVR device
  13038. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13039. */
  13040. Engine.prototype.enableVR = function () {
  13041. var _this = this;
  13042. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13043. var onResolved = function () {
  13044. _this.onVRRequestPresentComplete.notifyObservers(true);
  13045. _this._onVRFullScreenTriggered();
  13046. };
  13047. var onRejected = function () {
  13048. _this.onVRRequestPresentComplete.notifyObservers(false);
  13049. };
  13050. this.onVRRequestPresentStart.notifyObservers(this);
  13051. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13052. }
  13053. };
  13054. /**
  13055. * Call this function to leave webVR mode
  13056. * Will do nothing if webVR is not supported or if there is no webVR device
  13057. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13058. */
  13059. Engine.prototype.disableVR = function () {
  13060. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13061. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13062. }
  13063. };
  13064. Engine.prototype._getVRDisplaysAsync = function () {
  13065. var _this = this;
  13066. return new Promise(function (res, rej) {
  13067. if (navigator.getVRDisplays) {
  13068. navigator.getVRDisplays().then(function (devices) {
  13069. _this._vrSupported = true;
  13070. // note that devices may actually be an empty array. This is fine;
  13071. // we expect this._vrDisplay to be undefined in this case.
  13072. _this._vrDisplay = devices[0];
  13073. res({
  13074. vrDisplay: _this._vrDisplay,
  13075. vrSupported: _this._vrSupported
  13076. });
  13077. });
  13078. }
  13079. else {
  13080. _this._vrDisplay = undefined;
  13081. _this._vrSupported = false;
  13082. res({
  13083. vrDisplay: _this._vrDisplay,
  13084. vrSupported: _this._vrSupported
  13085. });
  13086. }
  13087. });
  13088. };
  13089. /**
  13090. * Binds the frame buffer to the specified texture.
  13091. * @param texture The texture to render to or null for the default canvas
  13092. * @param faceIndex The face of the texture to render to in case of cube texture
  13093. * @param requiredWidth The width of the target to render to
  13094. * @param requiredHeight The height of the target to render to
  13095. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13096. * @param depthStencilTexture The depth stencil texture to use to render
  13097. */
  13098. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13099. if (this._currentRenderTarget) {
  13100. this.unBindFramebuffer(this._currentRenderTarget);
  13101. }
  13102. this._currentRenderTarget = texture;
  13103. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13104. var gl = this._gl;
  13105. if (texture.isCube) {
  13106. if (faceIndex === undefined) {
  13107. faceIndex = 0;
  13108. }
  13109. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13110. if (depthStencilTexture) {
  13111. if (depthStencilTexture._generateStencilBuffer) {
  13112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13113. }
  13114. else {
  13115. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13116. }
  13117. }
  13118. }
  13119. if (this._cachedViewport && !forceFullscreenViewport) {
  13120. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13121. }
  13122. else {
  13123. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13124. }
  13125. this.wipeCaches();
  13126. };
  13127. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13128. if (this._currentFramebuffer !== framebuffer) {
  13129. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13130. this._currentFramebuffer = framebuffer;
  13131. }
  13132. };
  13133. /**
  13134. * Unbind the current render target texture from the webGL context
  13135. * @param texture defines the render target texture to unbind
  13136. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13137. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13138. */
  13139. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13140. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13141. this._currentRenderTarget = null;
  13142. // If MSAA, we need to bitblt back to main texture
  13143. var gl = this._gl;
  13144. if (texture._MSAAFramebuffer) {
  13145. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13146. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13147. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13148. }
  13149. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13150. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13151. gl.generateMipmap(gl.TEXTURE_2D);
  13152. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13153. }
  13154. if (onBeforeUnbind) {
  13155. if (texture._MSAAFramebuffer) {
  13156. // Bind the correct framebuffer
  13157. this.bindUnboundFramebuffer(texture._framebuffer);
  13158. }
  13159. onBeforeUnbind();
  13160. }
  13161. this.bindUnboundFramebuffer(null);
  13162. };
  13163. /**
  13164. * Unbind a list of render target textures from the webGL context
  13165. * This is used only when drawBuffer extension or webGL2 are active
  13166. * @param textures defines the render target textures to unbind
  13167. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13168. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13169. */
  13170. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13171. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13172. this._currentRenderTarget = null;
  13173. // If MSAA, we need to bitblt back to main texture
  13174. var gl = this._gl;
  13175. if (textures[0]._MSAAFramebuffer) {
  13176. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13177. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13178. var attachments = textures[0]._attachments;
  13179. if (!attachments) {
  13180. attachments = new Array(textures.length);
  13181. textures[0]._attachments = attachments;
  13182. }
  13183. for (var i = 0; i < textures.length; i++) {
  13184. var texture = textures[i];
  13185. for (var j = 0; j < attachments.length; j++) {
  13186. attachments[j] = gl.NONE;
  13187. }
  13188. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13189. gl.readBuffer(attachments[i]);
  13190. gl.drawBuffers(attachments);
  13191. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13192. }
  13193. for (var i = 0; i < attachments.length; i++) {
  13194. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13195. }
  13196. gl.drawBuffers(attachments);
  13197. }
  13198. for (var i = 0; i < textures.length; i++) {
  13199. var texture = textures[i];
  13200. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13201. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13202. gl.generateMipmap(gl.TEXTURE_2D);
  13203. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13204. }
  13205. }
  13206. if (onBeforeUnbind) {
  13207. if (textures[0]._MSAAFramebuffer) {
  13208. // Bind the correct framebuffer
  13209. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13210. }
  13211. onBeforeUnbind();
  13212. }
  13213. this.bindUnboundFramebuffer(null);
  13214. };
  13215. /**
  13216. * Force the mipmap generation for the given render target texture
  13217. * @param texture defines the render target texture to use
  13218. */
  13219. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13220. if (texture.generateMipMaps) {
  13221. var gl = this._gl;
  13222. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13223. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13224. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13225. }
  13226. };
  13227. /**
  13228. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13229. */
  13230. Engine.prototype.flushFramebuffer = function () {
  13231. this._gl.flush();
  13232. };
  13233. /**
  13234. * Unbind the current render target and bind the default framebuffer
  13235. */
  13236. Engine.prototype.restoreDefaultFramebuffer = function () {
  13237. if (this._currentRenderTarget) {
  13238. this.unBindFramebuffer(this._currentRenderTarget);
  13239. }
  13240. else {
  13241. this.bindUnboundFramebuffer(null);
  13242. }
  13243. if (this._cachedViewport) {
  13244. this.setViewport(this._cachedViewport);
  13245. }
  13246. this.wipeCaches();
  13247. };
  13248. // UBOs
  13249. /**
  13250. * Create an uniform buffer
  13251. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13252. * @param elements defines the content of the uniform buffer
  13253. * @returns the webGL uniform buffer
  13254. */
  13255. Engine.prototype.createUniformBuffer = function (elements) {
  13256. var ubo = this._gl.createBuffer();
  13257. if (!ubo) {
  13258. throw new Error("Unable to create uniform buffer");
  13259. }
  13260. this.bindUniformBuffer(ubo);
  13261. if (elements instanceof Float32Array) {
  13262. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13263. }
  13264. else {
  13265. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13266. }
  13267. this.bindUniformBuffer(null);
  13268. ubo.references = 1;
  13269. return ubo;
  13270. };
  13271. /**
  13272. * Create a dynamic uniform buffer
  13273. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13274. * @param elements defines the content of the uniform buffer
  13275. * @returns the webGL uniform buffer
  13276. */
  13277. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13278. var ubo = this._gl.createBuffer();
  13279. if (!ubo) {
  13280. throw new Error("Unable to create dynamic uniform buffer");
  13281. }
  13282. this.bindUniformBuffer(ubo);
  13283. if (elements instanceof Float32Array) {
  13284. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13285. }
  13286. else {
  13287. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13288. }
  13289. this.bindUniformBuffer(null);
  13290. ubo.references = 1;
  13291. return ubo;
  13292. };
  13293. /**
  13294. * Update an existing uniform buffer
  13295. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13296. * @param uniformBuffer defines the target uniform buffer
  13297. * @param elements defines the content to update
  13298. * @param offset defines the offset in the uniform buffer where update should start
  13299. * @param count defines the size of the data to update
  13300. */
  13301. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13302. this.bindUniformBuffer(uniformBuffer);
  13303. if (offset === undefined) {
  13304. offset = 0;
  13305. }
  13306. if (count === undefined) {
  13307. if (elements instanceof Float32Array) {
  13308. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13309. }
  13310. else {
  13311. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13312. }
  13313. }
  13314. else {
  13315. if (elements instanceof Float32Array) {
  13316. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13317. }
  13318. else {
  13319. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13320. }
  13321. }
  13322. this.bindUniformBuffer(null);
  13323. };
  13324. // VBOs
  13325. Engine.prototype._resetVertexBufferBinding = function () {
  13326. this.bindArrayBuffer(null);
  13327. this._cachedVertexBuffers = null;
  13328. };
  13329. /**
  13330. * Creates a vertex buffer
  13331. * @param data the data for the vertex buffer
  13332. * @returns the new WebGL static buffer
  13333. */
  13334. Engine.prototype.createVertexBuffer = function (data) {
  13335. var vbo = this._gl.createBuffer();
  13336. if (!vbo) {
  13337. throw new Error("Unable to create vertex buffer");
  13338. }
  13339. this.bindArrayBuffer(vbo);
  13340. if (data instanceof Array) {
  13341. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13342. }
  13343. else {
  13344. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13345. }
  13346. this._resetVertexBufferBinding();
  13347. vbo.references = 1;
  13348. return vbo;
  13349. };
  13350. /**
  13351. * Creates a dynamic vertex buffer
  13352. * @param data the data for the dynamic vertex buffer
  13353. * @returns the new WebGL dynamic buffer
  13354. */
  13355. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13356. var vbo = this._gl.createBuffer();
  13357. if (!vbo) {
  13358. throw new Error("Unable to create dynamic vertex buffer");
  13359. }
  13360. this.bindArrayBuffer(vbo);
  13361. if (data instanceof Array) {
  13362. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13363. }
  13364. else {
  13365. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13366. }
  13367. this._resetVertexBufferBinding();
  13368. vbo.references = 1;
  13369. return vbo;
  13370. };
  13371. /**
  13372. * Update a dynamic index buffer
  13373. * @param indexBuffer defines the target index buffer
  13374. * @param indices defines the data to update
  13375. * @param offset defines the offset in the target index buffer where update should start
  13376. */
  13377. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13378. if (offset === void 0) { offset = 0; }
  13379. // Force cache update
  13380. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13381. this.bindIndexBuffer(indexBuffer);
  13382. var arrayBuffer;
  13383. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13384. arrayBuffer = indices;
  13385. }
  13386. else {
  13387. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13388. }
  13389. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13390. this._resetIndexBufferBinding();
  13391. };
  13392. /**
  13393. * Updates a dynamic vertex buffer.
  13394. * @param vertexBuffer the vertex buffer to update
  13395. * @param data the data used to update the vertex buffer
  13396. * @param byteOffset the byte offset of the data
  13397. * @param byteLength the byte length of the data
  13398. */
  13399. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13400. this.bindArrayBuffer(vertexBuffer);
  13401. if (byteOffset === undefined) {
  13402. byteOffset = 0;
  13403. }
  13404. if (byteLength === undefined) {
  13405. if (data instanceof Array) {
  13406. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13407. }
  13408. else {
  13409. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13410. }
  13411. }
  13412. else {
  13413. if (data instanceof Array) {
  13414. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13415. }
  13416. else {
  13417. if (data instanceof ArrayBuffer) {
  13418. data = new Uint8Array(data, byteOffset, byteLength);
  13419. }
  13420. else {
  13421. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13422. }
  13423. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13424. }
  13425. }
  13426. this._resetVertexBufferBinding();
  13427. };
  13428. Engine.prototype._resetIndexBufferBinding = function () {
  13429. this.bindIndexBuffer(null);
  13430. this._cachedIndexBuffer = null;
  13431. };
  13432. /**
  13433. * Creates a new index buffer
  13434. * @param indices defines the content of the index buffer
  13435. * @param updatable defines if the index buffer must be updatable
  13436. * @returns a new webGL buffer
  13437. */
  13438. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13439. var vbo = this._gl.createBuffer();
  13440. if (!vbo) {
  13441. throw new Error("Unable to create index buffer");
  13442. }
  13443. this.bindIndexBuffer(vbo);
  13444. // Check for 32 bits indices
  13445. var arrayBuffer;
  13446. var need32Bits = false;
  13447. if (indices instanceof Uint16Array) {
  13448. arrayBuffer = indices;
  13449. }
  13450. else {
  13451. //check 32 bit support
  13452. if (this._caps.uintIndices) {
  13453. if (indices instanceof Uint32Array) {
  13454. arrayBuffer = indices;
  13455. need32Bits = true;
  13456. }
  13457. else {
  13458. //number[] or Int32Array, check if 32 bit is necessary
  13459. for (var index = 0; index < indices.length; index++) {
  13460. if (indices[index] > 65535) {
  13461. need32Bits = true;
  13462. break;
  13463. }
  13464. }
  13465. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13466. }
  13467. }
  13468. else {
  13469. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13470. arrayBuffer = new Uint16Array(indices);
  13471. }
  13472. }
  13473. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13474. this._resetIndexBufferBinding();
  13475. vbo.references = 1;
  13476. vbo.is32Bits = need32Bits;
  13477. return vbo;
  13478. };
  13479. /**
  13480. * Bind a webGL buffer to the webGL context
  13481. * @param buffer defines the buffer to bind
  13482. */
  13483. Engine.prototype.bindArrayBuffer = function (buffer) {
  13484. if (!this._vaoRecordInProgress) {
  13485. this._unbindVertexArrayObject();
  13486. }
  13487. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13488. };
  13489. /**
  13490. * Bind an uniform buffer to the current webGL context
  13491. * @param buffer defines the buffer to bind
  13492. */
  13493. Engine.prototype.bindUniformBuffer = function (buffer) {
  13494. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13495. };
  13496. /**
  13497. * Bind a buffer to the current webGL context at a given location
  13498. * @param buffer defines the buffer to bind
  13499. * @param location defines the index where to bind the buffer
  13500. */
  13501. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13502. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13503. };
  13504. /**
  13505. * Bind a specific block at a given index in a specific shader program
  13506. * @param shaderProgram defines the shader program
  13507. * @param blockName defines the block name
  13508. * @param index defines the index where to bind the block
  13509. */
  13510. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13511. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13512. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13513. };
  13514. ;
  13515. Engine.prototype.bindIndexBuffer = function (buffer) {
  13516. if (!this._vaoRecordInProgress) {
  13517. this._unbindVertexArrayObject();
  13518. }
  13519. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13520. };
  13521. Engine.prototype.bindBuffer = function (buffer, target) {
  13522. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13523. this._gl.bindBuffer(target, buffer);
  13524. this._currentBoundBuffer[target] = buffer;
  13525. }
  13526. };
  13527. /**
  13528. * update the bound buffer with the given data
  13529. * @param data defines the data to update
  13530. */
  13531. Engine.prototype.updateArrayBuffer = function (data) {
  13532. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13533. };
  13534. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13535. var pointer = this._currentBufferPointers[indx];
  13536. var changed = false;
  13537. if (!pointer.active) {
  13538. changed = true;
  13539. pointer.active = true;
  13540. pointer.index = indx;
  13541. pointer.size = size;
  13542. pointer.type = type;
  13543. pointer.normalized = normalized;
  13544. pointer.stride = stride;
  13545. pointer.offset = offset;
  13546. pointer.buffer = buffer;
  13547. }
  13548. else {
  13549. if (pointer.buffer !== buffer) {
  13550. pointer.buffer = buffer;
  13551. changed = true;
  13552. }
  13553. if (pointer.size !== size) {
  13554. pointer.size = size;
  13555. changed = true;
  13556. }
  13557. if (pointer.type !== type) {
  13558. pointer.type = type;
  13559. changed = true;
  13560. }
  13561. if (pointer.normalized !== normalized) {
  13562. pointer.normalized = normalized;
  13563. changed = true;
  13564. }
  13565. if (pointer.stride !== stride) {
  13566. pointer.stride = stride;
  13567. changed = true;
  13568. }
  13569. if (pointer.offset !== offset) {
  13570. pointer.offset = offset;
  13571. changed = true;
  13572. }
  13573. }
  13574. if (changed || this._vaoRecordInProgress) {
  13575. this.bindArrayBuffer(buffer);
  13576. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13577. }
  13578. };
  13579. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13580. if (indexBuffer == null) {
  13581. return;
  13582. }
  13583. if (this._cachedIndexBuffer !== indexBuffer) {
  13584. this._cachedIndexBuffer = indexBuffer;
  13585. this.bindIndexBuffer(indexBuffer);
  13586. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13587. }
  13588. };
  13589. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13590. var attributes = effect.getAttributesNames();
  13591. if (!this._vaoRecordInProgress) {
  13592. this._unbindVertexArrayObject();
  13593. }
  13594. this.unbindAllAttributes();
  13595. for (var index = 0; index < attributes.length; index++) {
  13596. var order = effect.getAttributeLocation(index);
  13597. if (order >= 0) {
  13598. var vertexBuffer = vertexBuffers[attributes[index]];
  13599. if (!vertexBuffer) {
  13600. continue;
  13601. }
  13602. this._gl.enableVertexAttribArray(order);
  13603. if (!this._vaoRecordInProgress) {
  13604. this._vertexAttribArraysEnabled[order] = true;
  13605. }
  13606. var buffer = vertexBuffer.getBuffer();
  13607. if (buffer) {
  13608. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13609. if (vertexBuffer.getIsInstanced()) {
  13610. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13611. if (!this._vaoRecordInProgress) {
  13612. this._currentInstanceLocations.push(order);
  13613. this._currentInstanceBuffers.push(buffer);
  13614. }
  13615. }
  13616. }
  13617. }
  13618. }
  13619. };
  13620. /**
  13621. * Records a vertex array object
  13622. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13623. * @param vertexBuffers defines the list of vertex buffers to store
  13624. * @param indexBuffer defines the index buffer to store
  13625. * @param effect defines the effect to store
  13626. * @returns the new vertex array object
  13627. */
  13628. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13629. var vao = this._gl.createVertexArray();
  13630. this._vaoRecordInProgress = true;
  13631. this._gl.bindVertexArray(vao);
  13632. this._mustWipeVertexAttributes = true;
  13633. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13634. this.bindIndexBuffer(indexBuffer);
  13635. this._vaoRecordInProgress = false;
  13636. this._gl.bindVertexArray(null);
  13637. return vao;
  13638. };
  13639. /**
  13640. * Bind a specific vertex array object
  13641. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13642. * @param vertexArrayObject defines the vertex array object to bind
  13643. * @param indexBuffer defines the index buffer to bind
  13644. */
  13645. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13646. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13647. this._cachedVertexArrayObject = vertexArrayObject;
  13648. this._gl.bindVertexArray(vertexArrayObject);
  13649. this._cachedVertexBuffers = null;
  13650. this._cachedIndexBuffer = null;
  13651. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13652. this._mustWipeVertexAttributes = true;
  13653. }
  13654. };
  13655. /**
  13656. * Bind webGl buffers directly to the webGL context
  13657. * @param vertexBuffer defines the vertex buffer to bind
  13658. * @param indexBuffer defines the index buffer to bind
  13659. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13660. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13661. * @param effect defines the effect associated with the vertex buffer
  13662. */
  13663. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13664. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13665. this._cachedVertexBuffers = vertexBuffer;
  13666. this._cachedEffectForVertexBuffers = effect;
  13667. var attributesCount = effect.getAttributesCount();
  13668. this._unbindVertexArrayObject();
  13669. this.unbindAllAttributes();
  13670. var offset = 0;
  13671. for (var index = 0; index < attributesCount; index++) {
  13672. if (index < vertexDeclaration.length) {
  13673. var order = effect.getAttributeLocation(index);
  13674. if (order >= 0) {
  13675. this._gl.enableVertexAttribArray(order);
  13676. this._vertexAttribArraysEnabled[order] = true;
  13677. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13678. }
  13679. offset += vertexDeclaration[index] * 4;
  13680. }
  13681. }
  13682. }
  13683. this._bindIndexBufferWithCache(indexBuffer);
  13684. };
  13685. Engine.prototype._unbindVertexArrayObject = function () {
  13686. if (!this._cachedVertexArrayObject) {
  13687. return;
  13688. }
  13689. this._cachedVertexArrayObject = null;
  13690. this._gl.bindVertexArray(null);
  13691. };
  13692. /**
  13693. * Bind a list of vertex buffers to the webGL context
  13694. * @param vertexBuffers defines the list of vertex buffers to bind
  13695. * @param indexBuffer defines the index buffer to bind
  13696. * @param effect defines the effect associated with the vertex buffers
  13697. */
  13698. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13699. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13700. this._cachedVertexBuffers = vertexBuffers;
  13701. this._cachedEffectForVertexBuffers = effect;
  13702. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13703. }
  13704. this._bindIndexBufferWithCache(indexBuffer);
  13705. };
  13706. /**
  13707. * Unbind all instance attributes
  13708. */
  13709. Engine.prototype.unbindInstanceAttributes = function () {
  13710. var boundBuffer;
  13711. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13712. var instancesBuffer = this._currentInstanceBuffers[i];
  13713. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13714. boundBuffer = instancesBuffer;
  13715. this.bindArrayBuffer(instancesBuffer);
  13716. }
  13717. var offsetLocation = this._currentInstanceLocations[i];
  13718. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13719. }
  13720. this._currentInstanceBuffers.length = 0;
  13721. this._currentInstanceLocations.length = 0;
  13722. };
  13723. /**
  13724. * Release and free the memory of a vertex array object
  13725. * @param vao defines the vertex array object to delete
  13726. */
  13727. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13728. this._gl.deleteVertexArray(vao);
  13729. };
  13730. /** @hidden */
  13731. Engine.prototype._releaseBuffer = function (buffer) {
  13732. buffer.references--;
  13733. if (buffer.references === 0) {
  13734. this._gl.deleteBuffer(buffer);
  13735. return true;
  13736. }
  13737. return false;
  13738. };
  13739. /**
  13740. * Creates a webGL buffer to use with instanciation
  13741. * @param capacity defines the size of the buffer
  13742. * @returns the webGL buffer
  13743. */
  13744. Engine.prototype.createInstancesBuffer = function (capacity) {
  13745. var buffer = this._gl.createBuffer();
  13746. if (!buffer) {
  13747. throw new Error("Unable to create instance buffer");
  13748. }
  13749. buffer.capacity = capacity;
  13750. this.bindArrayBuffer(buffer);
  13751. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13752. return buffer;
  13753. };
  13754. /**
  13755. * Delete a webGL buffer used with instanciation
  13756. * @param buffer defines the webGL buffer to delete
  13757. */
  13758. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13759. this._gl.deleteBuffer(buffer);
  13760. };
  13761. /**
  13762. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13763. * @param instancesBuffer defines the webGL buffer to update and bind
  13764. * @param data defines the data to store in the buffer
  13765. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13766. */
  13767. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13768. this.bindArrayBuffer(instancesBuffer);
  13769. if (data) {
  13770. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13771. }
  13772. if (offsetLocations[0].index !== undefined) {
  13773. var stride = 0;
  13774. for (var i = 0; i < offsetLocations.length; i++) {
  13775. var ai = offsetLocations[i];
  13776. stride += ai.attributeSize * 4;
  13777. }
  13778. for (var i = 0; i < offsetLocations.length; i++) {
  13779. var ai = offsetLocations[i];
  13780. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13781. this._gl.enableVertexAttribArray(ai.index);
  13782. this._vertexAttribArraysEnabled[ai.index] = true;
  13783. }
  13784. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13785. this._gl.vertexAttribDivisor(ai.index, 1);
  13786. this._currentInstanceLocations.push(ai.index);
  13787. this._currentInstanceBuffers.push(instancesBuffer);
  13788. }
  13789. }
  13790. else {
  13791. for (var index = 0; index < 4; index++) {
  13792. var offsetLocation = offsetLocations[index];
  13793. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13794. this._gl.enableVertexAttribArray(offsetLocation);
  13795. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13796. }
  13797. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13798. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13799. this._currentInstanceLocations.push(offsetLocation);
  13800. this._currentInstanceBuffers.push(instancesBuffer);
  13801. }
  13802. }
  13803. };
  13804. /**
  13805. * Apply all cached states (depth, culling, stencil and alpha)
  13806. */
  13807. Engine.prototype.applyStates = function () {
  13808. this._depthCullingState.apply(this._gl);
  13809. this._stencilState.apply(this._gl);
  13810. this._alphaState.apply(this._gl);
  13811. };
  13812. /**
  13813. * Send a draw order
  13814. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13815. * @param indexStart defines the starting index
  13816. * @param indexCount defines the number of index to draw
  13817. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13818. */
  13819. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13820. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13821. };
  13822. /**
  13823. * Draw a list of points
  13824. * @param verticesStart defines the index of first vertex to draw
  13825. * @param verticesCount defines the count of vertices to draw
  13826. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13827. */
  13828. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13829. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13830. };
  13831. /**
  13832. * Draw a list of unindexed primitives
  13833. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13834. * @param verticesStart defines the index of first vertex to draw
  13835. * @param verticesCount defines the count of vertices to draw
  13836. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13837. */
  13838. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13839. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13840. };
  13841. /**
  13842. * Draw a list of indexed primitives
  13843. * @param fillMode defines the primitive to use
  13844. * @param indexStart defines the starting index
  13845. * @param indexCount defines the number of index to draw
  13846. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13847. */
  13848. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13849. // Apply states
  13850. this.applyStates();
  13851. this._drawCalls.addCount(1, false);
  13852. // Render
  13853. var drawMode = this._drawMode(fillMode);
  13854. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13855. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13856. if (instancesCount) {
  13857. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13858. }
  13859. else {
  13860. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13861. }
  13862. };
  13863. /**
  13864. * Draw a list of unindexed primitives
  13865. * @param fillMode defines the primitive to use
  13866. * @param verticesStart defines the index of first vertex to draw
  13867. * @param verticesCount defines the count of vertices to draw
  13868. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13869. */
  13870. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13871. // Apply states
  13872. this.applyStates();
  13873. this._drawCalls.addCount(1, false);
  13874. var drawMode = this._drawMode(fillMode);
  13875. if (instancesCount) {
  13876. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13877. }
  13878. else {
  13879. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13880. }
  13881. };
  13882. Engine.prototype._drawMode = function (fillMode) {
  13883. switch (fillMode) {
  13884. // Triangle views
  13885. case BABYLON.Material.TriangleFillMode:
  13886. return this._gl.TRIANGLES;
  13887. case BABYLON.Material.PointFillMode:
  13888. return this._gl.POINTS;
  13889. case BABYLON.Material.WireFrameFillMode:
  13890. return this._gl.LINES;
  13891. // Draw modes
  13892. case BABYLON.Material.PointListDrawMode:
  13893. return this._gl.POINTS;
  13894. case BABYLON.Material.LineListDrawMode:
  13895. return this._gl.LINES;
  13896. case BABYLON.Material.LineLoopDrawMode:
  13897. return this._gl.LINE_LOOP;
  13898. case BABYLON.Material.LineStripDrawMode:
  13899. return this._gl.LINE_STRIP;
  13900. case BABYLON.Material.TriangleStripDrawMode:
  13901. return this._gl.TRIANGLE_STRIP;
  13902. case BABYLON.Material.TriangleFanDrawMode:
  13903. return this._gl.TRIANGLE_FAN;
  13904. default:
  13905. return this._gl.TRIANGLES;
  13906. }
  13907. };
  13908. // Shaders
  13909. /** @hidden */
  13910. Engine.prototype._releaseEffect = function (effect) {
  13911. if (this._compiledEffects[effect._key]) {
  13912. delete this._compiledEffects[effect._key];
  13913. this._deleteProgram(effect.getProgram());
  13914. }
  13915. };
  13916. /** @hidden */
  13917. Engine.prototype._deleteProgram = function (program) {
  13918. if (program) {
  13919. program.__SPECTOR_rebuildProgram = null;
  13920. if (program.transformFeedback) {
  13921. this.deleteTransformFeedback(program.transformFeedback);
  13922. program.transformFeedback = null;
  13923. }
  13924. this._gl.deleteProgram(program);
  13925. }
  13926. };
  13927. /**
  13928. * Create a new effect (used to store vertex/fragment shaders)
  13929. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13930. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13931. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13932. * @param samplers defines an array of string used to represent textures
  13933. * @param defines defines the string containing the defines to use to compile the shaders
  13934. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13935. * @param onCompiled defines a function to call when the effect creation is successful
  13936. * @param onError defines a function to call when the effect creation has failed
  13937. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13938. * @returns the new Effect
  13939. */
  13940. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13941. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13942. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13943. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13944. if (this._compiledEffects[name]) {
  13945. var compiledEffect = this._compiledEffects[name];
  13946. if (onCompiled && compiledEffect.isReady()) {
  13947. onCompiled(compiledEffect);
  13948. }
  13949. return compiledEffect;
  13950. }
  13951. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13952. effect._key = name;
  13953. this._compiledEffects[name] = effect;
  13954. return effect;
  13955. };
  13956. /**
  13957. * Create an effect to use with particle systems
  13958. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13959. * @param uniformsNames defines a list of attribute names
  13960. * @param samplers defines an array of string used to represent textures
  13961. * @param defines defines the string containing the defines to use to compile the shaders
  13962. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13963. * @param onCompiled defines a function to call when the effect creation is successful
  13964. * @param onError defines a function to call when the effect creation has failed
  13965. * @returns the new Effect
  13966. */
  13967. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13968. if (uniformsNames === void 0) { uniformsNames = []; }
  13969. if (samplers === void 0) { samplers = []; }
  13970. if (defines === void 0) { defines = ""; }
  13971. return this.createEffect({
  13972. vertex: "particles",
  13973. fragmentElement: fragmentName
  13974. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13975. };
  13976. /**
  13977. * Directly creates a webGL program
  13978. * @param vertexCode defines the vertex shader code to use
  13979. * @param fragmentCode defines the fragment shader code to use
  13980. * @param context defines the webGL context to use (if not set, the current one will be used)
  13981. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13982. * @returns the new webGL program
  13983. */
  13984. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13985. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13986. context = context || this._gl;
  13987. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13988. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13989. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13990. };
  13991. /**
  13992. * Creates a webGL program
  13993. * @param vertexCode defines the vertex shader code to use
  13994. * @param fragmentCode defines the fragment shader code to use
  13995. * @param defines defines the string containing the defines to use to compile the shaders
  13996. * @param context defines the webGL context to use (if not set, the current one will be used)
  13997. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13998. * @returns the new webGL program
  13999. */
  14000. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14001. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14002. context = context || this._gl;
  14003. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14004. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14005. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14006. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14007. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14008. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14009. return program;
  14010. };
  14011. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14012. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14013. var shaderProgram = context.createProgram();
  14014. if (!shaderProgram) {
  14015. throw new Error("Unable to create program");
  14016. }
  14017. context.attachShader(shaderProgram, vertexShader);
  14018. context.attachShader(shaderProgram, fragmentShader);
  14019. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14020. var transformFeedback = this.createTransformFeedback();
  14021. this.bindTransformFeedback(transformFeedback);
  14022. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14023. shaderProgram.transformFeedback = transformFeedback;
  14024. }
  14025. context.linkProgram(shaderProgram);
  14026. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14027. this.bindTransformFeedback(null);
  14028. }
  14029. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14030. if (!linked) {
  14031. context.validateProgram(shaderProgram);
  14032. var error = context.getProgramInfoLog(shaderProgram);
  14033. if (error) {
  14034. throw new Error(error);
  14035. }
  14036. }
  14037. context.deleteShader(vertexShader);
  14038. context.deleteShader(fragmentShader);
  14039. return shaderProgram;
  14040. };
  14041. /**
  14042. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14043. * @param shaderProgram defines the webGL program to use
  14044. * @param uniformsNames defines the list of uniform names
  14045. * @returns an array of webGL uniform locations
  14046. */
  14047. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14048. var results = new Array();
  14049. for (var index = 0; index < uniformsNames.length; index++) {
  14050. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14051. }
  14052. return results;
  14053. };
  14054. /**
  14055. * Gets the lsit of active attributes for a given webGL program
  14056. * @param shaderProgram defines the webGL program to use
  14057. * @param attributesNames defines the list of attribute names to get
  14058. * @returns an array of indices indicating the offset of each attribute
  14059. */
  14060. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14061. var results = [];
  14062. for (var index = 0; index < attributesNames.length; index++) {
  14063. try {
  14064. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14065. }
  14066. catch (e) {
  14067. results.push(-1);
  14068. }
  14069. }
  14070. return results;
  14071. };
  14072. /**
  14073. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14074. * @param effect defines the effect to activate
  14075. */
  14076. Engine.prototype.enableEffect = function (effect) {
  14077. if (!effect) {
  14078. return;
  14079. }
  14080. // Use program
  14081. this.bindSamplers(effect);
  14082. this._currentEffect = effect;
  14083. if (effect.onBind) {
  14084. effect.onBind(effect);
  14085. }
  14086. effect.onBindObservable.notifyObservers(effect);
  14087. };
  14088. /**
  14089. * Set the value of an uniform to an array of int32
  14090. * @param uniform defines the webGL uniform location where to store the value
  14091. * @param array defines the array of int32 to store
  14092. */
  14093. Engine.prototype.setIntArray = function (uniform, array) {
  14094. if (!uniform)
  14095. return;
  14096. this._gl.uniform1iv(uniform, array);
  14097. };
  14098. /**
  14099. * Set the value of an uniform to an array of int32 (stored as vec2)
  14100. * @param uniform defines the webGL uniform location where to store the value
  14101. * @param array defines the array of int32 to store
  14102. */
  14103. Engine.prototype.setIntArray2 = function (uniform, array) {
  14104. if (!uniform || array.length % 2 !== 0)
  14105. return;
  14106. this._gl.uniform2iv(uniform, array);
  14107. };
  14108. /**
  14109. * Set the value of an uniform to an array of int32 (stored as vec3)
  14110. * @param uniform defines the webGL uniform location where to store the value
  14111. * @param array defines the array of int32 to store
  14112. */
  14113. Engine.prototype.setIntArray3 = function (uniform, array) {
  14114. if (!uniform || array.length % 3 !== 0)
  14115. return;
  14116. this._gl.uniform3iv(uniform, array);
  14117. };
  14118. /**
  14119. * Set the value of an uniform to an array of int32 (stored as vec4)
  14120. * @param uniform defines the webGL uniform location where to store the value
  14121. * @param array defines the array of int32 to store
  14122. */
  14123. Engine.prototype.setIntArray4 = function (uniform, array) {
  14124. if (!uniform || array.length % 4 !== 0)
  14125. return;
  14126. this._gl.uniform4iv(uniform, array);
  14127. };
  14128. /**
  14129. * Set the value of an uniform to an array of float32
  14130. * @param uniform defines the webGL uniform location where to store the value
  14131. * @param array defines the array of float32 to store
  14132. */
  14133. Engine.prototype.setFloatArray = function (uniform, array) {
  14134. if (!uniform)
  14135. return;
  14136. this._gl.uniform1fv(uniform, array);
  14137. };
  14138. /**
  14139. * Set the value of an uniform to an array of float32 (stored as vec2)
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param array defines the array of float32 to store
  14142. */
  14143. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14144. if (!uniform || array.length % 2 !== 0)
  14145. return;
  14146. this._gl.uniform2fv(uniform, array);
  14147. };
  14148. /**
  14149. * Set the value of an uniform to an array of float32 (stored as vec3)
  14150. * @param uniform defines the webGL uniform location where to store the value
  14151. * @param array defines the array of float32 to store
  14152. */
  14153. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14154. if (!uniform || array.length % 3 !== 0)
  14155. return;
  14156. this._gl.uniform3fv(uniform, array);
  14157. };
  14158. /**
  14159. * Set the value of an uniform to an array of float32 (stored as vec4)
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param array defines the array of float32 to store
  14162. */
  14163. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14164. if (!uniform || array.length % 4 !== 0)
  14165. return;
  14166. this._gl.uniform4fv(uniform, array);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to an array of number
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param array defines the array of number to store
  14172. */
  14173. Engine.prototype.setArray = function (uniform, array) {
  14174. if (!uniform)
  14175. return;
  14176. this._gl.uniform1fv(uniform, array);
  14177. };
  14178. /**
  14179. * Set the value of an uniform to an array of number (stored as vec2)
  14180. * @param uniform defines the webGL uniform location where to store the value
  14181. * @param array defines the array of number to store
  14182. */
  14183. Engine.prototype.setArray2 = function (uniform, array) {
  14184. if (!uniform || array.length % 2 !== 0)
  14185. return;
  14186. this._gl.uniform2fv(uniform, array);
  14187. };
  14188. /**
  14189. * Set the value of an uniform to an array of number (stored as vec3)
  14190. * @param uniform defines the webGL uniform location where to store the value
  14191. * @param array defines the array of number to store
  14192. */
  14193. Engine.prototype.setArray3 = function (uniform, array) {
  14194. if (!uniform || array.length % 3 !== 0)
  14195. return;
  14196. this._gl.uniform3fv(uniform, array);
  14197. };
  14198. /**
  14199. * Set the value of an uniform to an array of number (stored as vec4)
  14200. * @param uniform defines the webGL uniform location where to store the value
  14201. * @param array defines the array of number to store
  14202. */
  14203. Engine.prototype.setArray4 = function (uniform, array) {
  14204. if (!uniform || array.length % 4 !== 0)
  14205. return;
  14206. this._gl.uniform4fv(uniform, array);
  14207. };
  14208. /**
  14209. * Set the value of an uniform to an array of float32 (stored as matrices)
  14210. * @param uniform defines the webGL uniform location where to store the value
  14211. * @param matrices defines the array of float32 to store
  14212. */
  14213. Engine.prototype.setMatrices = function (uniform, matrices) {
  14214. if (!uniform)
  14215. return;
  14216. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to a matrix
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param matrix defines the matrix to store
  14222. */
  14223. Engine.prototype.setMatrix = function (uniform, matrix) {
  14224. if (!uniform)
  14225. return;
  14226. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14227. };
  14228. /**
  14229. * Set the value of an uniform to a matrix (3x3)
  14230. * @param uniform defines the webGL uniform location where to store the value
  14231. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14232. */
  14233. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14234. if (!uniform)
  14235. return;
  14236. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14237. };
  14238. /**
  14239. * Set the value of an uniform to a matrix (2x2)
  14240. * @param uniform defines the webGL uniform location where to store the value
  14241. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14242. */
  14243. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14244. if (!uniform)
  14245. return;
  14246. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to a number (int)
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param value defines the int number to store
  14252. */
  14253. Engine.prototype.setInt = function (uniform, value) {
  14254. if (!uniform)
  14255. return;
  14256. this._gl.uniform1i(uniform, value);
  14257. };
  14258. /**
  14259. * Set the value of an uniform to a number (float)
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param value defines the float number to store
  14262. */
  14263. Engine.prototype.setFloat = function (uniform, value) {
  14264. if (!uniform)
  14265. return;
  14266. this._gl.uniform1f(uniform, value);
  14267. };
  14268. /**
  14269. * Set the value of an uniform to a vec2
  14270. * @param uniform defines the webGL uniform location where to store the value
  14271. * @param x defines the 1st component of the value
  14272. * @param y defines the 2nd component of the value
  14273. */
  14274. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14275. if (!uniform)
  14276. return;
  14277. this._gl.uniform2f(uniform, x, y);
  14278. };
  14279. /**
  14280. * Set the value of an uniform to a vec3
  14281. * @param uniform defines the webGL uniform location where to store the value
  14282. * @param x defines the 1st component of the value
  14283. * @param y defines the 2nd component of the value
  14284. * @param z defines the 3rd component of the value
  14285. */
  14286. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14287. if (!uniform)
  14288. return;
  14289. this._gl.uniform3f(uniform, x, y, z);
  14290. };
  14291. /**
  14292. * Set the value of an uniform to a boolean
  14293. * @param uniform defines the webGL uniform location where to store the value
  14294. * @param bool defines the boolean to store
  14295. */
  14296. Engine.prototype.setBool = function (uniform, bool) {
  14297. if (!uniform)
  14298. return;
  14299. this._gl.uniform1i(uniform, bool);
  14300. };
  14301. /**
  14302. * Set the value of an uniform to a vec4
  14303. * @param uniform defines the webGL uniform location where to store the value
  14304. * @param x defines the 1st component of the value
  14305. * @param y defines the 2nd component of the value
  14306. * @param z defines the 3rd component of the value
  14307. * @param w defines the 4th component of the value
  14308. */
  14309. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14310. if (!uniform)
  14311. return;
  14312. this._gl.uniform4f(uniform, x, y, z, w);
  14313. };
  14314. /**
  14315. * Set the value of an uniform to a Color3
  14316. * @param uniform defines the webGL uniform location where to store the value
  14317. * @param color3 defines the color to store
  14318. */
  14319. Engine.prototype.setColor3 = function (uniform, color3) {
  14320. if (!uniform)
  14321. return;
  14322. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14323. };
  14324. /**
  14325. * Set the value of an uniform to a Color3 and an alpha value
  14326. * @param uniform defines the webGL uniform location where to store the value
  14327. * @param color3 defines the color to store
  14328. * @param alpha defines the alpha component to store
  14329. */
  14330. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14331. if (!uniform)
  14332. return;
  14333. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14334. };
  14335. /**
  14336. * Sets a Color4 on a uniform variable
  14337. * @param uniform defines the uniform location
  14338. * @param color4 defines the value to be set
  14339. */
  14340. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14341. if (!uniform)
  14342. return;
  14343. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14344. };
  14345. // States
  14346. /**
  14347. * Set various states to the webGL context
  14348. * @param culling defines backface culling state
  14349. * @param zOffset defines the value to apply to zOffset (0 by default)
  14350. * @param force defines if states must be applied even if cache is up to date
  14351. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14352. */
  14353. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14354. if (zOffset === void 0) { zOffset = 0; }
  14355. if (reverseSide === void 0) { reverseSide = false; }
  14356. // Culling
  14357. if (this._depthCullingState.cull !== culling || force) {
  14358. this._depthCullingState.cull = culling;
  14359. }
  14360. // Cull face
  14361. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14362. if (this._depthCullingState.cullFace !== cullFace || force) {
  14363. this._depthCullingState.cullFace = cullFace;
  14364. }
  14365. // Z offset
  14366. this.setZOffset(zOffset);
  14367. // Front face
  14368. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14369. if (this._depthCullingState.frontFace !== frontFace || force) {
  14370. this._depthCullingState.frontFace = frontFace;
  14371. }
  14372. };
  14373. /**
  14374. * Set the z offset to apply to current rendering
  14375. * @param value defines the offset to apply
  14376. */
  14377. Engine.prototype.setZOffset = function (value) {
  14378. this._depthCullingState.zOffset = value;
  14379. };
  14380. /**
  14381. * Gets the current value of the zOffset
  14382. * @returns the current zOffset state
  14383. */
  14384. Engine.prototype.getZOffset = function () {
  14385. return this._depthCullingState.zOffset;
  14386. };
  14387. /**
  14388. * Enable or disable depth buffering
  14389. * @param enable defines the state to set
  14390. */
  14391. Engine.prototype.setDepthBuffer = function (enable) {
  14392. this._depthCullingState.depthTest = enable;
  14393. };
  14394. /**
  14395. * Gets a boolean indicating if depth writing is enabled
  14396. * @returns the current depth writing state
  14397. */
  14398. Engine.prototype.getDepthWrite = function () {
  14399. return this._depthCullingState.depthMask;
  14400. };
  14401. /**
  14402. * Enable or disable depth writing
  14403. * @param enable defines the state to set
  14404. */
  14405. Engine.prototype.setDepthWrite = function (enable) {
  14406. this._depthCullingState.depthMask = enable;
  14407. };
  14408. /**
  14409. * Enable or disable color writing
  14410. * @param enable defines the state to set
  14411. */
  14412. Engine.prototype.setColorWrite = function (enable) {
  14413. this._gl.colorMask(enable, enable, enable, enable);
  14414. this._colorWrite = enable;
  14415. };
  14416. /**
  14417. * Gets a boolean indicating if color writing is enabled
  14418. * @returns the current color writing state
  14419. */
  14420. Engine.prototype.getColorWrite = function () {
  14421. return this._colorWrite;
  14422. };
  14423. /**
  14424. * Sets alpha constants used by some alpha blending modes
  14425. * @param r defines the red component
  14426. * @param g defines the green component
  14427. * @param b defines the blue component
  14428. * @param a defines the alpha component
  14429. */
  14430. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14431. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14432. };
  14433. /**
  14434. * Sets the current alpha mode
  14435. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14436. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14437. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14438. */
  14439. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14440. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14441. if (this._alphaMode === mode) {
  14442. return;
  14443. }
  14444. switch (mode) {
  14445. case Engine.ALPHA_DISABLE:
  14446. this._alphaState.alphaBlend = false;
  14447. break;
  14448. case Engine.ALPHA_PREMULTIPLIED:
  14449. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14450. this._alphaState.alphaBlend = true;
  14451. break;
  14452. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14453. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14454. this._alphaState.alphaBlend = true;
  14455. break;
  14456. case Engine.ALPHA_COMBINE:
  14457. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14458. this._alphaState.alphaBlend = true;
  14459. break;
  14460. case Engine.ALPHA_ONEONE:
  14461. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14462. this._alphaState.alphaBlend = true;
  14463. break;
  14464. case Engine.ALPHA_ADD:
  14465. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14466. this._alphaState.alphaBlend = true;
  14467. break;
  14468. case Engine.ALPHA_SUBTRACT:
  14469. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14470. this._alphaState.alphaBlend = true;
  14471. break;
  14472. case Engine.ALPHA_MULTIPLY:
  14473. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14474. this._alphaState.alphaBlend = true;
  14475. break;
  14476. case Engine.ALPHA_MAXIMIZED:
  14477. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14478. this._alphaState.alphaBlend = true;
  14479. break;
  14480. case Engine.ALPHA_INTERPOLATE:
  14481. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14482. this._alphaState.alphaBlend = true;
  14483. break;
  14484. case Engine.ALPHA_SCREENMODE:
  14485. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14486. this._alphaState.alphaBlend = true;
  14487. break;
  14488. }
  14489. if (!noDepthWriteChange) {
  14490. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14491. }
  14492. this._alphaMode = mode;
  14493. };
  14494. /**
  14495. * Gets the current alpha mode
  14496. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14497. * @returns the current alpha mode
  14498. */
  14499. Engine.prototype.getAlphaMode = function () {
  14500. return this._alphaMode;
  14501. };
  14502. // Textures
  14503. /**
  14504. * Force the entire cache to be cleared
  14505. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14506. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14507. */
  14508. Engine.prototype.wipeCaches = function (bruteForce) {
  14509. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14510. return;
  14511. }
  14512. this._currentEffect = null;
  14513. if (bruteForce) {
  14514. this.resetTextureCache();
  14515. this._currentProgram = null;
  14516. this._stencilState.reset();
  14517. this._depthCullingState.reset();
  14518. this.setDepthFunctionToLessOrEqual();
  14519. this._alphaState.reset();
  14520. }
  14521. this._resetVertexBufferBinding();
  14522. this._cachedIndexBuffer = null;
  14523. this._cachedEffectForVertexBuffers = null;
  14524. this._unbindVertexArrayObject();
  14525. this.bindIndexBuffer(null);
  14526. };
  14527. /**
  14528. * Set the compressed texture format to use, based on the formats you have, and the formats
  14529. * supported by the hardware / browser.
  14530. *
  14531. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14532. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14533. * to API arguments needed to compressed textures. This puts the burden on the container
  14534. * generator to house the arcane code for determining these for current & future formats.
  14535. *
  14536. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14537. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14538. *
  14539. * Note: The result of this call is not taken into account when a texture is base64.
  14540. *
  14541. * @param formatsAvailable defines the list of those format families you have created
  14542. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14543. *
  14544. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14545. * @returns The extension selected.
  14546. */
  14547. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14548. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14549. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14550. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14551. return this._textureFormatInUse = this._texturesSupported[i];
  14552. }
  14553. }
  14554. }
  14555. // actively set format to nothing, to allow this to be called more than once
  14556. // and possibly fail the 2nd time
  14557. this._textureFormatInUse = null;
  14558. return null;
  14559. };
  14560. /** @hidden */
  14561. Engine.prototype._createTexture = function () {
  14562. var texture = this._gl.createTexture();
  14563. if (!texture) {
  14564. throw new Error("Unable to create texture");
  14565. }
  14566. return texture;
  14567. };
  14568. /**
  14569. * Usually called from BABYLON.Texture.ts.
  14570. * Passed information to create a WebGLTexture
  14571. * @param urlArg defines a value which contains one of the following:
  14572. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14573. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14574. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14575. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14576. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14577. * @param scene needed for loading to the correct scene
  14578. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14579. * @param onLoad optional callback to be called upon successful completion
  14580. * @param onError optional callback to be called upon failure
  14581. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14582. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14583. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14584. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14585. */
  14586. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14587. var _this = this;
  14588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14589. if (onLoad === void 0) { onLoad = null; }
  14590. if (onError === void 0) { onError = null; }
  14591. if (buffer === void 0) { buffer = null; }
  14592. if (fallback === void 0) { fallback = null; }
  14593. if (format === void 0) { format = null; }
  14594. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14595. var fromData = url.substr(0, 5) === "data:";
  14596. var fromBlob = url.substr(0, 5) === "blob:";
  14597. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14598. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14599. // establish the file extension, if possible
  14600. var lastDot = url.lastIndexOf('.');
  14601. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14602. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14603. var isTGA = (extension.indexOf(".tga") === 0);
  14604. // determine if a ktx file should be substituted
  14605. var isKTX = false;
  14606. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14607. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14608. isKTX = true;
  14609. }
  14610. if (scene) {
  14611. scene._addPendingData(texture);
  14612. }
  14613. texture.url = url;
  14614. texture.generateMipMaps = !noMipmap;
  14615. texture.samplingMode = samplingMode;
  14616. texture.invertY = invertY;
  14617. if (!this._doNotHandleContextLost) {
  14618. // Keep a link to the buffer only if we plan to handle context lost
  14619. texture._buffer = buffer;
  14620. }
  14621. var onLoadObserver = null;
  14622. if (onLoad && !fallback) {
  14623. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14624. }
  14625. if (!fallback)
  14626. this._internalTexturesCache.push(texture);
  14627. var onerror = function (message, exception) {
  14628. if (scene) {
  14629. scene._removePendingData(texture);
  14630. }
  14631. if (onLoadObserver) {
  14632. texture.onLoadedObservable.remove(onLoadObserver);
  14633. }
  14634. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14635. if (isKTX) {
  14636. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14637. }
  14638. else if (BABYLON.Tools.UseFallbackTexture) {
  14639. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14640. }
  14641. if (onError) {
  14642. onError(message || "Unknown error", exception);
  14643. }
  14644. };
  14645. var callback = null;
  14646. // processing for non-image formats
  14647. if (isKTX || isTGA || isDDS) {
  14648. if (isKTX) {
  14649. callback = function (data) {
  14650. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14651. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14652. ktx.uploadLevels(_this._gl, !noMipmap);
  14653. return false;
  14654. }, samplingMode);
  14655. };
  14656. }
  14657. else if (isTGA) {
  14658. callback = function (arrayBuffer) {
  14659. var data = new Uint8Array(arrayBuffer);
  14660. var header = BABYLON.TGATools.GetTGAHeader(data);
  14661. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14662. BABYLON.TGATools.UploadContent(_this._gl, data);
  14663. return false;
  14664. }, samplingMode);
  14665. };
  14666. }
  14667. else if (isDDS) {
  14668. callback = function (data) {
  14669. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14670. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14671. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14672. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14673. return false;
  14674. }, samplingMode);
  14675. };
  14676. }
  14677. if (!buffer) {
  14678. this._loadFile(url, function (data) {
  14679. if (callback) {
  14680. callback(data);
  14681. }
  14682. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14683. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14684. });
  14685. }
  14686. else {
  14687. if (callback) {
  14688. callback(buffer);
  14689. }
  14690. }
  14691. // image format processing
  14692. }
  14693. else {
  14694. var onload = function (img) {
  14695. if (fromBlob && !_this._doNotHandleContextLost) {
  14696. // We need to store the image if we need to rebuild the texture
  14697. // in case of a webgl context lost
  14698. texture._buffer = img;
  14699. }
  14700. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14701. var gl = _this._gl;
  14702. var isPot = (img.width === potWidth && img.height === potHeight);
  14703. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14704. if (isPot) {
  14705. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14706. return false;
  14707. }
  14708. // Using shaders to rescale because canvas.drawImage is lossy
  14709. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14710. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14711. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14716. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14717. _this._releaseTexture(source);
  14718. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14719. continuationCallback();
  14720. });
  14721. return true;
  14722. }, samplingMode);
  14723. };
  14724. if (!fromData || isBase64)
  14725. if (buffer instanceof HTMLImageElement) {
  14726. onload(buffer);
  14727. }
  14728. else {
  14729. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14730. }
  14731. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14732. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14733. else
  14734. onload(buffer);
  14735. }
  14736. return texture;
  14737. };
  14738. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14739. var _this = this;
  14740. var rtt = this.createRenderTargetTexture({
  14741. width: destination.width,
  14742. height: destination.height,
  14743. }, {
  14744. generateMipMaps: false,
  14745. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14746. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14747. generateDepthBuffer: false,
  14748. generateStencilBuffer: false
  14749. });
  14750. if (!this._rescalePostProcess) {
  14751. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14752. }
  14753. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14754. _this._rescalePostProcess.onApply = function (effect) {
  14755. effect._bindTexture("textureSampler", source);
  14756. };
  14757. var hostingScene = scene;
  14758. if (!hostingScene) {
  14759. hostingScene = _this.scenes[_this.scenes.length - 1];
  14760. }
  14761. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14762. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14763. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14764. _this.unBindFramebuffer(rtt);
  14765. _this._releaseTexture(rtt);
  14766. if (onComplete) {
  14767. onComplete();
  14768. }
  14769. });
  14770. };
  14771. /**
  14772. * Update a raw texture
  14773. * @param texture defines the texture to update
  14774. * @param data defines the data to store in the texture
  14775. * @param format defines the format of the data
  14776. * @param invertY defines if data must be stored with Y axis inverted
  14777. * @param compression defines the compression used (null by default)
  14778. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14779. */
  14780. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14781. if (compression === void 0) { compression = null; }
  14782. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14783. if (!texture) {
  14784. return;
  14785. }
  14786. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14787. var internalFormat = this._getInternalFormat(format);
  14788. var textureType = this._getWebGLTextureType(type);
  14789. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14790. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14791. if (!this._doNotHandleContextLost) {
  14792. texture._bufferView = data;
  14793. texture.format = format;
  14794. texture.type = type;
  14795. texture.invertY = invertY;
  14796. texture._compression = compression;
  14797. }
  14798. if (texture.width % 4 !== 0) {
  14799. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14800. }
  14801. if (compression && data) {
  14802. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14803. }
  14804. else {
  14805. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14806. }
  14807. if (texture.generateMipMaps) {
  14808. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14809. }
  14810. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14811. // this.resetTextureCache();
  14812. texture.isReady = true;
  14813. };
  14814. /**
  14815. * Creates a raw texture
  14816. * @param data defines the data to store in the texture
  14817. * @param width defines the width of the texture
  14818. * @param height defines the height of the texture
  14819. * @param format defines the format of the data
  14820. * @param generateMipMaps defines if the engine should generate the mip levels
  14821. * @param invertY defines if data must be stored with Y axis inverted
  14822. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14823. * @param compression defines the compression used (null by default)
  14824. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14825. * @returns the raw texture inside an InternalTexture
  14826. */
  14827. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14828. if (compression === void 0) { compression = null; }
  14829. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14830. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14831. texture.baseWidth = width;
  14832. texture.baseHeight = height;
  14833. texture.width = width;
  14834. texture.height = height;
  14835. texture.format = format;
  14836. texture.generateMipMaps = generateMipMaps;
  14837. texture.samplingMode = samplingMode;
  14838. texture.invertY = invertY;
  14839. texture._compression = compression;
  14840. texture.type = type;
  14841. if (!this._doNotHandleContextLost) {
  14842. texture._bufferView = data;
  14843. }
  14844. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14845. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14846. // Filters
  14847. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14848. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14849. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14850. if (generateMipMaps) {
  14851. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14852. }
  14853. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14854. this._internalTexturesCache.push(texture);
  14855. return texture;
  14856. };
  14857. /**
  14858. * Creates a dynamic texture
  14859. * @param width defines the width of the texture
  14860. * @param height defines the height of the texture
  14861. * @param generateMipMaps defines if the engine should generate the mip levels
  14862. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14863. * @returns the dynamic texture inside an InternalTexture
  14864. */
  14865. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14866. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14867. texture.baseWidth = width;
  14868. texture.baseHeight = height;
  14869. if (generateMipMaps) {
  14870. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14871. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14872. }
  14873. // this.resetTextureCache();
  14874. texture.width = width;
  14875. texture.height = height;
  14876. texture.isReady = false;
  14877. texture.generateMipMaps = generateMipMaps;
  14878. texture.samplingMode = samplingMode;
  14879. this.updateTextureSamplingMode(samplingMode, texture);
  14880. this._internalTexturesCache.push(texture);
  14881. return texture;
  14882. };
  14883. /**
  14884. * Update the sampling mode of a given texture
  14885. * @param samplingMode defines the required sampling mode
  14886. * @param texture defines the texture to update
  14887. */
  14888. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14889. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14890. if (texture.isCube) {
  14891. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14892. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14893. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14894. }
  14895. else if (texture.is3D) {
  14896. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14897. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14898. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14899. }
  14900. else {
  14901. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14902. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14903. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14904. }
  14905. texture.samplingMode = samplingMode;
  14906. };
  14907. /**
  14908. * Update the content of a dynamic texture
  14909. * @param texture defines the texture to update
  14910. * @param canvas defines the canvas containing the source
  14911. * @param invertY defines if data must be stored with Y axis inverted
  14912. * @param premulAlpha defines if alpha is stored as premultiplied
  14913. * @param format defines the format of the data
  14914. */
  14915. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14916. if (premulAlpha === void 0) { premulAlpha = false; }
  14917. if (!texture) {
  14918. return;
  14919. }
  14920. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14921. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14922. if (premulAlpha) {
  14923. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14924. }
  14925. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14926. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14927. if (texture.generateMipMaps) {
  14928. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14929. }
  14930. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14931. if (premulAlpha) {
  14932. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14933. }
  14934. texture.isReady = true;
  14935. };
  14936. /**
  14937. * Update a video texture
  14938. * @param texture defines the texture to update
  14939. * @param video defines the video element to use
  14940. * @param invertY defines if data must be stored with Y axis inverted
  14941. */
  14942. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14943. if (!texture || texture._isDisabled) {
  14944. return;
  14945. }
  14946. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14947. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14948. try {
  14949. // Testing video texture support
  14950. if (this._videoTextureSupported === undefined) {
  14951. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14952. if (this._gl.getError() !== 0) {
  14953. this._videoTextureSupported = false;
  14954. }
  14955. else {
  14956. this._videoTextureSupported = true;
  14957. }
  14958. }
  14959. // Copy video through the current working canvas if video texture is not supported
  14960. if (!this._videoTextureSupported) {
  14961. if (!texture._workingCanvas) {
  14962. texture._workingCanvas = document.createElement("canvas");
  14963. var context = texture._workingCanvas.getContext("2d");
  14964. if (!context) {
  14965. throw new Error("Unable to get 2d context");
  14966. }
  14967. texture._workingContext = context;
  14968. texture._workingCanvas.width = texture.width;
  14969. texture._workingCanvas.height = texture.height;
  14970. }
  14971. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14972. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14973. }
  14974. else {
  14975. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14976. }
  14977. if (texture.generateMipMaps) {
  14978. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14979. }
  14980. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14981. // this.resetTextureCache();
  14982. texture.isReady = true;
  14983. }
  14984. catch (ex) {
  14985. // Something unexpected
  14986. // Let's disable the texture
  14987. texture._isDisabled = true;
  14988. }
  14989. };
  14990. /**
  14991. * Updates a depth texture Comparison Mode and Function.
  14992. * If the comparison Function is equal to 0, the mode will be set to none.
  14993. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14994. * @param texture The texture to set the comparison function for
  14995. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14996. */
  14997. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14998. if (this.webGLVersion === 1) {
  14999. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15000. return;
  15001. }
  15002. var gl = this._gl;
  15003. if (texture.isCube) {
  15004. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15005. if (comparisonFunction === 0) {
  15006. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15008. }
  15009. else {
  15010. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15012. }
  15013. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15014. }
  15015. else {
  15016. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15017. if (comparisonFunction === 0) {
  15018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15020. }
  15021. else {
  15022. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15023. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15024. }
  15025. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15026. }
  15027. texture._comparisonFunction = comparisonFunction;
  15028. };
  15029. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15030. var width = size.width || size;
  15031. var height = size.height || size;
  15032. internalTexture.baseWidth = width;
  15033. internalTexture.baseHeight = height;
  15034. internalTexture.width = width;
  15035. internalTexture.height = height;
  15036. internalTexture.isReady = true;
  15037. internalTexture.samples = 1;
  15038. internalTexture.generateMipMaps = false;
  15039. internalTexture._generateDepthBuffer = true;
  15040. internalTexture._generateStencilBuffer = generateStencil;
  15041. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15042. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15043. internalTexture._comparisonFunction = comparisonFunction;
  15044. var gl = this._gl;
  15045. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15046. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15047. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15048. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15049. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15050. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15051. if (comparisonFunction === 0) {
  15052. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15053. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15054. }
  15055. else {
  15056. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15057. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15058. }
  15059. };
  15060. /**
  15061. * Creates a depth stencil texture.
  15062. * This is only available in WebGL 2 or with the depth texture extension available.
  15063. * @param size The size of face edge in the texture.
  15064. * @param options The options defining the texture.
  15065. * @returns The texture
  15066. */
  15067. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15068. if (options.isCube) {
  15069. var width = size.width || size;
  15070. return this._createDepthStencilCubeTexture(width, options);
  15071. }
  15072. else {
  15073. return this._createDepthStencilTexture(size, options);
  15074. }
  15075. };
  15076. /**
  15077. * Creates a depth stencil texture.
  15078. * This is only available in WebGL 2 or with the depth texture extension available.
  15079. * @param size The size of face edge in the texture.
  15080. * @param options The options defining the texture.
  15081. * @returns The texture
  15082. */
  15083. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15084. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15085. if (!this._caps.depthTextureExtension) {
  15086. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15087. return internalTexture;
  15088. }
  15089. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15090. var gl = this._gl;
  15091. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15092. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15093. if (this.webGLVersion > 1) {
  15094. if (internalOptions.generateStencil) {
  15095. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15096. }
  15097. else {
  15098. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15099. }
  15100. }
  15101. else {
  15102. if (internalOptions.generateStencil) {
  15103. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15104. }
  15105. else {
  15106. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15107. }
  15108. }
  15109. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15110. return internalTexture;
  15111. };
  15112. /**
  15113. * Creates a depth stencil cube texture.
  15114. * This is only available in WebGL 2.
  15115. * @param size The size of face edge in the cube texture.
  15116. * @param options The options defining the cube texture.
  15117. * @returns The cube texture
  15118. */
  15119. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15120. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15121. internalTexture.isCube = true;
  15122. if (this.webGLVersion === 1) {
  15123. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15124. return internalTexture;
  15125. }
  15126. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15127. var gl = this._gl;
  15128. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15129. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15130. // Create the depth/stencil buffer
  15131. for (var face = 0; face < 6; face++) {
  15132. if (internalOptions.generateStencil) {
  15133. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15134. }
  15135. else {
  15136. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15137. }
  15138. }
  15139. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15140. return internalTexture;
  15141. };
  15142. /**
  15143. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15144. * @param renderTarget The render target to set the frame buffer for
  15145. */
  15146. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15147. // Create the framebuffer
  15148. var internalTexture = renderTarget.getInternalTexture();
  15149. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15150. return;
  15151. }
  15152. var gl = this._gl;
  15153. var depthStencilTexture = renderTarget.depthStencilTexture;
  15154. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15155. if (depthStencilTexture.isCube) {
  15156. if (depthStencilTexture._generateStencilBuffer) {
  15157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15158. }
  15159. else {
  15160. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15161. }
  15162. }
  15163. else {
  15164. if (depthStencilTexture._generateStencilBuffer) {
  15165. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15166. }
  15167. else {
  15168. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15169. }
  15170. }
  15171. this.bindUnboundFramebuffer(null);
  15172. };
  15173. /**
  15174. * Creates a new render target texture
  15175. * @param size defines the size of the texture
  15176. * @param options defines the options used to create the texture
  15177. * @returns a new render target texture stored in an InternalTexture
  15178. */
  15179. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15180. var fullOptions = new RenderTargetCreationOptions();
  15181. if (options !== undefined && typeof options === "object") {
  15182. fullOptions.generateMipMaps = options.generateMipMaps;
  15183. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15184. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15185. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15186. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15187. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15188. }
  15189. else {
  15190. fullOptions.generateMipMaps = options;
  15191. fullOptions.generateDepthBuffer = true;
  15192. fullOptions.generateStencilBuffer = false;
  15193. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15194. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15195. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15196. }
  15197. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15198. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15199. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15200. }
  15201. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15202. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15203. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15204. }
  15205. var gl = this._gl;
  15206. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15207. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15208. var width = size.width || size;
  15209. var height = size.height || size;
  15210. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15211. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15212. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15213. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15214. }
  15215. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15219. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15220. // Create the framebuffer
  15221. var framebuffer = gl.createFramebuffer();
  15222. this.bindUnboundFramebuffer(framebuffer);
  15223. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15224. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15225. if (fullOptions.generateMipMaps) {
  15226. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15227. }
  15228. // Unbind
  15229. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15230. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15231. this.bindUnboundFramebuffer(null);
  15232. texture._framebuffer = framebuffer;
  15233. texture.baseWidth = width;
  15234. texture.baseHeight = height;
  15235. texture.width = width;
  15236. texture.height = height;
  15237. texture.isReady = true;
  15238. texture.samples = 1;
  15239. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15240. texture.samplingMode = fullOptions.samplingMode;
  15241. texture.type = fullOptions.type;
  15242. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15243. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15244. // this.resetTextureCache();
  15245. this._internalTexturesCache.push(texture);
  15246. return texture;
  15247. };
  15248. /**
  15249. * Create a multi render target texture
  15250. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15251. * @param size defines the size of the texture
  15252. * @param options defines the creation options
  15253. * @returns the cube texture as an InternalTexture
  15254. */
  15255. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15256. var generateMipMaps = false;
  15257. var generateDepthBuffer = true;
  15258. var generateStencilBuffer = false;
  15259. var generateDepthTexture = false;
  15260. var textureCount = 1;
  15261. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15262. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15263. var types = new Array();
  15264. var samplingModes = new Array();
  15265. if (options !== undefined) {
  15266. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15267. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15268. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15269. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15270. textureCount = options.textureCount || 1;
  15271. if (options.types) {
  15272. types = options.types;
  15273. }
  15274. if (options.samplingModes) {
  15275. samplingModes = options.samplingModes;
  15276. }
  15277. }
  15278. var gl = this._gl;
  15279. // Create the framebuffer
  15280. var framebuffer = gl.createFramebuffer();
  15281. this.bindUnboundFramebuffer(framebuffer);
  15282. var width = size.width || size;
  15283. var height = size.height || size;
  15284. var textures = [];
  15285. var attachments = [];
  15286. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15287. for (var i = 0; i < textureCount; i++) {
  15288. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15289. var type = types[i] || defaultType;
  15290. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15291. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15292. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15293. }
  15294. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15295. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15296. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15297. }
  15298. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15299. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15300. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15301. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15302. }
  15303. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15304. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15305. textures.push(texture);
  15306. attachments.push(attachment);
  15307. gl.activeTexture(gl["TEXTURE" + i]);
  15308. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15311. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15312. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15313. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15314. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15315. if (generateMipMaps) {
  15316. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15317. }
  15318. // Unbind
  15319. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15320. texture._framebuffer = framebuffer;
  15321. texture._depthStencilBuffer = depthStencilBuffer;
  15322. texture.baseWidth = width;
  15323. texture.baseHeight = height;
  15324. texture.width = width;
  15325. texture.height = height;
  15326. texture.isReady = true;
  15327. texture.samples = 1;
  15328. texture.generateMipMaps = generateMipMaps;
  15329. texture.samplingMode = samplingMode;
  15330. texture.type = type;
  15331. texture._generateDepthBuffer = generateDepthBuffer;
  15332. texture._generateStencilBuffer = generateStencilBuffer;
  15333. texture._attachments = attachments;
  15334. this._internalTexturesCache.push(texture);
  15335. }
  15336. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15337. // Depth texture
  15338. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15339. gl.activeTexture(gl.TEXTURE0);
  15340. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15343. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15344. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15345. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  15346. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15347. depthTexture._framebuffer = framebuffer;
  15348. depthTexture.baseWidth = width;
  15349. depthTexture.baseHeight = height;
  15350. depthTexture.width = width;
  15351. depthTexture.height = height;
  15352. depthTexture.isReady = true;
  15353. depthTexture.samples = 1;
  15354. depthTexture.generateMipMaps = generateMipMaps;
  15355. depthTexture.samplingMode = gl.NEAREST;
  15356. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15357. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15358. textures.push(depthTexture);
  15359. this._internalTexturesCache.push(depthTexture);
  15360. }
  15361. gl.drawBuffers(attachments);
  15362. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15363. this.bindUnboundFramebuffer(null);
  15364. this.resetTextureCache();
  15365. return textures;
  15366. };
  15367. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15368. if (samples === void 0) { samples = 1; }
  15369. var depthStencilBuffer = null;
  15370. var gl = this._gl;
  15371. // Create the depth/stencil buffer
  15372. if (generateStencilBuffer) {
  15373. depthStencilBuffer = gl.createRenderbuffer();
  15374. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15375. if (samples > 1) {
  15376. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15377. }
  15378. else {
  15379. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15380. }
  15381. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15382. }
  15383. else if (generateDepthBuffer) {
  15384. depthStencilBuffer = gl.createRenderbuffer();
  15385. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15386. if (samples > 1) {
  15387. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15388. }
  15389. else {
  15390. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15391. }
  15392. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15393. }
  15394. return depthStencilBuffer;
  15395. };
  15396. /**
  15397. * Updates the sample count of a render target texture
  15398. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15399. * @param texture defines the texture to update
  15400. * @param samples defines the sample count to set
  15401. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15402. */
  15403. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15404. if (this.webGLVersion < 2 || !texture) {
  15405. return 1;
  15406. }
  15407. if (texture.samples === samples) {
  15408. return samples;
  15409. }
  15410. var gl = this._gl;
  15411. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15412. // Dispose previous render buffers
  15413. if (texture._depthStencilBuffer) {
  15414. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15415. texture._depthStencilBuffer = null;
  15416. }
  15417. if (texture._MSAAFramebuffer) {
  15418. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15419. texture._MSAAFramebuffer = null;
  15420. }
  15421. if (texture._MSAARenderBuffer) {
  15422. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15423. texture._MSAARenderBuffer = null;
  15424. }
  15425. if (samples > 1) {
  15426. var framebuffer = gl.createFramebuffer();
  15427. if (!framebuffer) {
  15428. throw new Error("Unable to create multi sampled framebuffer");
  15429. }
  15430. texture._MSAAFramebuffer = framebuffer;
  15431. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15432. var colorRenderbuffer = gl.createRenderbuffer();
  15433. if (!colorRenderbuffer) {
  15434. throw new Error("Unable to create multi sampled framebuffer");
  15435. }
  15436. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15437. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15438. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15439. texture._MSAARenderBuffer = colorRenderbuffer;
  15440. }
  15441. else {
  15442. this.bindUnboundFramebuffer(texture._framebuffer);
  15443. }
  15444. texture.samples = samples;
  15445. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15446. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15447. this.bindUnboundFramebuffer(null);
  15448. return samples;
  15449. };
  15450. /**
  15451. * Update the sample count for a given multiple render target texture
  15452. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15453. * @param textures defines the textures to update
  15454. * @param samples defines the sample count to set
  15455. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15456. */
  15457. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15458. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15459. return 1;
  15460. }
  15461. if (textures[0].samples === samples) {
  15462. return samples;
  15463. }
  15464. var gl = this._gl;
  15465. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15466. // Dispose previous render buffers
  15467. if (textures[0]._depthStencilBuffer) {
  15468. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15469. textures[0]._depthStencilBuffer = null;
  15470. }
  15471. if (textures[0]._MSAAFramebuffer) {
  15472. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15473. textures[0]._MSAAFramebuffer = null;
  15474. }
  15475. for (var i = 0; i < textures.length; i++) {
  15476. if (textures[i]._MSAARenderBuffer) {
  15477. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15478. textures[i]._MSAARenderBuffer = null;
  15479. }
  15480. }
  15481. if (samples > 1) {
  15482. var framebuffer = gl.createFramebuffer();
  15483. if (!framebuffer) {
  15484. throw new Error("Unable to create multi sampled framebuffer");
  15485. }
  15486. this.bindUnboundFramebuffer(framebuffer);
  15487. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15488. var attachments = [];
  15489. for (var i = 0; i < textures.length; i++) {
  15490. var texture = textures[i];
  15491. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15492. var colorRenderbuffer = gl.createRenderbuffer();
  15493. if (!colorRenderbuffer) {
  15494. throw new Error("Unable to create multi sampled framebuffer");
  15495. }
  15496. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15497. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15498. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15499. texture._MSAAFramebuffer = framebuffer;
  15500. texture._MSAARenderBuffer = colorRenderbuffer;
  15501. texture.samples = samples;
  15502. texture._depthStencilBuffer = depthStencilBuffer;
  15503. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15504. attachments.push(attachment);
  15505. }
  15506. gl.drawBuffers(attachments);
  15507. }
  15508. else {
  15509. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15510. }
  15511. this.bindUnboundFramebuffer(null);
  15512. return samples;
  15513. };
  15514. /** @hidden */
  15515. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15516. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15517. };
  15518. /** @hidden */
  15519. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15520. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15521. };
  15522. /**
  15523. * Creates a new render target cube texture
  15524. * @param size defines the size of the texture
  15525. * @param options defines the options used to create the texture
  15526. * @returns a new render target cube texture stored in an InternalTexture
  15527. */
  15528. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15529. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15530. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15531. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15532. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15533. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15534. }
  15535. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15536. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15537. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15538. }
  15539. var gl = this._gl;
  15540. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15541. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15542. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15543. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15544. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15545. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15546. }
  15547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15551. for (var face = 0; face < 6; face++) {
  15552. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15553. }
  15554. // Create the framebuffer
  15555. var framebuffer = gl.createFramebuffer();
  15556. this.bindUnboundFramebuffer(framebuffer);
  15557. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15558. // MipMaps
  15559. if (fullOptions.generateMipMaps) {
  15560. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15561. }
  15562. // Unbind
  15563. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15564. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15565. this.bindUnboundFramebuffer(null);
  15566. texture._framebuffer = framebuffer;
  15567. texture.width = size;
  15568. texture.height = size;
  15569. texture.isReady = true;
  15570. texture.isCube = true;
  15571. texture.samples = 1;
  15572. texture.generateMipMaps = fullOptions.generateMipMaps;
  15573. texture.samplingMode = fullOptions.samplingMode;
  15574. texture.type = fullOptions.type;
  15575. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15576. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15577. this._internalTexturesCache.push(texture);
  15578. return texture;
  15579. };
  15580. /**
  15581. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15582. * @param rootUrl defines the url where the file to load is located
  15583. * @param scene defines the current scene
  15584. * @param scale defines scale to apply to the mip map selection
  15585. * @param offset defines offset to apply to the mip map selection
  15586. * @param onLoad defines an optional callback raised when the texture is loaded
  15587. * @param onError defines an optional callback raised if there is an issue to load the texture
  15588. * @param format defines the format of the data
  15589. * @param forcedExtension defines the extension to use to pick the right loader
  15590. * @returns the cube texture as an InternalTexture
  15591. */
  15592. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15593. var _this = this;
  15594. if (onLoad === void 0) { onLoad = null; }
  15595. if (onError === void 0) { onError = null; }
  15596. if (forcedExtension === void 0) { forcedExtension = null; }
  15597. var callback = function (loadData) {
  15598. if (!loadData) {
  15599. if (onLoad) {
  15600. onLoad(null);
  15601. }
  15602. return;
  15603. }
  15604. var texture = loadData.texture;
  15605. if (loadData.info.sphericalPolynomial) {
  15606. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15607. }
  15608. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15609. texture._lodGenerationScale = scale;
  15610. texture._lodGenerationOffset = offset;
  15611. if (_this._caps.textureLOD) {
  15612. // Do not add extra process if texture lod is supported.
  15613. if (onLoad) {
  15614. onLoad(texture);
  15615. }
  15616. return;
  15617. }
  15618. var mipSlices = 3;
  15619. var gl = _this._gl;
  15620. var width = loadData.width;
  15621. if (!width) {
  15622. return;
  15623. }
  15624. var textures = [];
  15625. for (var i = 0; i < mipSlices; i++) {
  15626. //compute LOD from even spacing in smoothness (matching shader calculation)
  15627. var smoothness = i / (mipSlices - 1);
  15628. var roughness = 1 - smoothness;
  15629. var minLODIndex = offset; // roughness = 0
  15630. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15631. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15632. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15633. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15634. glTextureFromLod.isCube = true;
  15635. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15640. if (loadData.isDDS) {
  15641. var info = loadData.info;
  15642. var data = loadData.data;
  15643. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15644. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15645. }
  15646. else {
  15647. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15648. }
  15649. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15650. // Wrap in a base texture for easy binding.
  15651. var lodTexture = new BABYLON.BaseTexture(scene);
  15652. lodTexture.isCube = true;
  15653. lodTexture._texture = glTextureFromLod;
  15654. glTextureFromLod.isReady = true;
  15655. textures.push(lodTexture);
  15656. }
  15657. texture._lodTextureHigh = textures[2];
  15658. texture._lodTextureMid = textures[1];
  15659. texture._lodTextureLow = textures[0];
  15660. if (onLoad) {
  15661. onLoad(texture);
  15662. }
  15663. };
  15664. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15665. };
  15666. /**
  15667. * Creates a cube texture
  15668. * @param rootUrl defines the url where the files to load is located
  15669. * @param scene defines the current scene
  15670. * @param files defines the list of files to load (1 per face)
  15671. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15672. * @param onLoad defines an optional callback raised when the texture is loaded
  15673. * @param onError defines an optional callback raised if there is an issue to load the texture
  15674. * @param format defines the format of the data
  15675. * @param forcedExtension defines the extension to use to pick the right loader
  15676. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15677. * @returns the cube texture as an InternalTexture
  15678. */
  15679. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15680. var _this = this;
  15681. if (onLoad === void 0) { onLoad = null; }
  15682. if (onError === void 0) { onError = null; }
  15683. if (forcedExtension === void 0) { forcedExtension = null; }
  15684. if (createPolynomials === void 0) { createPolynomials = false; }
  15685. var gl = this._gl;
  15686. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15687. texture.isCube = true;
  15688. texture.url = rootUrl;
  15689. texture.generateMipMaps = !noMipmap;
  15690. if (!this._doNotHandleContextLost) {
  15691. texture._extension = forcedExtension;
  15692. texture._files = files;
  15693. }
  15694. var isKTX = false;
  15695. var isDDS = false;
  15696. var lastDot = rootUrl.lastIndexOf('.');
  15697. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15698. if (this._textureFormatInUse) {
  15699. extension = this._textureFormatInUse;
  15700. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15701. isKTX = true;
  15702. }
  15703. else {
  15704. isDDS = (extension === ".dds");
  15705. }
  15706. var onerror = function (request, exception) {
  15707. if (onError && request) {
  15708. onError(request.status + " " + request.statusText, exception);
  15709. }
  15710. };
  15711. if (isKTX) {
  15712. this._loadFile(rootUrl, function (data) {
  15713. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15714. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15715. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15716. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15717. ktx.uploadLevels(_this._gl, !noMipmap);
  15718. _this.setCubeMapTextureParams(gl, loadMipmap);
  15719. texture.width = ktx.pixelWidth;
  15720. texture.height = ktx.pixelHeight;
  15721. texture.isReady = true;
  15722. }, undefined, undefined, true, onerror);
  15723. }
  15724. else if (isDDS) {
  15725. if (files && files.length === 6) {
  15726. this._cascadeLoadFiles(scene, function (imgs) {
  15727. var info;
  15728. var loadMipmap = false;
  15729. var width = 0;
  15730. for (var index = 0; index < imgs.length; index++) {
  15731. var data = imgs[index];
  15732. info = BABYLON.DDSTools.GetDDSInfo(data);
  15733. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15734. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15735. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15736. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15737. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15738. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15739. }
  15740. texture.width = info.width;
  15741. texture.height = info.height;
  15742. texture.type = info.textureType;
  15743. width = info.width;
  15744. }
  15745. _this.setCubeMapTextureParams(gl, loadMipmap);
  15746. texture.isReady = true;
  15747. if (onLoad) {
  15748. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15749. }
  15750. }, files, onError);
  15751. }
  15752. else {
  15753. this._loadFile(rootUrl, function (data) {
  15754. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15755. if (createPolynomials) {
  15756. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15757. }
  15758. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15759. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15760. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15761. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15762. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15763. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15764. }
  15765. _this.setCubeMapTextureParams(gl, loadMipmap);
  15766. texture.width = info.width;
  15767. texture.height = info.height;
  15768. texture.isReady = true;
  15769. texture.type = info.textureType;
  15770. if (onLoad) {
  15771. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15772. }
  15773. }, undefined, undefined, true, onerror);
  15774. }
  15775. }
  15776. else {
  15777. if (!files) {
  15778. throw new Error("Cannot load cubemap because files were not defined");
  15779. }
  15780. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15781. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15782. var height = width;
  15783. _this._prepareWorkingCanvas();
  15784. if (!_this._workingCanvas || !_this._workingContext) {
  15785. return;
  15786. }
  15787. _this._workingCanvas.width = width;
  15788. _this._workingCanvas.height = height;
  15789. var faces = [
  15790. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15791. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15792. ];
  15793. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15794. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15795. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15796. for (var index = 0; index < faces.length; index++) {
  15797. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15798. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15799. }
  15800. if (!noMipmap) {
  15801. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15802. }
  15803. _this.setCubeMapTextureParams(gl, !noMipmap);
  15804. texture.width = width;
  15805. texture.height = height;
  15806. texture.isReady = true;
  15807. if (format) {
  15808. texture.format = format;
  15809. }
  15810. texture.onLoadedObservable.notifyObservers(texture);
  15811. texture.onLoadedObservable.clear();
  15812. if (onLoad) {
  15813. onLoad();
  15814. }
  15815. }, files, onError);
  15816. }
  15817. this._internalTexturesCache.push(texture);
  15818. return texture;
  15819. };
  15820. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15825. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15826. // this.resetTextureCache();
  15827. };
  15828. /**
  15829. * Update a raw cube texture
  15830. * @param texture defines the texture to udpdate
  15831. * @param data defines the data to store
  15832. * @param format defines the data format
  15833. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15834. * @param invertY defines if data must be stored with Y axis inverted
  15835. * @param compression defines the compression used (null by default)
  15836. * @param level defines which level of the texture to update
  15837. */
  15838. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15839. if (compression === void 0) { compression = null; }
  15840. if (level === void 0) { level = 0; }
  15841. texture._bufferViewArray = data;
  15842. texture.format = format;
  15843. texture.type = type;
  15844. texture.invertY = invertY;
  15845. texture._compression = compression;
  15846. var gl = this._gl;
  15847. var textureType = this._getWebGLTextureType(type);
  15848. var internalFormat = this._getInternalFormat(format);
  15849. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15850. var needConversion = false;
  15851. if (internalFormat === gl.RGB) {
  15852. internalFormat = gl.RGBA;
  15853. needConversion = true;
  15854. }
  15855. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15856. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15857. if (texture.width % 4 !== 0) {
  15858. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15859. }
  15860. // Data are known to be in +X +Y +Z -X -Y -Z
  15861. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15862. var faceData = data[faceIndex];
  15863. if (compression) {
  15864. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15865. }
  15866. else {
  15867. if (needConversion) {
  15868. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15869. }
  15870. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15871. }
  15872. }
  15873. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15874. if (isPot && texture.generateMipMaps && level === 0) {
  15875. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15876. }
  15877. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15878. // this.resetTextureCache();
  15879. texture.isReady = true;
  15880. };
  15881. /**
  15882. * Creates a new raw cube texture
  15883. * @param data defines the array of data to use to create each face
  15884. * @param size defines the size of the textures
  15885. * @param format defines the format of the data
  15886. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15887. * @param generateMipMaps defines if the engine should generate the mip levels
  15888. * @param invertY defines if data must be stored with Y axis inverted
  15889. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15890. * @param compression defines the compression used (null by default)
  15891. * @returns the cube texture as an InternalTexture
  15892. */
  15893. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15894. if (compression === void 0) { compression = null; }
  15895. var gl = this._gl;
  15896. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15897. texture.isCube = true;
  15898. texture.generateMipMaps = generateMipMaps;
  15899. texture.format = format;
  15900. texture.type = type;
  15901. if (!this._doNotHandleContextLost) {
  15902. texture._bufferViewArray = data;
  15903. }
  15904. var textureType = this._getWebGLTextureType(type);
  15905. var internalFormat = this._getInternalFormat(format);
  15906. if (internalFormat === gl.RGB) {
  15907. internalFormat = gl.RGBA;
  15908. }
  15909. var width = size;
  15910. var height = width;
  15911. texture.width = width;
  15912. texture.height = height;
  15913. // Double check on POT to generate Mips.
  15914. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15915. if (!isPot) {
  15916. generateMipMaps = false;
  15917. }
  15918. // Upload data if needed. The texture won't be ready until then.
  15919. if (data) {
  15920. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15921. }
  15922. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15923. // Filters
  15924. if (data && generateMipMaps) {
  15925. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15926. }
  15927. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15930. }
  15931. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15934. }
  15935. else {
  15936. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15939. }
  15940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15942. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15943. return texture;
  15944. };
  15945. /**
  15946. * Creates a new raw cube texture from a specified url
  15947. * @param url defines the url where the data is located
  15948. * @param scene defines the current scene
  15949. * @param size defines the size of the textures
  15950. * @param format defines the format of the data
  15951. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15952. * @param noMipmap defines if the engine should avoid generating the mip levels
  15953. * @param callback defines a callback used to extract texture data from loaded data
  15954. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15955. * @param onLoad defines a callback called when texture is loaded
  15956. * @param onError defines a callback called if there is an error
  15957. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15958. * @param invertY defines if data must be stored with Y axis inverted
  15959. * @returns the cube texture as an InternalTexture
  15960. */
  15961. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15962. var _this = this;
  15963. if (onLoad === void 0) { onLoad = null; }
  15964. if (onError === void 0) { onError = null; }
  15965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15966. if (invertY === void 0) { invertY = false; }
  15967. var gl = this._gl;
  15968. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15969. scene._addPendingData(texture);
  15970. texture.url = url;
  15971. this._internalTexturesCache.push(texture);
  15972. var onerror = function (request, exception) {
  15973. scene._removePendingData(texture);
  15974. if (onError && request) {
  15975. onError(request.status + " " + request.statusText, exception);
  15976. }
  15977. };
  15978. var internalCallback = function (data) {
  15979. var width = texture.width;
  15980. var faceDataArrays = callback(data);
  15981. if (!faceDataArrays) {
  15982. return;
  15983. }
  15984. if (mipmapGenerator) {
  15985. var textureType = _this._getWebGLTextureType(type);
  15986. var internalFormat = _this._getInternalFormat(format);
  15987. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15988. var needConversion = false;
  15989. if (internalFormat === gl.RGB) {
  15990. internalFormat = gl.RGBA;
  15991. needConversion = true;
  15992. }
  15993. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15994. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15995. var mipData = mipmapGenerator(faceDataArrays);
  15996. for (var level = 0; level < mipData.length; level++) {
  15997. var mipSize = width >> level;
  15998. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15999. var mipFaceData = mipData[level][faceIndex];
  16000. if (needConversion) {
  16001. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16002. }
  16003. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16004. }
  16005. }
  16006. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16007. }
  16008. else {
  16009. texture.generateMipMaps = !noMipmap;
  16010. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16011. }
  16012. texture.isReady = true;
  16013. // this.resetTextureCache();
  16014. scene._removePendingData(texture);
  16015. if (onLoad) {
  16016. onLoad();
  16017. }
  16018. };
  16019. this._loadFile(url, function (data) {
  16020. internalCallback(data);
  16021. }, undefined, scene.database, true, onerror);
  16022. return texture;
  16023. };
  16024. ;
  16025. /**
  16026. * Update a raw 3D texture
  16027. * @param texture defines the texture to update
  16028. * @param data defines the data to store
  16029. * @param format defines the data format
  16030. * @param invertY defines if data must be stored with Y axis inverted
  16031. * @param compression defines the used compression (can be null)
  16032. */
  16033. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  16034. if (compression === void 0) { compression = null; }
  16035. var internalFormat = this._getInternalFormat(format);
  16036. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16037. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16038. if (!this._doNotHandleContextLost) {
  16039. texture._bufferView = data;
  16040. texture.format = format;
  16041. texture.invertY = invertY;
  16042. texture._compression = compression;
  16043. }
  16044. if (texture.width % 4 !== 0) {
  16045. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16046. }
  16047. if (compression && data) {
  16048. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16049. }
  16050. else {
  16051. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16052. }
  16053. if (texture.generateMipMaps) {
  16054. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16055. }
  16056. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16057. // this.resetTextureCache();
  16058. texture.isReady = true;
  16059. };
  16060. /**
  16061. * Creates a new raw 3D texture
  16062. * @param data defines the data used to create the texture
  16063. * @param width defines the width of the texture
  16064. * @param height defines the height of the texture
  16065. * @param depth defines the depth of the texture
  16066. * @param format defines the format of the texture
  16067. * @param generateMipMaps defines if the engine must generate mip levels
  16068. * @param invertY defines if data must be stored with Y axis inverted
  16069. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16070. * @param compression defines the compressed used (can be null)
  16071. * @returns a new raw 3D texture (stored in an InternalTexture)
  16072. */
  16073. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16074. if (compression === void 0) { compression = null; }
  16075. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16076. texture.baseWidth = width;
  16077. texture.baseHeight = height;
  16078. texture.baseDepth = depth;
  16079. texture.width = width;
  16080. texture.height = height;
  16081. texture.depth = depth;
  16082. texture.format = format;
  16083. texture.generateMipMaps = generateMipMaps;
  16084. texture.samplingMode = samplingMode;
  16085. texture.is3D = true;
  16086. if (!this._doNotHandleContextLost) {
  16087. texture._bufferView = data;
  16088. }
  16089. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16090. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16091. // Filters
  16092. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16093. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16094. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16095. if (generateMipMaps) {
  16096. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16097. }
  16098. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16099. this._internalTexturesCache.push(texture);
  16100. return texture;
  16101. };
  16102. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16103. var gl = this._gl;
  16104. if (!gl) {
  16105. return;
  16106. }
  16107. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16110. if (!noMipmap && !isCompressed) {
  16111. gl.generateMipmap(gl.TEXTURE_2D);
  16112. }
  16113. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16114. // this.resetTextureCache();
  16115. if (scene) {
  16116. scene._removePendingData(texture);
  16117. }
  16118. texture.onLoadedObservable.notifyObservers(texture);
  16119. texture.onLoadedObservable.clear();
  16120. };
  16121. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16122. var _this = this;
  16123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16124. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16125. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16126. var gl = this._gl;
  16127. if (!gl) {
  16128. return;
  16129. }
  16130. if (!texture._webGLTexture) {
  16131. // this.resetTextureCache();
  16132. if (scene) {
  16133. scene._removePendingData(texture);
  16134. }
  16135. return;
  16136. }
  16137. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16138. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16139. texture.baseWidth = width;
  16140. texture.baseHeight = height;
  16141. texture.width = potWidth;
  16142. texture.height = potHeight;
  16143. texture.isReady = true;
  16144. if (processFunction(potWidth, potHeight, function () {
  16145. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16146. })) {
  16147. // Returning as texture needs extra async steps
  16148. return;
  16149. }
  16150. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16151. };
  16152. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16153. // Create new RGBA data container.
  16154. var rgbaData;
  16155. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16156. rgbaData = new Float32Array(width * height * 4);
  16157. }
  16158. else {
  16159. rgbaData = new Uint32Array(width * height * 4);
  16160. }
  16161. // Convert each pixel.
  16162. for (var x = 0; x < width; x++) {
  16163. for (var y = 0; y < height; y++) {
  16164. var index = (y * width + x) * 3;
  16165. var newIndex = (y * width + x) * 4;
  16166. // Map Old Value to new value.
  16167. rgbaData[newIndex + 0] = rgbData[index + 0];
  16168. rgbaData[newIndex + 1] = rgbData[index + 1];
  16169. rgbaData[newIndex + 2] = rgbData[index + 2];
  16170. // Add fully opaque alpha channel.
  16171. rgbaData[newIndex + 3] = 1;
  16172. }
  16173. }
  16174. return rgbaData;
  16175. };
  16176. /** @hidden */
  16177. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16178. var gl = this._gl;
  16179. if (texture._framebuffer) {
  16180. gl.deleteFramebuffer(texture._framebuffer);
  16181. texture._framebuffer = null;
  16182. }
  16183. if (texture._depthStencilBuffer) {
  16184. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16185. texture._depthStencilBuffer = null;
  16186. }
  16187. if (texture._MSAAFramebuffer) {
  16188. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16189. texture._MSAAFramebuffer = null;
  16190. }
  16191. if (texture._MSAARenderBuffer) {
  16192. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16193. texture._MSAARenderBuffer = null;
  16194. }
  16195. };
  16196. /** @hidden */
  16197. Engine.prototype._releaseTexture = function (texture) {
  16198. var gl = this._gl;
  16199. this._releaseFramebufferObjects(texture);
  16200. gl.deleteTexture(texture._webGLTexture);
  16201. // Unbind channels
  16202. this.unbindAllTextures();
  16203. var index = this._internalTexturesCache.indexOf(texture);
  16204. if (index !== -1) {
  16205. this._internalTexturesCache.splice(index, 1);
  16206. }
  16207. // Integrated fixed lod samplers.
  16208. if (texture._lodTextureHigh) {
  16209. texture._lodTextureHigh.dispose();
  16210. }
  16211. if (texture._lodTextureMid) {
  16212. texture._lodTextureMid.dispose();
  16213. }
  16214. if (texture._lodTextureLow) {
  16215. texture._lodTextureLow.dispose();
  16216. }
  16217. // Set output texture of post process to null if the texture has been released/disposed
  16218. this.scenes.forEach(function (scene) {
  16219. scene.postProcesses.forEach(function (postProcess) {
  16220. if (postProcess._outputTexture == texture) {
  16221. postProcess._outputTexture = null;
  16222. }
  16223. });
  16224. scene.cameras.forEach(function (camera) {
  16225. camera._postProcesses.forEach(function (postProcess) {
  16226. if (postProcess) {
  16227. if (postProcess._outputTexture == texture) {
  16228. postProcess._outputTexture = null;
  16229. }
  16230. }
  16231. });
  16232. });
  16233. });
  16234. };
  16235. Engine.prototype.setProgram = function (program) {
  16236. if (this._currentProgram !== program) {
  16237. this._gl.useProgram(program);
  16238. this._currentProgram = program;
  16239. }
  16240. };
  16241. /**
  16242. * Binds an effect to the webGL context
  16243. * @param effect defines the effect to bind
  16244. */
  16245. Engine.prototype.bindSamplers = function (effect) {
  16246. this.setProgram(effect.getProgram());
  16247. var samplers = effect.getSamplers();
  16248. for (var index = 0; index < samplers.length; index++) {
  16249. var uniform = effect.getUniform(samplers[index]);
  16250. if (uniform) {
  16251. this._boundUniforms[index] = uniform;
  16252. }
  16253. }
  16254. this._currentEffect = null;
  16255. };
  16256. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16257. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16258. return;
  16259. }
  16260. // Remove
  16261. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16262. // Bind last to it
  16263. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16264. // Bind to dummy
  16265. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16266. };
  16267. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16268. if (!internalTexture) {
  16269. return -1;
  16270. }
  16271. internalTexture._initialSlot = channel;
  16272. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16273. if (channel !== internalTexture._designatedSlot) {
  16274. this._textureCollisions.addCount(1, false);
  16275. }
  16276. }
  16277. else {
  16278. if (channel !== internalTexture._designatedSlot) {
  16279. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16280. return internalTexture._designatedSlot;
  16281. }
  16282. else {
  16283. // No slot for this texture, let's pick a new one (if we find a free slot)
  16284. if (this._nextFreeTextureSlots.length) {
  16285. return this._nextFreeTextureSlots[0];
  16286. }
  16287. // We need to recycle the oldest bound texture, sorry.
  16288. this._textureCollisions.addCount(1, false);
  16289. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16290. }
  16291. }
  16292. }
  16293. return channel;
  16294. };
  16295. Engine.prototype._linkTrackers = function (previous, next) {
  16296. previous.next = next;
  16297. next.previous = previous;
  16298. };
  16299. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16300. var currentSlot = internalTexture._designatedSlot;
  16301. if (currentSlot === -1) {
  16302. return -1;
  16303. }
  16304. internalTexture._designatedSlot = -1;
  16305. if (this.disableTextureBindingOptimization) {
  16306. return -1;
  16307. }
  16308. // Remove from bound list
  16309. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16310. // Free the slot
  16311. this._boundTexturesCache[currentSlot] = null;
  16312. this._nextFreeTextureSlots.push(currentSlot);
  16313. return currentSlot;
  16314. };
  16315. Engine.prototype._activateCurrentTexture = function () {
  16316. if (this._currentTextureChannel !== this._activeChannel) {
  16317. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16318. this._currentTextureChannel = this._activeChannel;
  16319. }
  16320. };
  16321. /** @hidden */
  16322. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16323. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16324. if (force === void 0) { force = false; }
  16325. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16326. this._activeChannel = texture._designatedSlot;
  16327. }
  16328. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16329. var isTextureForRendering = texture && texture._initialSlot > -1;
  16330. if (currentTextureBound !== texture || force) {
  16331. if (currentTextureBound) {
  16332. this._removeDesignatedSlot(currentTextureBound);
  16333. }
  16334. this._activateCurrentTexture();
  16335. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16336. this._boundTexturesCache[this._activeChannel] = texture;
  16337. if (texture) {
  16338. if (!this.disableTextureBindingOptimization) {
  16339. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16340. if (slotIndex > -1) {
  16341. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16342. }
  16343. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16344. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16345. }
  16346. texture._designatedSlot = this._activeChannel;
  16347. }
  16348. }
  16349. else if (forTextureDataUpdate) {
  16350. this._activateCurrentTexture();
  16351. }
  16352. if (isTextureForRendering && !forTextureDataUpdate) {
  16353. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16354. }
  16355. };
  16356. /** @hidden */
  16357. Engine.prototype._bindTexture = function (channel, texture) {
  16358. if (channel < 0) {
  16359. return;
  16360. }
  16361. if (texture) {
  16362. channel = this._getCorrectTextureChannel(channel, texture);
  16363. }
  16364. this._activeChannel = channel;
  16365. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16366. };
  16367. /**
  16368. * Sets a texture to the webGL context from a postprocess
  16369. * @param channel defines the channel to use
  16370. * @param postProcess defines the source postprocess
  16371. */
  16372. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16373. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16374. };
  16375. /**
  16376. * Binds the output of the passed in post process to the texture channel specified
  16377. * @param channel The channel the texture should be bound to
  16378. * @param postProcess The post process which's output should be bound
  16379. */
  16380. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16381. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16382. };
  16383. /**
  16384. * Unbind all textures from the webGL context
  16385. */
  16386. Engine.prototype.unbindAllTextures = function () {
  16387. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16388. this._activeChannel = channel;
  16389. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16390. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16391. if (this.webGLVersion > 1) {
  16392. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16393. }
  16394. }
  16395. };
  16396. /**
  16397. * Sets a texture to the according uniform.
  16398. * @param channel The texture channel
  16399. * @param uniform The uniform to set
  16400. * @param texture The texture to apply
  16401. */
  16402. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16403. if (channel < 0) {
  16404. return;
  16405. }
  16406. if (uniform) {
  16407. this._boundUniforms[channel] = uniform;
  16408. }
  16409. this._setTexture(channel, texture);
  16410. };
  16411. /**
  16412. * Sets a depth stencil texture from a render target to the according uniform.
  16413. * @param channel The texture channel
  16414. * @param uniform The uniform to set
  16415. * @param texture The render target texture containing the depth stencil texture to apply
  16416. */
  16417. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16418. if (channel < 0) {
  16419. return;
  16420. }
  16421. if (uniform) {
  16422. this._boundUniforms[channel] = uniform;
  16423. }
  16424. if (!texture || !texture.depthStencilTexture) {
  16425. this._setTexture(channel, null);
  16426. }
  16427. else {
  16428. this._setTexture(channel, texture, false, true);
  16429. }
  16430. };
  16431. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16432. var uniform = this._boundUniforms[sourceSlot];
  16433. if (uniform._currentState === destination) {
  16434. return;
  16435. }
  16436. this._gl.uniform1i(uniform, destination);
  16437. uniform._currentState = destination;
  16438. };
  16439. Engine.prototype._getTextureWrapMode = function (mode) {
  16440. switch (mode) {
  16441. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16442. return this._gl.REPEAT;
  16443. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16444. return this._gl.CLAMP_TO_EDGE;
  16445. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16446. return this._gl.MIRRORED_REPEAT;
  16447. }
  16448. return this._gl.REPEAT;
  16449. };
  16450. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16451. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16452. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16453. // Not ready?
  16454. if (!texture) {
  16455. if (this._boundTexturesCache[channel] != null) {
  16456. this._activeChannel = channel;
  16457. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16458. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16459. if (this.webGLVersion > 1) {
  16460. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16461. }
  16462. }
  16463. return false;
  16464. }
  16465. // Video
  16466. if (texture.video) {
  16467. this._activeChannel = channel;
  16468. texture.update();
  16469. }
  16470. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16471. texture.delayLoad();
  16472. return false;
  16473. }
  16474. var internalTexture;
  16475. if (depthStencilTexture) {
  16476. internalTexture = texture.depthStencilTexture;
  16477. }
  16478. else if (texture.isReady()) {
  16479. internalTexture = texture.getInternalTexture();
  16480. }
  16481. else if (texture.isCube) {
  16482. internalTexture = this.emptyCubeTexture;
  16483. }
  16484. else if (texture.is3D) {
  16485. internalTexture = this.emptyTexture3D;
  16486. }
  16487. else {
  16488. internalTexture = this.emptyTexture;
  16489. }
  16490. if (!isPartOfTextureArray) {
  16491. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16492. }
  16493. var needToBind = true;
  16494. if (this._boundTexturesCache[channel] === internalTexture) {
  16495. this._moveBoundTextureOnTop(internalTexture);
  16496. if (!isPartOfTextureArray) {
  16497. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16498. }
  16499. needToBind = false;
  16500. }
  16501. this._activeChannel = channel;
  16502. if (internalTexture && internalTexture.is3D) {
  16503. if (needToBind) {
  16504. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16505. }
  16506. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16507. internalTexture._cachedWrapU = texture.wrapU;
  16508. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16509. }
  16510. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16511. internalTexture._cachedWrapV = texture.wrapV;
  16512. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16513. }
  16514. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16515. internalTexture._cachedWrapR = texture.wrapR;
  16516. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16517. }
  16518. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16519. }
  16520. else if (internalTexture && internalTexture.isCube) {
  16521. if (needToBind) {
  16522. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16523. }
  16524. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16525. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16526. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16527. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16528. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16529. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16530. }
  16531. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16532. }
  16533. else {
  16534. if (needToBind) {
  16535. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16536. }
  16537. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16538. internalTexture._cachedWrapU = texture.wrapU;
  16539. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16540. }
  16541. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16542. internalTexture._cachedWrapV = texture.wrapV;
  16543. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16544. }
  16545. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16546. }
  16547. return true;
  16548. };
  16549. /**
  16550. * Sets an array of texture to the webGL context
  16551. * @param channel defines the channel where the texture array must be set
  16552. * @param uniform defines the associated uniform location
  16553. * @param textures defines the array of textures to bind
  16554. */
  16555. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16556. if (channel < 0 || !uniform) {
  16557. return;
  16558. }
  16559. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16560. this._textureUnits = new Int32Array(textures.length);
  16561. }
  16562. for (var i = 0; i < textures.length; i++) {
  16563. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16564. }
  16565. this._gl.uniform1iv(uniform, this._textureUnits);
  16566. for (var index = 0; index < textures.length; index++) {
  16567. this._setTexture(this._textureUnits[index], textures[index], true);
  16568. }
  16569. };
  16570. /** @hidden */
  16571. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16572. var internalTexture = texture.getInternalTexture();
  16573. if (!internalTexture) {
  16574. return;
  16575. }
  16576. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16577. var value = texture.anisotropicFilteringLevel;
  16578. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16579. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16580. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16581. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16582. }
  16583. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16584. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16585. internalTexture._cachedAnisotropicFilteringLevel = value;
  16586. }
  16587. };
  16588. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16589. this._bindTextureDirectly(target, texture, true, true);
  16590. this._gl.texParameterf(target, parameter, value);
  16591. };
  16592. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16593. if (texture) {
  16594. this._bindTextureDirectly(target, texture, true, true);
  16595. }
  16596. this._gl.texParameteri(target, parameter, value);
  16597. };
  16598. /**
  16599. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16600. * @param x defines the x coordinate of the rectangle where pixels must be read
  16601. * @param y defines the y coordinate of the rectangle where pixels must be read
  16602. * @param width defines the width of the rectangle where pixels must be read
  16603. * @param height defines the height of the rectangle where pixels must be read
  16604. * @returns a Uint8Array containing RGBA colors
  16605. */
  16606. Engine.prototype.readPixels = function (x, y, width, height) {
  16607. var data = new Uint8Array(height * width * 4);
  16608. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16609. return data;
  16610. };
  16611. /**
  16612. * Add an externaly attached data from its key.
  16613. * This method call will fail and return false, if such key already exists.
  16614. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16615. * @param key the unique key that identifies the data
  16616. * @param data the data object to associate to the key for this Engine instance
  16617. * @return true if no such key were already present and the data was added successfully, false otherwise
  16618. */
  16619. Engine.prototype.addExternalData = function (key, data) {
  16620. if (!this._externalData) {
  16621. this._externalData = new BABYLON.StringDictionary();
  16622. }
  16623. return this._externalData.add(key, data);
  16624. };
  16625. /**
  16626. * Get an externaly attached data from its key
  16627. * @param key the unique key that identifies the data
  16628. * @return the associated data, if present (can be null), or undefined if not present
  16629. */
  16630. Engine.prototype.getExternalData = function (key) {
  16631. if (!this._externalData) {
  16632. this._externalData = new BABYLON.StringDictionary();
  16633. }
  16634. return this._externalData.get(key);
  16635. };
  16636. /**
  16637. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16638. * @param key the unique key that identifies the data
  16639. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16640. * @return the associated data, can be null if the factory returned null.
  16641. */
  16642. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16643. if (!this._externalData) {
  16644. this._externalData = new BABYLON.StringDictionary();
  16645. }
  16646. return this._externalData.getOrAddWithFactory(key, factory);
  16647. };
  16648. /**
  16649. * Remove an externaly attached data from the Engine instance
  16650. * @param key the unique key that identifies the data
  16651. * @return true if the data was successfully removed, false if it doesn't exist
  16652. */
  16653. Engine.prototype.removeExternalData = function (key) {
  16654. if (!this._externalData) {
  16655. this._externalData = new BABYLON.StringDictionary();
  16656. }
  16657. return this._externalData.remove(key);
  16658. };
  16659. /**
  16660. * Unbind all vertex attributes from the webGL context
  16661. */
  16662. Engine.prototype.unbindAllAttributes = function () {
  16663. if (this._mustWipeVertexAttributes) {
  16664. this._mustWipeVertexAttributes = false;
  16665. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16666. this._gl.disableVertexAttribArray(i);
  16667. this._vertexAttribArraysEnabled[i] = false;
  16668. this._currentBufferPointers[i].active = false;
  16669. }
  16670. return;
  16671. }
  16672. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16673. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16674. continue;
  16675. }
  16676. this._gl.disableVertexAttribArray(i);
  16677. this._vertexAttribArraysEnabled[i] = false;
  16678. this._currentBufferPointers[i].active = false;
  16679. }
  16680. };
  16681. /**
  16682. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16683. */
  16684. Engine.prototype.releaseEffects = function () {
  16685. for (var name in this._compiledEffects) {
  16686. this._deleteProgram(this._compiledEffects[name]._program);
  16687. }
  16688. this._compiledEffects = {};
  16689. };
  16690. /**
  16691. * Dispose and release all associated resources
  16692. */
  16693. Engine.prototype.dispose = function () {
  16694. this.hideLoadingUI();
  16695. this.stopRenderLoop();
  16696. // Release postProcesses
  16697. while (this.postProcesses.length) {
  16698. this.postProcesses[0].dispose();
  16699. }
  16700. // Empty texture
  16701. if (this._emptyTexture) {
  16702. this._releaseTexture(this._emptyTexture);
  16703. this._emptyTexture = null;
  16704. }
  16705. if (this._emptyCubeTexture) {
  16706. this._releaseTexture(this._emptyCubeTexture);
  16707. this._emptyCubeTexture = null;
  16708. }
  16709. // Rescale PP
  16710. if (this._rescalePostProcess) {
  16711. this._rescalePostProcess.dispose();
  16712. }
  16713. // Release scenes
  16714. while (this.scenes.length) {
  16715. this.scenes[0].dispose();
  16716. }
  16717. // Release audio engine
  16718. if (Engine.audioEngine) {
  16719. Engine.audioEngine.dispose();
  16720. }
  16721. // Release effects
  16722. this.releaseEffects();
  16723. // Unbind
  16724. this.unbindAllAttributes();
  16725. this._boundUniforms = [];
  16726. if (this._dummyFramebuffer) {
  16727. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16728. }
  16729. //WebVR
  16730. this.disableVR();
  16731. // Events
  16732. if (BABYLON.Tools.IsWindowObjectExist()) {
  16733. window.removeEventListener("blur", this._onBlur);
  16734. window.removeEventListener("focus", this._onFocus);
  16735. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16736. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16737. if (this._renderingCanvas) {
  16738. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16739. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16740. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16741. if (!this._doNotHandleContextLost) {
  16742. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16743. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16744. }
  16745. }
  16746. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16747. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16748. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16749. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16750. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16751. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16752. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16753. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16754. if (this._onVrDisplayConnect) {
  16755. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16756. if (this._onVrDisplayDisconnect) {
  16757. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16758. }
  16759. if (this._onVrDisplayPresentChange) {
  16760. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16761. }
  16762. this._onVrDisplayConnect = null;
  16763. this._onVrDisplayDisconnect = null;
  16764. }
  16765. }
  16766. // Remove from Instances
  16767. var index = Engine.Instances.indexOf(this);
  16768. if (index >= 0) {
  16769. Engine.Instances.splice(index, 1);
  16770. }
  16771. this._workingCanvas = null;
  16772. this._workingContext = null;
  16773. this._currentBufferPointers = [];
  16774. this._renderingCanvas = null;
  16775. this._currentProgram = null;
  16776. this._bindedRenderFunction = null;
  16777. this.onResizeObservable.clear();
  16778. this.onCanvasBlurObservable.clear();
  16779. this.onCanvasFocusObservable.clear();
  16780. this.onCanvasPointerOutObservable.clear();
  16781. this.onBeginFrameObservable.clear();
  16782. this.onEndFrameObservable.clear();
  16783. BABYLON.Effect.ResetCache();
  16784. // Abort active requests
  16785. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16786. var request = _a[_i];
  16787. request.abort();
  16788. }
  16789. };
  16790. // Loading screen
  16791. /**
  16792. * Display the loading screen
  16793. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16794. */
  16795. Engine.prototype.displayLoadingUI = function () {
  16796. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16797. return;
  16798. }
  16799. var loadingScreen = this.loadingScreen;
  16800. if (loadingScreen) {
  16801. loadingScreen.displayLoadingUI();
  16802. }
  16803. };
  16804. /**
  16805. * Hide the loading screen
  16806. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16807. */
  16808. Engine.prototype.hideLoadingUI = function () {
  16809. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16810. return;
  16811. }
  16812. var loadingScreen = this.loadingScreen;
  16813. if (loadingScreen) {
  16814. loadingScreen.hideLoadingUI();
  16815. }
  16816. };
  16817. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16818. /**
  16819. * Gets the current loading screen object
  16820. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16821. */
  16822. get: function () {
  16823. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16824. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16825. return this._loadingScreen;
  16826. },
  16827. /**
  16828. * Sets the current loading screen object
  16829. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16830. */
  16831. set: function (loadingScreen) {
  16832. this._loadingScreen = loadingScreen;
  16833. },
  16834. enumerable: true,
  16835. configurable: true
  16836. });
  16837. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16838. /**
  16839. * Sets the current loading screen text
  16840. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16841. */
  16842. set: function (text) {
  16843. this.loadingScreen.loadingUIText = text;
  16844. },
  16845. enumerable: true,
  16846. configurable: true
  16847. });
  16848. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16849. /**
  16850. * Sets the current loading screen background color
  16851. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16852. */
  16853. set: function (color) {
  16854. this.loadingScreen.loadingUIBackgroundColor = color;
  16855. },
  16856. enumerable: true,
  16857. configurable: true
  16858. });
  16859. /**
  16860. * Attach a new callback raised when context lost event is fired
  16861. * @param callback defines the callback to call
  16862. */
  16863. Engine.prototype.attachContextLostEvent = function (callback) {
  16864. if (this._renderingCanvas) {
  16865. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16866. }
  16867. };
  16868. /**
  16869. * Attach a new callback raised when context restored event is fired
  16870. * @param callback defines the callback to call
  16871. */
  16872. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16873. if (this._renderingCanvas) {
  16874. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16875. }
  16876. };
  16877. /**
  16878. * Gets the source code of the vertex shader associated with a specific webGL program
  16879. * @param program defines the program to use
  16880. * @returns a string containing the source code of the vertex shader associated with the program
  16881. */
  16882. Engine.prototype.getVertexShaderSource = function (program) {
  16883. var shaders = this._gl.getAttachedShaders(program);
  16884. if (!shaders) {
  16885. return null;
  16886. }
  16887. return this._gl.getShaderSource(shaders[0]);
  16888. };
  16889. /**
  16890. * Gets the source code of the fragment shader associated with a specific webGL program
  16891. * @param program defines the program to use
  16892. * @returns a string containing the source code of the fragment shader associated with the program
  16893. */
  16894. Engine.prototype.getFragmentShaderSource = function (program) {
  16895. var shaders = this._gl.getAttachedShaders(program);
  16896. if (!shaders) {
  16897. return null;
  16898. }
  16899. return this._gl.getShaderSource(shaders[1]);
  16900. };
  16901. /**
  16902. * Get the current error code of the webGL context
  16903. * @returns the error code
  16904. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16905. */
  16906. Engine.prototype.getError = function () {
  16907. return this._gl.getError();
  16908. };
  16909. // FPS
  16910. /**
  16911. * Gets the current framerate
  16912. * @returns a number representing the framerate
  16913. */
  16914. Engine.prototype.getFps = function () {
  16915. return this._fps;
  16916. };
  16917. /**
  16918. * Gets the time spent between current and previous frame
  16919. * @returns a number representing the delta time in ms
  16920. */
  16921. Engine.prototype.getDeltaTime = function () {
  16922. return this._deltaTime;
  16923. };
  16924. Engine.prototype._measureFps = function () {
  16925. this._performanceMonitor.sampleFrame();
  16926. this._fps = this._performanceMonitor.averageFPS;
  16927. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16928. };
  16929. /** @hidden */
  16930. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16931. if (faceIndex === void 0) { faceIndex = -1; }
  16932. var gl = this._gl;
  16933. if (!this._dummyFramebuffer) {
  16934. var dummy = gl.createFramebuffer();
  16935. if (!dummy) {
  16936. throw new Error("Unable to create dummy framebuffer");
  16937. }
  16938. this._dummyFramebuffer = dummy;
  16939. }
  16940. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16941. if (faceIndex > -1) {
  16942. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16943. }
  16944. else {
  16945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16946. }
  16947. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16948. var buffer;
  16949. switch (readType) {
  16950. case gl.UNSIGNED_BYTE:
  16951. buffer = new Uint8Array(4 * width * height);
  16952. readType = gl.UNSIGNED_BYTE;
  16953. break;
  16954. default:
  16955. buffer = new Float32Array(4 * width * height);
  16956. readType = gl.FLOAT;
  16957. break;
  16958. }
  16959. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16960. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16961. return buffer;
  16962. };
  16963. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16964. if (this._webGLVersion > 1) {
  16965. return this._caps.colorBufferFloat;
  16966. }
  16967. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16968. };
  16969. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16970. if (this._webGLVersion > 1) {
  16971. return this._caps.colorBufferFloat;
  16972. }
  16973. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16974. };
  16975. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16976. Engine.prototype._canRenderToFramebuffer = function (type) {
  16977. var gl = this._gl;
  16978. //clear existing errors
  16979. while (gl.getError() !== gl.NO_ERROR) { }
  16980. var successful = true;
  16981. var texture = gl.createTexture();
  16982. gl.bindTexture(gl.TEXTURE_2D, texture);
  16983. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16986. var fb = gl.createFramebuffer();
  16987. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16988. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16989. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16990. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16991. successful = successful && (gl.getError() === gl.NO_ERROR);
  16992. //try render by clearing frame buffer's color buffer
  16993. if (successful) {
  16994. gl.clear(gl.COLOR_BUFFER_BIT);
  16995. successful = successful && (gl.getError() === gl.NO_ERROR);
  16996. }
  16997. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16998. if (successful) {
  16999. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17000. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17001. var readFormat = gl.RGBA;
  17002. var readType = gl.UNSIGNED_BYTE;
  17003. var buffer = new Uint8Array(4);
  17004. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17005. successful = successful && (gl.getError() === gl.NO_ERROR);
  17006. }
  17007. //clean up
  17008. gl.deleteTexture(texture);
  17009. gl.deleteFramebuffer(fb);
  17010. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17011. //clear accumulated errors
  17012. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17013. return successful;
  17014. };
  17015. /** @hidden */
  17016. Engine.prototype._getWebGLTextureType = function (type) {
  17017. if (type === Engine.TEXTURETYPE_FLOAT) {
  17018. return this._gl.FLOAT;
  17019. }
  17020. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17021. // Add Half Float Constant.
  17022. return this._gl.HALF_FLOAT_OES;
  17023. }
  17024. return this._gl.UNSIGNED_BYTE;
  17025. };
  17026. ;
  17027. Engine.prototype._getInternalFormat = function (format) {
  17028. var internalFormat = this._gl.RGBA;
  17029. switch (format) {
  17030. case Engine.TEXTUREFORMAT_ALPHA:
  17031. internalFormat = this._gl.ALPHA;
  17032. break;
  17033. case Engine.TEXTUREFORMAT_LUMINANCE:
  17034. internalFormat = this._gl.LUMINANCE;
  17035. break;
  17036. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17037. internalFormat = this._gl.LUMINANCE_ALPHA;
  17038. break;
  17039. case Engine.TEXTUREFORMAT_RGB:
  17040. case Engine.TEXTUREFORMAT_RGB32F:
  17041. internalFormat = this._gl.RGB;
  17042. break;
  17043. case Engine.TEXTUREFORMAT_RGBA:
  17044. case Engine.TEXTUREFORMAT_RGBA32F:
  17045. internalFormat = this._gl.RGBA;
  17046. break;
  17047. case Engine.TEXTUREFORMAT_R32F:
  17048. internalFormat = this._gl.RED;
  17049. break;
  17050. case Engine.TEXTUREFORMAT_RG32F:
  17051. internalFormat = this._gl.RG;
  17052. break;
  17053. }
  17054. return internalFormat;
  17055. };
  17056. /** @hidden */
  17057. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17058. if (this._webGLVersion === 1) {
  17059. if (format) {
  17060. switch (format) {
  17061. case Engine.TEXTUREFORMAT_LUMINANCE:
  17062. return this._gl.LUMINANCE;
  17063. }
  17064. }
  17065. return this._gl.RGBA;
  17066. }
  17067. if (type === Engine.TEXTURETYPE_FLOAT) {
  17068. if (format) {
  17069. switch (format) {
  17070. case Engine.TEXTUREFORMAT_R32F:
  17071. return this._gl.R32F;
  17072. case Engine.TEXTUREFORMAT_RG32F:
  17073. return this._gl.RG32F;
  17074. case Engine.TEXTUREFORMAT_RGB32F:
  17075. return this._gl.RGB32F;
  17076. }
  17077. }
  17078. return this._gl.RGBA32F;
  17079. }
  17080. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17081. return this._gl.RGBA16F;
  17082. }
  17083. if (format) {
  17084. switch (format) {
  17085. case Engine.TEXTUREFORMAT_LUMINANCE:
  17086. return this._gl.LUMINANCE;
  17087. case Engine.TEXTUREFORMAT_RGB:
  17088. return this._gl.RGB;
  17089. }
  17090. }
  17091. return this._gl.RGBA;
  17092. };
  17093. ;
  17094. /** @hidden */
  17095. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17096. if (type === Engine.TEXTURETYPE_FLOAT) {
  17097. return this._gl.RGBA32F;
  17098. }
  17099. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17100. return this._gl.RGBA16F;
  17101. }
  17102. return this._gl.RGBA8;
  17103. };
  17104. ;
  17105. /**
  17106. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17107. * @return the new query
  17108. */
  17109. Engine.prototype.createQuery = function () {
  17110. return this._gl.createQuery();
  17111. };
  17112. /**
  17113. * Delete and release a webGL query
  17114. * @param query defines the query to delete
  17115. * @return the current engine
  17116. */
  17117. Engine.prototype.deleteQuery = function (query) {
  17118. this._gl.deleteQuery(query);
  17119. return this;
  17120. };
  17121. /**
  17122. * Check if a given query has resolved and got its value
  17123. * @param query defines the query to check
  17124. * @returns true if the query got its value
  17125. */
  17126. Engine.prototype.isQueryResultAvailable = function (query) {
  17127. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17128. };
  17129. /**
  17130. * Gets the value of a given query
  17131. * @param query defines the query to check
  17132. * @returns the value of the query
  17133. */
  17134. Engine.prototype.getQueryResult = function (query) {
  17135. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17136. };
  17137. /**
  17138. * Initiates an occlusion query
  17139. * @param algorithmType defines the algorithm to use
  17140. * @param query defines the query to use
  17141. * @returns the current engine
  17142. * @see http://doc.babylonjs.com/features/occlusionquery
  17143. */
  17144. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17145. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17146. this._gl.beginQuery(glAlgorithm, query);
  17147. return this;
  17148. };
  17149. /**
  17150. * Ends an occlusion query
  17151. * @see http://doc.babylonjs.com/features/occlusionquery
  17152. * @param algorithmType defines the algorithm to use
  17153. * @returns the current engine
  17154. */
  17155. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17156. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17157. this._gl.endQuery(glAlgorithm);
  17158. return this;
  17159. };
  17160. /* Time queries */
  17161. Engine.prototype._createTimeQuery = function () {
  17162. var timerQuery = this._caps.timerQuery;
  17163. if (timerQuery.createQueryEXT) {
  17164. return timerQuery.createQueryEXT();
  17165. }
  17166. return this.createQuery();
  17167. };
  17168. Engine.prototype._deleteTimeQuery = function (query) {
  17169. var timerQuery = this._caps.timerQuery;
  17170. if (timerQuery.deleteQueryEXT) {
  17171. timerQuery.deleteQueryEXT(query);
  17172. return;
  17173. }
  17174. this.deleteQuery(query);
  17175. };
  17176. Engine.prototype._getTimeQueryResult = function (query) {
  17177. var timerQuery = this._caps.timerQuery;
  17178. if (timerQuery.getQueryObjectEXT) {
  17179. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17180. }
  17181. return this.getQueryResult(query);
  17182. };
  17183. Engine.prototype._getTimeQueryAvailability = function (query) {
  17184. var timerQuery = this._caps.timerQuery;
  17185. if (timerQuery.getQueryObjectEXT) {
  17186. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17187. }
  17188. return this.isQueryResultAvailable(query);
  17189. };
  17190. /**
  17191. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17192. * Please note that only one query can be issued at a time
  17193. * @returns a time token used to track the time span
  17194. */
  17195. Engine.prototype.startTimeQuery = function () {
  17196. var timerQuery = this._caps.timerQuery;
  17197. if (!timerQuery) {
  17198. return null;
  17199. }
  17200. var token = new BABYLON._TimeToken();
  17201. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17202. if (this._caps.canUseTimestampForTimerQuery) {
  17203. token._startTimeQuery = this._createTimeQuery();
  17204. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17205. }
  17206. else {
  17207. if (this._currentNonTimestampToken) {
  17208. return this._currentNonTimestampToken;
  17209. }
  17210. token._timeElapsedQuery = this._createTimeQuery();
  17211. if (timerQuery.beginQueryEXT) {
  17212. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17213. }
  17214. else {
  17215. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17216. }
  17217. this._currentNonTimestampToken = token;
  17218. }
  17219. return token;
  17220. };
  17221. /**
  17222. * Ends a time query
  17223. * @param token defines the token used to measure the time span
  17224. * @returns the time spent (in ns)
  17225. */
  17226. Engine.prototype.endTimeQuery = function (token) {
  17227. var timerQuery = this._caps.timerQuery;
  17228. if (!timerQuery || !token) {
  17229. return -1;
  17230. }
  17231. if (this._caps.canUseTimestampForTimerQuery) {
  17232. if (!token._startTimeQuery) {
  17233. return -1;
  17234. }
  17235. if (!token._endTimeQuery) {
  17236. token._endTimeQuery = this._createTimeQuery();
  17237. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17238. }
  17239. }
  17240. else if (!token._timeElapsedQueryEnded) {
  17241. if (!token._timeElapsedQuery) {
  17242. return -1;
  17243. }
  17244. if (timerQuery.endQueryEXT) {
  17245. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17246. }
  17247. else {
  17248. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17249. }
  17250. token._timeElapsedQueryEnded = true;
  17251. }
  17252. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17253. var available = false;
  17254. if (token._endTimeQuery) {
  17255. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17256. }
  17257. else if (token._timeElapsedQuery) {
  17258. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17259. }
  17260. if (available && !disjoint) {
  17261. var result = 0;
  17262. if (this._caps.canUseTimestampForTimerQuery) {
  17263. if (!token._startTimeQuery || !token._endTimeQuery) {
  17264. return -1;
  17265. }
  17266. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17267. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17268. result = timeEnd - timeStart;
  17269. this._deleteTimeQuery(token._startTimeQuery);
  17270. this._deleteTimeQuery(token._endTimeQuery);
  17271. token._startTimeQuery = null;
  17272. token._endTimeQuery = null;
  17273. }
  17274. else {
  17275. if (!token._timeElapsedQuery) {
  17276. return -1;
  17277. }
  17278. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17279. this._deleteTimeQuery(token._timeElapsedQuery);
  17280. token._timeElapsedQuery = null;
  17281. token._timeElapsedQueryEnded = false;
  17282. this._currentNonTimestampToken = null;
  17283. }
  17284. return result;
  17285. }
  17286. return -1;
  17287. };
  17288. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17289. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17290. };
  17291. // Transform feedback
  17292. /**
  17293. * Creates a webGL transform feedback object
  17294. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17295. * @returns the webGL transform feedback object
  17296. */
  17297. Engine.prototype.createTransformFeedback = function () {
  17298. return this._gl.createTransformFeedback();
  17299. };
  17300. /**
  17301. * Delete a webGL transform feedback object
  17302. * @param value defines the webGL transform feedback object to delete
  17303. */
  17304. Engine.prototype.deleteTransformFeedback = function (value) {
  17305. this._gl.deleteTransformFeedback(value);
  17306. };
  17307. /**
  17308. * Bind a webGL transform feedback object to the webgl context
  17309. * @param value defines the webGL transform feedback object to bind
  17310. */
  17311. Engine.prototype.bindTransformFeedback = function (value) {
  17312. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17313. };
  17314. /**
  17315. * Begins a transform feedback operation
  17316. * @param usePoints defines if points or triangles must be used
  17317. */
  17318. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17319. if (usePoints === void 0) { usePoints = true; }
  17320. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17321. };
  17322. /**
  17323. * Ends a transform feedback operation
  17324. */
  17325. Engine.prototype.endTransformFeedback = function () {
  17326. this._gl.endTransformFeedback();
  17327. };
  17328. /**
  17329. * Specify the varyings to use with transform feedback
  17330. * @param program defines the associated webGL program
  17331. * @param value defines the list of strings representing the varying names
  17332. */
  17333. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17334. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17335. };
  17336. /**
  17337. * Bind a webGL buffer for a transform feedback operation
  17338. * @param value defines the webGL buffer to bind
  17339. */
  17340. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17341. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17342. };
  17343. /** @hidden */
  17344. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17345. var _this = this;
  17346. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17347. this._activeRequests.push(request);
  17348. request.onCompleteObservable.add(function (request) {
  17349. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17350. });
  17351. return request;
  17352. };
  17353. /** @hidden */
  17354. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17355. var _this = this;
  17356. return new Promise(function (resolve, reject) {
  17357. _this._loadFile(url, function (data) {
  17358. resolve(data);
  17359. }, undefined, database, useArrayBuffer, function (request, exception) {
  17360. reject(exception);
  17361. });
  17362. });
  17363. };
  17364. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17365. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17366. var onload = function (data) {
  17367. loadedFiles[index] = data;
  17368. loadedFiles._internalCount++;
  17369. if (loadedFiles._internalCount === 6) {
  17370. onfinish(loadedFiles);
  17371. }
  17372. };
  17373. var onerror = function (request, exception) {
  17374. if (onErrorCallBack && request) {
  17375. onErrorCallBack(request.status + " " + request.statusText, exception);
  17376. }
  17377. };
  17378. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17379. };
  17380. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17381. if (onError === void 0) { onError = null; }
  17382. var loadedFiles = [];
  17383. loadedFiles._internalCount = 0;
  17384. for (var index = 0; index < 6; index++) {
  17385. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17386. }
  17387. };
  17388. // Statics
  17389. /**
  17390. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17391. * @returns true if the engine can be created
  17392. * @ignorenaming
  17393. */
  17394. Engine.isSupported = function () {
  17395. try {
  17396. var tempcanvas = document.createElement("canvas");
  17397. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17398. return gl != null && !!window.WebGLRenderingContext;
  17399. }
  17400. catch (e) {
  17401. return false;
  17402. }
  17403. };
  17404. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17405. Engine.ExceptionList = [
  17406. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17407. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17408. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17409. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17410. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17411. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17412. ];
  17413. /** Gets the list of created engines */
  17414. Engine.Instances = new Array();
  17415. // Const statics
  17416. Engine._ALPHA_DISABLE = 0;
  17417. Engine._ALPHA_ADD = 1;
  17418. Engine._ALPHA_COMBINE = 2;
  17419. Engine._ALPHA_SUBTRACT = 3;
  17420. Engine._ALPHA_MULTIPLY = 4;
  17421. Engine._ALPHA_MAXIMIZED = 5;
  17422. Engine._ALPHA_ONEONE = 6;
  17423. Engine._ALPHA_PREMULTIPLIED = 7;
  17424. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17425. Engine._ALPHA_INTERPOLATE = 9;
  17426. Engine._ALPHA_SCREENMODE = 10;
  17427. Engine._DELAYLOADSTATE_NONE = 0;
  17428. Engine._DELAYLOADSTATE_LOADED = 1;
  17429. Engine._DELAYLOADSTATE_LOADING = 2;
  17430. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17431. Engine._TEXTUREFORMAT_ALPHA = 0;
  17432. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17433. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17434. Engine._TEXTUREFORMAT_RGB = 4;
  17435. Engine._TEXTUREFORMAT_RGBA = 5;
  17436. Engine._TEXTUREFORMAT_R32F = 6;
  17437. Engine._TEXTUREFORMAT_RG32F = 7;
  17438. Engine._TEXTUREFORMAT_RGB32F = 8;
  17439. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17440. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17441. Engine._TEXTURETYPE_FLOAT = 1;
  17442. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17443. // Depht or Stencil test Constants.
  17444. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17445. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17446. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17447. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17448. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17449. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17450. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17451. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17452. // Stencil Actions Constants.
  17453. Engine._KEEP = 0x1E00;
  17454. Engine._REPLACE = 0x1E01;
  17455. Engine._INCR = 0x1E02;
  17456. Engine._DECR = 0x1E03;
  17457. Engine._INVERT = 0x150A;
  17458. Engine._INCR_WRAP = 0x8507;
  17459. Engine._DECR_WRAP = 0x8508;
  17460. // Texture rescaling mode
  17461. Engine._SCALEMODE_FLOOR = 1;
  17462. Engine._SCALEMODE_NEAREST = 2;
  17463. Engine._SCALEMODE_CEILING = 3;
  17464. // Updatable statics so stick with vars here
  17465. /**
  17466. * Gets or sets the epsilon value used by collision engine
  17467. */
  17468. Engine.CollisionsEpsilon = 0.001;
  17469. /**
  17470. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17471. */
  17472. Engine.CodeRepository = "src/";
  17473. /**
  17474. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17475. */
  17476. Engine.ShadersRepository = "src/Shaders/";
  17477. return Engine;
  17478. }());
  17479. BABYLON.Engine = Engine;
  17480. })(BABYLON || (BABYLON = {}));
  17481. //# sourceMappingURL=babylon.engine.js.map
  17482. var BABYLON;
  17483. (function (BABYLON) {
  17484. /**
  17485. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17486. */
  17487. var Node = /** @class */ (function () {
  17488. /**
  17489. * Creates a new Node
  17490. * @param {string} name - the name and id to be given to this node
  17491. * @param {BABYLON.Scene} the scene this node will be added to
  17492. */
  17493. function Node(name, scene) {
  17494. if (scene === void 0) { scene = null; }
  17495. /**
  17496. * Gets or sets a string used to store user defined state for the node
  17497. */
  17498. this.state = "";
  17499. /**
  17500. * Gets or sets an object used to store user defined information for the node
  17501. */
  17502. this.metadata = null;
  17503. /**
  17504. * Gets or sets a boolean used to define if the node must be serialized
  17505. */
  17506. this.doNotSerialize = false;
  17507. /** @hidden */
  17508. this._isDisposed = false;
  17509. /**
  17510. * Gets a list of Animations associated with the node
  17511. */
  17512. this.animations = new Array();
  17513. this._ranges = {};
  17514. this._isEnabled = true;
  17515. this._isReady = true;
  17516. /** @hidden */
  17517. this._currentRenderId = -1;
  17518. this._parentRenderId = -1;
  17519. this._childRenderId = -1;
  17520. this._animationPropertiesOverride = null;
  17521. /**
  17522. * An event triggered when the mesh is disposed
  17523. */
  17524. this.onDisposeObservable = new BABYLON.Observable();
  17525. // Behaviors
  17526. this._behaviors = new Array();
  17527. this.name = name;
  17528. this.id = name;
  17529. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17530. this.uniqueId = this._scene.getUniqueId();
  17531. this._initCache();
  17532. }
  17533. /**
  17534. * Gets a boolean indicating if the node has been disposed
  17535. * @returns true if the node was disposed
  17536. */
  17537. Node.prototype.isDisposed = function () {
  17538. return this._isDisposed;
  17539. };
  17540. Object.defineProperty(Node.prototype, "parent", {
  17541. get: function () {
  17542. return this._parentNode;
  17543. },
  17544. /**
  17545. * Gets or sets the parent of the node
  17546. */
  17547. set: function (parent) {
  17548. if (this._parentNode === parent) {
  17549. return;
  17550. }
  17551. // Remove self from list of children of parent
  17552. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17553. var index = this._parentNode._children.indexOf(this);
  17554. if (index !== -1) {
  17555. this._parentNode._children.splice(index, 1);
  17556. }
  17557. }
  17558. // Store new parent
  17559. this._parentNode = parent;
  17560. // Add as child to new parent
  17561. if (this._parentNode) {
  17562. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17563. this._parentNode._children = new Array();
  17564. }
  17565. this._parentNode._children.push(this);
  17566. }
  17567. },
  17568. enumerable: true,
  17569. configurable: true
  17570. });
  17571. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17572. /**
  17573. * Gets or sets the animation properties override
  17574. */
  17575. get: function () {
  17576. if (!this._animationPropertiesOverride) {
  17577. return this._scene.animationPropertiesOverride;
  17578. }
  17579. return this._animationPropertiesOverride;
  17580. },
  17581. set: function (value) {
  17582. this._animationPropertiesOverride = value;
  17583. },
  17584. enumerable: true,
  17585. configurable: true
  17586. });
  17587. /**
  17588. * Gets a string idenfifying the name of the class
  17589. * @returns "Node" string
  17590. */
  17591. Node.prototype.getClassName = function () {
  17592. return "Node";
  17593. };
  17594. Object.defineProperty(Node.prototype, "onDispose", {
  17595. /**
  17596. * Sets a callback that will be raised when the node will be disposed
  17597. */
  17598. set: function (callback) {
  17599. if (this._onDisposeObserver) {
  17600. this.onDisposeObservable.remove(this._onDisposeObserver);
  17601. }
  17602. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17603. },
  17604. enumerable: true,
  17605. configurable: true
  17606. });
  17607. /**
  17608. * Gets the scene of the node
  17609. * @returns a {BABYLON.Scene}
  17610. */
  17611. Node.prototype.getScene = function () {
  17612. return this._scene;
  17613. };
  17614. /**
  17615. * Gets the engine of the node
  17616. * @returns a {BABYLON.Engine}
  17617. */
  17618. Node.prototype.getEngine = function () {
  17619. return this._scene.getEngine();
  17620. };
  17621. /**
  17622. * Attach a behavior to the node
  17623. * @see http://doc.babylonjs.com/features/behaviour
  17624. * @param behavior defines the behavior to attach
  17625. * @returns the current Node
  17626. */
  17627. Node.prototype.addBehavior = function (behavior) {
  17628. var _this = this;
  17629. var index = this._behaviors.indexOf(behavior);
  17630. if (index !== -1) {
  17631. return this;
  17632. }
  17633. behavior.init();
  17634. if (this._scene.isLoading) {
  17635. // We defer the attach when the scene will be loaded
  17636. var observer = this._scene.onDataLoadedObservable.add(function () {
  17637. behavior.attach(_this);
  17638. setTimeout(function () {
  17639. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17640. _this._scene.onDataLoadedObservable.remove(observer);
  17641. }, 0);
  17642. });
  17643. }
  17644. else {
  17645. behavior.attach(this);
  17646. }
  17647. this._behaviors.push(behavior);
  17648. return this;
  17649. };
  17650. /**
  17651. * Remove an attached behavior
  17652. * @see http://doc.babylonjs.com/features/behaviour
  17653. * @param behavior defines the behavior to attach
  17654. * @returns the current Node
  17655. */
  17656. Node.prototype.removeBehavior = function (behavior) {
  17657. var index = this._behaviors.indexOf(behavior);
  17658. if (index === -1) {
  17659. return this;
  17660. }
  17661. this._behaviors[index].detach();
  17662. this._behaviors.splice(index, 1);
  17663. return this;
  17664. };
  17665. Object.defineProperty(Node.prototype, "behaviors", {
  17666. /**
  17667. * Gets the list of attached behaviors
  17668. * @see http://doc.babylonjs.com/features/behaviour
  17669. */
  17670. get: function () {
  17671. return this._behaviors;
  17672. },
  17673. enumerable: true,
  17674. configurable: true
  17675. });
  17676. /**
  17677. * Gets an attached behavior by name
  17678. * @param name defines the name of the behavior to look for
  17679. * @see http://doc.babylonjs.com/features/behaviour
  17680. * @returns null if behavior was not found else the requested behavior
  17681. */
  17682. Node.prototype.getBehaviorByName = function (name) {
  17683. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17684. var behavior = _a[_i];
  17685. if (behavior.name === name) {
  17686. return behavior;
  17687. }
  17688. }
  17689. return null;
  17690. };
  17691. /**
  17692. * Returns the world matrix of the node
  17693. * @returns a matrix containing the node's world matrix
  17694. */
  17695. Node.prototype.getWorldMatrix = function () {
  17696. return BABYLON.Matrix.Identity();
  17697. };
  17698. /** @hidden */
  17699. Node.prototype._getWorldMatrixDeterminant = function () {
  17700. return 1;
  17701. };
  17702. // override it in derived class if you add new variables to the cache
  17703. // and call the parent class method
  17704. /** @hidden */
  17705. Node.prototype._initCache = function () {
  17706. this._cache = {};
  17707. this._cache.parent = undefined;
  17708. };
  17709. /** @hidden */
  17710. Node.prototype.updateCache = function (force) {
  17711. if (!force && this.isSynchronized())
  17712. return;
  17713. this._cache.parent = this.parent;
  17714. this._updateCache();
  17715. };
  17716. // override it in derived class if you add new variables to the cache
  17717. // and call the parent class method if !ignoreParentClass
  17718. /** @hidden */
  17719. Node.prototype._updateCache = function (ignoreParentClass) {
  17720. };
  17721. // override it in derived class if you add new variables to the cache
  17722. /** @hidden */
  17723. Node.prototype._isSynchronized = function () {
  17724. return true;
  17725. };
  17726. /** @hidden */
  17727. Node.prototype._markSyncedWithParent = function () {
  17728. if (this.parent) {
  17729. this._parentRenderId = this.parent._childRenderId;
  17730. }
  17731. };
  17732. /** @hidden */
  17733. Node.prototype.isSynchronizedWithParent = function () {
  17734. if (!this.parent) {
  17735. return true;
  17736. }
  17737. if (this._parentRenderId !== this.parent._childRenderId) {
  17738. return false;
  17739. }
  17740. return this.parent.isSynchronized();
  17741. };
  17742. /** @hidden */
  17743. Node.prototype.isSynchronized = function (updateCache) {
  17744. var check = this.hasNewParent();
  17745. check = check || !this.isSynchronizedWithParent();
  17746. check = check || !this._isSynchronized();
  17747. if (updateCache)
  17748. this.updateCache(true);
  17749. return !check;
  17750. };
  17751. /** @hidden */
  17752. Node.prototype.hasNewParent = function (update) {
  17753. if (this._cache.parent === this.parent)
  17754. return false;
  17755. if (update)
  17756. this._cache.parent = this.parent;
  17757. return true;
  17758. };
  17759. /**
  17760. * Is this node ready to be used/rendered
  17761. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17762. * @return true if the node is ready
  17763. */
  17764. Node.prototype.isReady = function (completeCheck) {
  17765. if (completeCheck === void 0) { completeCheck = false; }
  17766. return this._isReady;
  17767. };
  17768. /**
  17769. * Is this node enabled?
  17770. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  17771. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  17772. * @return whether this node (and its parent) is enabled
  17773. */
  17774. Node.prototype.isEnabled = function (checkAncestors) {
  17775. if (checkAncestors === void 0) { checkAncestors = true; }
  17776. if (checkAncestors === false) {
  17777. return this._isEnabled;
  17778. }
  17779. if (this._isEnabled === false) {
  17780. return false;
  17781. }
  17782. if (this.parent !== undefined && this.parent !== null) {
  17783. return this.parent.isEnabled(checkAncestors);
  17784. }
  17785. return true;
  17786. };
  17787. /**
  17788. * Set the enabled state of this node
  17789. * @param value defines the new enabled state
  17790. */
  17791. Node.prototype.setEnabled = function (value) {
  17792. this._isEnabled = value;
  17793. };
  17794. /**
  17795. * Is this node a descendant of the given node?
  17796. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17797. * @param ancestor defines the parent node to inspect
  17798. * @returns a boolean indicating if this node is a descendant of the given node
  17799. */
  17800. Node.prototype.isDescendantOf = function (ancestor) {
  17801. if (this.parent) {
  17802. if (this.parent === ancestor) {
  17803. return true;
  17804. }
  17805. return this.parent.isDescendantOf(ancestor);
  17806. }
  17807. return false;
  17808. };
  17809. /** @hidden */
  17810. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17811. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17812. if (!this._children) {
  17813. return;
  17814. }
  17815. for (var index = 0; index < this._children.length; index++) {
  17816. var item = this._children[index];
  17817. if (!predicate || predicate(item)) {
  17818. results.push(item);
  17819. }
  17820. if (!directDescendantsOnly) {
  17821. item._getDescendants(results, false, predicate);
  17822. }
  17823. }
  17824. };
  17825. /**
  17826. * Will return all nodes that have this node as ascendant
  17827. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17828. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17829. * @return all children nodes of all types
  17830. */
  17831. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17832. var results = new Array();
  17833. this._getDescendants(results, directDescendantsOnly, predicate);
  17834. return results;
  17835. };
  17836. /**
  17837. * Get all child-meshes of this node
  17838. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17839. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17840. * @returns an array of {BABYLON.AbstractMesh}
  17841. */
  17842. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17843. var results = [];
  17844. this._getDescendants(results, directDescendantsOnly, function (node) {
  17845. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17846. });
  17847. return results;
  17848. };
  17849. /**
  17850. * Get all child-transformNodes of this node
  17851. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17852. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17853. * @returns an array of {BABYLON.TransformNode}
  17854. */
  17855. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17856. var results = [];
  17857. this._getDescendants(results, directDescendantsOnly, function (node) {
  17858. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17859. });
  17860. return results;
  17861. };
  17862. /**
  17863. * Get all direct children of this node
  17864. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17865. * @returns an array of {BABYLON.Node}
  17866. */
  17867. Node.prototype.getChildren = function (predicate) {
  17868. return this.getDescendants(true, predicate);
  17869. };
  17870. /** @hidden */
  17871. Node.prototype._setReady = function (state) {
  17872. if (state === this._isReady) {
  17873. return;
  17874. }
  17875. if (!state) {
  17876. this._isReady = false;
  17877. return;
  17878. }
  17879. if (this.onReady) {
  17880. this.onReady(this);
  17881. }
  17882. this._isReady = true;
  17883. };
  17884. /**
  17885. * Get an animation by name
  17886. * @param name defines the name of the animation to look for
  17887. * @returns null if not found else the requested animation
  17888. */
  17889. Node.prototype.getAnimationByName = function (name) {
  17890. for (var i = 0; i < this.animations.length; i++) {
  17891. var animation = this.animations[i];
  17892. if (animation.name === name) {
  17893. return animation;
  17894. }
  17895. }
  17896. return null;
  17897. };
  17898. /**
  17899. * Creates an animation range for this node
  17900. * @param name defines the name of the range
  17901. * @param from defines the starting key
  17902. * @param to defines the end key
  17903. */
  17904. Node.prototype.createAnimationRange = function (name, from, to) {
  17905. // check name not already in use
  17906. if (!this._ranges[name]) {
  17907. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17908. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17909. if (this.animations[i]) {
  17910. this.animations[i].createRange(name, from, to);
  17911. }
  17912. }
  17913. }
  17914. };
  17915. /**
  17916. * Delete a specific animation range
  17917. * @param name defines the name of the range to delete
  17918. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17919. */
  17920. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17921. if (deleteFrames === void 0) { deleteFrames = true; }
  17922. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17923. if (this.animations[i]) {
  17924. this.animations[i].deleteRange(name, deleteFrames);
  17925. }
  17926. }
  17927. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17928. };
  17929. /**
  17930. * Get an animation range by name
  17931. * @param name defines the name of the animation range to look for
  17932. * @returns null if not found else the requested animation range
  17933. */
  17934. Node.prototype.getAnimationRange = function (name) {
  17935. return this._ranges[name];
  17936. };
  17937. /**
  17938. * Will start the animation sequence
  17939. * @param name defines the range frames for animation sequence
  17940. * @param loop defines if the animation should loop (false by default)
  17941. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17942. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17943. * @returns the object created for this animation. If range does not exist, it will return null
  17944. */
  17945. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17946. var range = this.getAnimationRange(name);
  17947. if (!range) {
  17948. return null;
  17949. }
  17950. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17951. };
  17952. /**
  17953. * Serialize animation ranges into a JSON compatible object
  17954. * @returns serialization object
  17955. */
  17956. Node.prototype.serializeAnimationRanges = function () {
  17957. var serializationRanges = [];
  17958. for (var name in this._ranges) {
  17959. var localRange = this._ranges[name];
  17960. if (!localRange) {
  17961. continue;
  17962. }
  17963. var range = {};
  17964. range.name = name;
  17965. range.from = localRange.from;
  17966. range.to = localRange.to;
  17967. serializationRanges.push(range);
  17968. }
  17969. return serializationRanges;
  17970. };
  17971. /**
  17972. * Computes the world matrix of the node
  17973. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17974. * @returns the world matrix
  17975. */
  17976. Node.prototype.computeWorldMatrix = function (force) {
  17977. return BABYLON.Matrix.Identity();
  17978. };
  17979. /**
  17980. * Releases resources associated with this node.
  17981. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17982. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17983. */
  17984. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17985. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17986. if (!doNotRecurse) {
  17987. var nodes = this.getDescendants(true);
  17988. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17989. var node = nodes_1[_i];
  17990. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17991. }
  17992. }
  17993. else {
  17994. var transformNodes = this.getChildTransformNodes(true);
  17995. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17996. var transformNode = transformNodes_1[_a];
  17997. transformNode.parent = null;
  17998. transformNode.computeWorldMatrix(true);
  17999. }
  18000. }
  18001. this.parent = null;
  18002. // Callback
  18003. this.onDisposeObservable.notifyObservers(this);
  18004. this.onDisposeObservable.clear();
  18005. // Behaviors
  18006. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18007. var behavior = _c[_b];
  18008. behavior.detach();
  18009. }
  18010. this._behaviors = [];
  18011. this._isDisposed = true;
  18012. };
  18013. /**
  18014. * Parse animation range data from a serialization object and store them into a given node
  18015. * @param node defines where to store the animation ranges
  18016. * @param parsedNode defines the serialization object to read data from
  18017. * @param scene defines the hosting scene
  18018. */
  18019. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18020. if (parsedNode.ranges) {
  18021. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18022. var data = parsedNode.ranges[index];
  18023. node.createAnimationRange(data.name, data.from, data.to);
  18024. }
  18025. }
  18026. };
  18027. __decorate([
  18028. BABYLON.serialize()
  18029. ], Node.prototype, "name", void 0);
  18030. __decorate([
  18031. BABYLON.serialize()
  18032. ], Node.prototype, "id", void 0);
  18033. __decorate([
  18034. BABYLON.serialize()
  18035. ], Node.prototype, "uniqueId", void 0);
  18036. __decorate([
  18037. BABYLON.serialize()
  18038. ], Node.prototype, "state", void 0);
  18039. __decorate([
  18040. BABYLON.serialize()
  18041. ], Node.prototype, "metadata", void 0);
  18042. return Node;
  18043. }());
  18044. BABYLON.Node = Node;
  18045. })(BABYLON || (BABYLON = {}));
  18046. //# sourceMappingURL=babylon.node.js.map
  18047. var BABYLON;
  18048. (function (BABYLON) {
  18049. var BoundingSphere = /** @class */ (function () {
  18050. /**
  18051. * Creates a new bounding sphere
  18052. * @param min defines the minimum vector (in local space)
  18053. * @param max defines the maximum vector (in local space)
  18054. */
  18055. function BoundingSphere(min, max) {
  18056. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18057. this.reConstruct(min, max);
  18058. }
  18059. /**
  18060. * Recreates the entire bounding sphere from scratch
  18061. * @param min defines the new minimum vector (in local space)
  18062. * @param max defines the new maximum vector (in local space)
  18063. */
  18064. BoundingSphere.prototype.reConstruct = function (min, max) {
  18065. this.minimum = min.clone();
  18066. this.maximum = max.clone();
  18067. var distance = BABYLON.Vector3.Distance(min, max);
  18068. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18069. this.radius = distance * 0.5;
  18070. this.centerWorld = BABYLON.Vector3.Zero();
  18071. this._update(BABYLON.Matrix.Identity());
  18072. };
  18073. // Methods
  18074. BoundingSphere.prototype._update = function (world) {
  18075. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18076. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18077. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18078. };
  18079. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18080. for (var i = 0; i < 6; i++) {
  18081. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18082. return false;
  18083. }
  18084. return true;
  18085. };
  18086. BoundingSphere.prototype.intersectsPoint = function (point) {
  18087. var x = this.centerWorld.x - point.x;
  18088. var y = this.centerWorld.y - point.y;
  18089. var z = this.centerWorld.z - point.z;
  18090. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18091. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18092. return false;
  18093. return true;
  18094. };
  18095. // Statics
  18096. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18097. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18098. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18099. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18100. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18101. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18102. return false;
  18103. return true;
  18104. };
  18105. return BoundingSphere;
  18106. }());
  18107. BABYLON.BoundingSphere = BoundingSphere;
  18108. })(BABYLON || (BABYLON = {}));
  18109. //# sourceMappingURL=babylon.boundingSphere.js.map
  18110. var BABYLON;
  18111. (function (BABYLON) {
  18112. var BoundingBox = /** @class */ (function () {
  18113. /**
  18114. * Creates a new bounding box
  18115. * @param min defines the minimum vector (in local space)
  18116. * @param max defines the maximum vector (in local space)
  18117. */
  18118. function BoundingBox(min, max) {
  18119. this.vectorsWorld = new Array();
  18120. this.reConstruct(min, max);
  18121. }
  18122. // Methods
  18123. /**
  18124. * Recreates the entire bounding box from scratch
  18125. * @param min defines the new minimum vector (in local space)
  18126. * @param max defines the new maximum vector (in local space)
  18127. */
  18128. BoundingBox.prototype.reConstruct = function (min, max) {
  18129. this.minimum = min.clone();
  18130. this.maximum = max.clone();
  18131. // Bounding vectors
  18132. this.vectors = new Array();
  18133. this.vectors.push(this.minimum.clone());
  18134. this.vectors.push(this.maximum.clone());
  18135. this.vectors.push(this.minimum.clone());
  18136. this.vectors[2].x = this.maximum.x;
  18137. this.vectors.push(this.minimum.clone());
  18138. this.vectors[3].y = this.maximum.y;
  18139. this.vectors.push(this.minimum.clone());
  18140. this.vectors[4].z = this.maximum.z;
  18141. this.vectors.push(this.maximum.clone());
  18142. this.vectors[5].z = this.minimum.z;
  18143. this.vectors.push(this.maximum.clone());
  18144. this.vectors[6].x = this.minimum.x;
  18145. this.vectors.push(this.maximum.clone());
  18146. this.vectors[7].y = this.minimum.y;
  18147. // OBB
  18148. this.center = this.maximum.add(this.minimum).scale(0.5);
  18149. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18150. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18151. // World
  18152. for (var index = 0; index < this.vectors.length; index++) {
  18153. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18154. }
  18155. this.minimumWorld = BABYLON.Vector3.Zero();
  18156. this.maximumWorld = BABYLON.Vector3.Zero();
  18157. this.centerWorld = BABYLON.Vector3.Zero();
  18158. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18159. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18160. };
  18161. BoundingBox.prototype.getWorldMatrix = function () {
  18162. return this._worldMatrix;
  18163. };
  18164. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18165. this._worldMatrix.copyFrom(matrix);
  18166. return this;
  18167. };
  18168. BoundingBox.prototype._update = function (world) {
  18169. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18170. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18171. for (var index = 0; index < this.vectors.length; index++) {
  18172. var v = this.vectorsWorld[index];
  18173. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18174. if (v.x < this.minimumWorld.x)
  18175. this.minimumWorld.x = v.x;
  18176. if (v.y < this.minimumWorld.y)
  18177. this.minimumWorld.y = v.y;
  18178. if (v.z < this.minimumWorld.z)
  18179. this.minimumWorld.z = v.z;
  18180. if (v.x > this.maximumWorld.x)
  18181. this.maximumWorld.x = v.x;
  18182. if (v.y > this.maximumWorld.y)
  18183. this.maximumWorld.y = v.y;
  18184. if (v.z > this.maximumWorld.z)
  18185. this.maximumWorld.z = v.z;
  18186. }
  18187. // Extend
  18188. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18189. this.extendSizeWorld.scaleInPlace(0.5);
  18190. // OBB
  18191. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18192. this.centerWorld.scaleInPlace(0.5);
  18193. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18194. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18195. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18196. this._worldMatrix = world;
  18197. };
  18198. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18199. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18200. };
  18201. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18202. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18203. };
  18204. BoundingBox.prototype.intersectsPoint = function (point) {
  18205. var delta = -BABYLON.Epsilon;
  18206. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18207. return false;
  18208. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18209. return false;
  18210. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18211. return false;
  18212. return true;
  18213. };
  18214. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18215. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18216. };
  18217. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18218. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18219. return false;
  18220. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18221. return false;
  18222. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18223. return false;
  18224. return true;
  18225. };
  18226. // Statics
  18227. BoundingBox.Intersects = function (box0, box1) {
  18228. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18229. return false;
  18230. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18231. return false;
  18232. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18233. return false;
  18234. return true;
  18235. };
  18236. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18237. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18238. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18239. return (num <= (sphereRadius * sphereRadius));
  18240. };
  18241. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18242. for (var p = 0; p < 6; p++) {
  18243. for (var i = 0; i < 8; i++) {
  18244. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18245. return false;
  18246. }
  18247. }
  18248. }
  18249. return true;
  18250. };
  18251. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18252. for (var p = 0; p < 6; p++) {
  18253. var inCount = 8;
  18254. for (var i = 0; i < 8; i++) {
  18255. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18256. --inCount;
  18257. }
  18258. else {
  18259. break;
  18260. }
  18261. }
  18262. if (inCount === 0)
  18263. return false;
  18264. }
  18265. return true;
  18266. };
  18267. return BoundingBox;
  18268. }());
  18269. BABYLON.BoundingBox = BoundingBox;
  18270. })(BABYLON || (BABYLON = {}));
  18271. //# sourceMappingURL=babylon.boundingBox.js.map
  18272. var BABYLON;
  18273. (function (BABYLON) {
  18274. var computeBoxExtents = function (axis, box) {
  18275. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18276. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18277. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18278. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18279. var r = r0 + r1 + r2;
  18280. return {
  18281. min: p - r,
  18282. max: p + r
  18283. };
  18284. };
  18285. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18286. var axisOverlap = function (axis, box0, box1) {
  18287. var result0 = computeBoxExtents(axis, box0);
  18288. var result1 = computeBoxExtents(axis, box1);
  18289. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18290. };
  18291. var BoundingInfo = /** @class */ (function () {
  18292. function BoundingInfo(minimum, maximum) {
  18293. this.minimum = minimum;
  18294. this.maximum = maximum;
  18295. this._isLocked = false;
  18296. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18297. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18298. }
  18299. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18300. get: function () {
  18301. return this._isLocked;
  18302. },
  18303. set: function (value) {
  18304. this._isLocked = value;
  18305. },
  18306. enumerable: true,
  18307. configurable: true
  18308. });
  18309. // Methods
  18310. BoundingInfo.prototype.update = function (world) {
  18311. if (this._isLocked) {
  18312. return;
  18313. }
  18314. this.boundingBox._update(world);
  18315. this.boundingSphere._update(world);
  18316. };
  18317. /**
  18318. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18319. * @param center New center of the bounding info
  18320. * @param extend New extend of the bounding info
  18321. */
  18322. BoundingInfo.prototype.centerOn = function (center, extend) {
  18323. this.minimum = center.subtract(extend);
  18324. this.maximum = center.add(extend);
  18325. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18326. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18327. return this;
  18328. };
  18329. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18330. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18331. return false;
  18332. return this.boundingBox.isInFrustum(frustumPlanes);
  18333. };
  18334. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18335. /**
  18336. * Gets the world distance between the min and max points of the bounding box
  18337. */
  18338. get: function () {
  18339. var boundingBox = this.boundingBox;
  18340. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18341. return size.length();
  18342. },
  18343. enumerable: true,
  18344. configurable: true
  18345. });
  18346. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18347. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18348. };
  18349. BoundingInfo.prototype._checkCollision = function (collider) {
  18350. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18351. };
  18352. BoundingInfo.prototype.intersectsPoint = function (point) {
  18353. if (!this.boundingSphere.centerWorld) {
  18354. return false;
  18355. }
  18356. if (!this.boundingSphere.intersectsPoint(point)) {
  18357. return false;
  18358. }
  18359. if (!this.boundingBox.intersectsPoint(point)) {
  18360. return false;
  18361. }
  18362. return true;
  18363. };
  18364. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18365. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18366. return false;
  18367. }
  18368. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18369. return false;
  18370. }
  18371. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18372. return false;
  18373. }
  18374. if (!precise) {
  18375. return true;
  18376. }
  18377. var box0 = this.boundingBox;
  18378. var box1 = boundingInfo.boundingBox;
  18379. if (!axisOverlap(box0.directions[0], box0, box1))
  18380. return false;
  18381. if (!axisOverlap(box0.directions[1], box0, box1))
  18382. return false;
  18383. if (!axisOverlap(box0.directions[2], box0, box1))
  18384. return false;
  18385. if (!axisOverlap(box1.directions[0], box0, box1))
  18386. return false;
  18387. if (!axisOverlap(box1.directions[1], box0, box1))
  18388. return false;
  18389. if (!axisOverlap(box1.directions[2], box0, box1))
  18390. return false;
  18391. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18392. return false;
  18393. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18394. return false;
  18395. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18396. return false;
  18397. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18398. return false;
  18399. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18400. return false;
  18401. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18402. return false;
  18403. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18404. return false;
  18405. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18406. return false;
  18407. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18408. return false;
  18409. return true;
  18410. };
  18411. return BoundingInfo;
  18412. }());
  18413. BABYLON.BoundingInfo = BoundingInfo;
  18414. })(BABYLON || (BABYLON = {}));
  18415. //# sourceMappingURL=babylon.boundingInfo.js.map
  18416. var BABYLON;
  18417. (function (BABYLON) {
  18418. var TransformNode = /** @class */ (function (_super) {
  18419. __extends(TransformNode, _super);
  18420. function TransformNode(name, scene, isPure) {
  18421. if (scene === void 0) { scene = null; }
  18422. if (isPure === void 0) { isPure = true; }
  18423. var _this = _super.call(this, name, scene) || this;
  18424. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18425. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18426. _this._up = new BABYLON.Vector3(0, 1, 0);
  18427. _this._right = new BABYLON.Vector3(1, 0, 0);
  18428. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18429. // Properties
  18430. _this._rotation = BABYLON.Vector3.Zero();
  18431. _this._scaling = BABYLON.Vector3.One();
  18432. _this._isDirty = false;
  18433. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18434. _this.scalingDeterminant = 1;
  18435. _this.infiniteDistance = false;
  18436. _this.position = BABYLON.Vector3.Zero();
  18437. _this._localWorld = BABYLON.Matrix.Zero();
  18438. _this._worldMatrix = BABYLON.Matrix.Zero();
  18439. _this._worldMatrixDeterminant = 0;
  18440. _this._absolutePosition = BABYLON.Vector3.Zero();
  18441. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18442. _this._postMultiplyPivotMatrix = false;
  18443. _this._isWorldMatrixFrozen = false;
  18444. /**
  18445. * An event triggered after the world matrix is updated
  18446. */
  18447. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18448. _this._nonUniformScaling = false;
  18449. if (isPure) {
  18450. _this.getScene().addTransformNode(_this);
  18451. }
  18452. return _this;
  18453. }
  18454. /**
  18455. * Gets a string idenfifying the name of the class
  18456. * @returns "TransformNode" string
  18457. */
  18458. TransformNode.prototype.getClassName = function () {
  18459. return "TransformNode";
  18460. };
  18461. Object.defineProperty(TransformNode.prototype, "rotation", {
  18462. /**
  18463. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18464. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18465. * Default : (0.0, 0.0, 0.0)
  18466. */
  18467. get: function () {
  18468. return this._rotation;
  18469. },
  18470. set: function (newRotation) {
  18471. this._rotation = newRotation;
  18472. },
  18473. enumerable: true,
  18474. configurable: true
  18475. });
  18476. Object.defineProperty(TransformNode.prototype, "scaling", {
  18477. /**
  18478. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18479. * Default : (1.0, 1.0, 1.0)
  18480. */
  18481. get: function () {
  18482. return this._scaling;
  18483. },
  18484. /**
  18485. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18486. * Default : (1.0, 1.0, 1.0)
  18487. */
  18488. set: function (newScaling) {
  18489. this._scaling = newScaling;
  18490. },
  18491. enumerable: true,
  18492. configurable: true
  18493. });
  18494. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18495. /**
  18496. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18497. * It's null by default.
  18498. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18499. */
  18500. get: function () {
  18501. return this._rotationQuaternion;
  18502. },
  18503. set: function (quaternion) {
  18504. this._rotationQuaternion = quaternion;
  18505. //reset the rotation vector.
  18506. if (quaternion && this.rotation.length()) {
  18507. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18508. }
  18509. },
  18510. enumerable: true,
  18511. configurable: true
  18512. });
  18513. Object.defineProperty(TransformNode.prototype, "forward", {
  18514. /**
  18515. * The forward direction of that transform in world space.
  18516. */
  18517. get: function () {
  18518. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18519. },
  18520. enumerable: true,
  18521. configurable: true
  18522. });
  18523. Object.defineProperty(TransformNode.prototype, "up", {
  18524. /**
  18525. * The up direction of that transform in world space.
  18526. */
  18527. get: function () {
  18528. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18529. },
  18530. enumerable: true,
  18531. configurable: true
  18532. });
  18533. Object.defineProperty(TransformNode.prototype, "right", {
  18534. /**
  18535. * The right direction of that transform in world space.
  18536. */
  18537. get: function () {
  18538. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18539. },
  18540. enumerable: true,
  18541. configurable: true
  18542. });
  18543. /**
  18544. * Returns the latest update of the World matrix
  18545. * Returns a Matrix.
  18546. */
  18547. TransformNode.prototype.getWorldMatrix = function () {
  18548. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18549. this.computeWorldMatrix();
  18550. }
  18551. return this._worldMatrix;
  18552. };
  18553. /** @hidden */
  18554. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18555. return this._worldMatrixDeterminant;
  18556. };
  18557. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18558. /**
  18559. * Returns directly the latest state of the mesh World matrix.
  18560. * A Matrix is returned.
  18561. */
  18562. get: function () {
  18563. return this._worldMatrix;
  18564. },
  18565. enumerable: true,
  18566. configurable: true
  18567. });
  18568. /**
  18569. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18570. * Returns the TransformNode.
  18571. */
  18572. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18573. this._poseMatrix.copyFrom(matrix);
  18574. return this;
  18575. };
  18576. /**
  18577. * Returns the mesh Pose matrix.
  18578. * Returned object : Matrix
  18579. */
  18580. TransformNode.prototype.getPoseMatrix = function () {
  18581. return this._poseMatrix;
  18582. };
  18583. TransformNode.prototype._isSynchronized = function () {
  18584. if (this._isDirty) {
  18585. return false;
  18586. }
  18587. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18588. return false;
  18589. if (this._cache.pivotMatrixUpdated) {
  18590. return false;
  18591. }
  18592. if (this.infiniteDistance) {
  18593. return false;
  18594. }
  18595. if (!this._cache.position.equals(this.position))
  18596. return false;
  18597. if (this.rotationQuaternion) {
  18598. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18599. return false;
  18600. }
  18601. if (!this._cache.rotation.equals(this.rotation))
  18602. return false;
  18603. if (!this._cache.scaling.equals(this.scaling))
  18604. return false;
  18605. return true;
  18606. };
  18607. TransformNode.prototype._initCache = function () {
  18608. _super.prototype._initCache.call(this);
  18609. this._cache.localMatrixUpdated = false;
  18610. this._cache.position = BABYLON.Vector3.Zero();
  18611. this._cache.scaling = BABYLON.Vector3.Zero();
  18612. this._cache.rotation = BABYLON.Vector3.Zero();
  18613. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18614. this._cache.billboardMode = -1;
  18615. };
  18616. TransformNode.prototype.markAsDirty = function (property) {
  18617. if (property === "rotation") {
  18618. this.rotationQuaternion = null;
  18619. }
  18620. this._currentRenderId = Number.MAX_VALUE;
  18621. this._isDirty = true;
  18622. return this;
  18623. };
  18624. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18625. /**
  18626. * Returns the current mesh absolute position.
  18627. * Retuns a Vector3.
  18628. */
  18629. get: function () {
  18630. return this._absolutePosition;
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. /**
  18636. * Sets a new matrix to apply before all other transformation
  18637. * @param matrix defines the transform matrix
  18638. * @returns the current TransformNode
  18639. */
  18640. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18641. return this.setPivotMatrix(matrix, false);
  18642. };
  18643. /**
  18644. * Sets a new pivot matrix to the current node
  18645. * @param matrix defines the new pivot matrix to use
  18646. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  18647. * @returns the current TransformNode
  18648. */
  18649. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18650. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18651. this._pivotMatrix = matrix.clone();
  18652. this._cache.pivotMatrixUpdated = true;
  18653. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18654. if (this._postMultiplyPivotMatrix) {
  18655. if (!this._pivotMatrixInverse) {
  18656. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18657. }
  18658. else {
  18659. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18660. }
  18661. }
  18662. return this;
  18663. };
  18664. /**
  18665. * Returns the mesh pivot matrix.
  18666. * Default : Identity.
  18667. * A Matrix is returned.
  18668. */
  18669. TransformNode.prototype.getPivotMatrix = function () {
  18670. return this._pivotMatrix;
  18671. };
  18672. /**
  18673. * Prevents the World matrix to be computed any longer.
  18674. * Returns the TransformNode.
  18675. */
  18676. TransformNode.prototype.freezeWorldMatrix = function () {
  18677. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18678. this.computeWorldMatrix(true);
  18679. this._isWorldMatrixFrozen = true;
  18680. return this;
  18681. };
  18682. /**
  18683. * Allows back the World matrix computation.
  18684. * Returns the TransformNode.
  18685. */
  18686. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18687. this._isWorldMatrixFrozen = false;
  18688. this.computeWorldMatrix(true);
  18689. return this;
  18690. };
  18691. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18692. /**
  18693. * True if the World matrix has been frozen.
  18694. * Returns a boolean.
  18695. */
  18696. get: function () {
  18697. return this._isWorldMatrixFrozen;
  18698. },
  18699. enumerable: true,
  18700. configurable: true
  18701. });
  18702. /**
  18703. * Retuns the mesh absolute position in the World.
  18704. * Returns a Vector3.
  18705. */
  18706. TransformNode.prototype.getAbsolutePosition = function () {
  18707. this.computeWorldMatrix();
  18708. return this._absolutePosition;
  18709. };
  18710. /**
  18711. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18712. * Returns the TransformNode.
  18713. */
  18714. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18715. if (!absolutePosition) {
  18716. return this;
  18717. }
  18718. var absolutePositionX;
  18719. var absolutePositionY;
  18720. var absolutePositionZ;
  18721. if (absolutePosition.x === undefined) {
  18722. if (arguments.length < 3) {
  18723. return this;
  18724. }
  18725. absolutePositionX = arguments[0];
  18726. absolutePositionY = arguments[1];
  18727. absolutePositionZ = arguments[2];
  18728. }
  18729. else {
  18730. absolutePositionX = absolutePosition.x;
  18731. absolutePositionY = absolutePosition.y;
  18732. absolutePositionZ = absolutePosition.z;
  18733. }
  18734. if (this.parent) {
  18735. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18736. invertParentWorldMatrix.invert();
  18737. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18738. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18739. }
  18740. else {
  18741. this.position.x = absolutePositionX;
  18742. this.position.y = absolutePositionY;
  18743. this.position.z = absolutePositionZ;
  18744. }
  18745. return this;
  18746. };
  18747. /**
  18748. * Sets the mesh position in its local space.
  18749. * Returns the TransformNode.
  18750. */
  18751. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18752. this.computeWorldMatrix();
  18753. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18754. return this;
  18755. };
  18756. /**
  18757. * Returns the mesh position in the local space from the current World matrix values.
  18758. * Returns a new Vector3.
  18759. */
  18760. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18761. this.computeWorldMatrix();
  18762. var invLocalWorldMatrix = this._localWorld.clone();
  18763. invLocalWorldMatrix.invert();
  18764. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18765. };
  18766. /**
  18767. * Translates the mesh along the passed Vector3 in its local space.
  18768. * Returns the TransformNode.
  18769. */
  18770. TransformNode.prototype.locallyTranslate = function (vector3) {
  18771. this.computeWorldMatrix(true);
  18772. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18773. return this;
  18774. };
  18775. /**
  18776. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18777. * @param targetPoint the position (must be in same space as current mesh) to look at
  18778. * @param yawCor optional yaw (y-axis) correction in radians
  18779. * @param pitchCor optional pitch (x-axis) correction in radians
  18780. * @param rollCor optional roll (z-axis) correction in radians
  18781. * @param space the choosen space of the target
  18782. * @returns the TransformNode.
  18783. */
  18784. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18785. if (yawCor === void 0) { yawCor = 0; }
  18786. if (pitchCor === void 0) { pitchCor = 0; }
  18787. if (rollCor === void 0) { rollCor = 0; }
  18788. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18789. var dv = TransformNode._lookAtVectorCache;
  18790. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18791. targetPoint.subtractToRef(pos, dv);
  18792. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18793. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18794. var pitch = Math.atan2(dv.y, len);
  18795. if (this.rotationQuaternion) {
  18796. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18797. }
  18798. else {
  18799. this.rotation.x = pitch + pitchCor;
  18800. this.rotation.y = yaw + yawCor;
  18801. this.rotation.z = rollCor;
  18802. }
  18803. return this;
  18804. };
  18805. /**
  18806. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18807. * This Vector3 is expressed in the World space.
  18808. */
  18809. TransformNode.prototype.getDirection = function (localAxis) {
  18810. var result = BABYLON.Vector3.Zero();
  18811. this.getDirectionToRef(localAxis, result);
  18812. return result;
  18813. };
  18814. /**
  18815. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18816. * localAxis is expressed in the mesh local space.
  18817. * result is computed in the Wordl space from the mesh World matrix.
  18818. * Returns the TransformNode.
  18819. */
  18820. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18821. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18822. return this;
  18823. };
  18824. /**
  18825. * Sets a new pivot point to the current node
  18826. * @param point defines the new pivot point to use
  18827. * @param space defines if the point is in world or local space (local by default)
  18828. * @returns the current TransformNode
  18829. */
  18830. TransformNode.prototype.setPivotPoint = function (point, space) {
  18831. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18832. if (this.getScene().getRenderId() == 0) {
  18833. this.computeWorldMatrix(true);
  18834. }
  18835. var wm = this.getWorldMatrix();
  18836. if (space == BABYLON.Space.WORLD) {
  18837. var tmat = BABYLON.Tmp.Matrix[0];
  18838. wm.invertToRef(tmat);
  18839. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18840. }
  18841. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18842. };
  18843. /**
  18844. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18845. */
  18846. TransformNode.prototype.getPivotPoint = function () {
  18847. var point = BABYLON.Vector3.Zero();
  18848. this.getPivotPointToRef(point);
  18849. return point;
  18850. };
  18851. /**
  18852. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18853. * Returns the TransformNode.
  18854. */
  18855. TransformNode.prototype.getPivotPointToRef = function (result) {
  18856. result.x = -this._pivotMatrix.m[12];
  18857. result.y = -this._pivotMatrix.m[13];
  18858. result.z = -this._pivotMatrix.m[14];
  18859. return this;
  18860. };
  18861. /**
  18862. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18863. */
  18864. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18865. var point = BABYLON.Vector3.Zero();
  18866. this.getAbsolutePivotPointToRef(point);
  18867. return point;
  18868. };
  18869. /**
  18870. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18871. * Returns the TransformNode.
  18872. */
  18873. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18874. result.x = this._pivotMatrix.m[12];
  18875. result.y = this._pivotMatrix.m[13];
  18876. result.z = this._pivotMatrix.m[14];
  18877. this.getPivotPointToRef(result);
  18878. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18879. return this;
  18880. };
  18881. /**
  18882. * Defines the passed node as the parent of the current node.
  18883. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18884. * Returns the TransformNode.
  18885. */
  18886. TransformNode.prototype.setParent = function (node) {
  18887. if (node === null) {
  18888. var rotation = BABYLON.Tmp.Quaternion[0];
  18889. var position = BABYLON.Tmp.Vector3[0];
  18890. var scale = BABYLON.Tmp.Vector3[1];
  18891. if (this.parent && this.parent.computeWorldMatrix) {
  18892. this.parent.computeWorldMatrix(true);
  18893. }
  18894. this.computeWorldMatrix(true);
  18895. this.getWorldMatrix().decompose(scale, rotation, position);
  18896. if (this.rotationQuaternion) {
  18897. this.rotationQuaternion.copyFrom(rotation);
  18898. }
  18899. else {
  18900. rotation.toEulerAnglesToRef(this.rotation);
  18901. }
  18902. this.scaling.x = scale.x;
  18903. this.scaling.y = scale.y;
  18904. this.scaling.z = scale.z;
  18905. this.position.x = position.x;
  18906. this.position.y = position.y;
  18907. this.position.z = position.z;
  18908. }
  18909. else {
  18910. var rotation = BABYLON.Tmp.Quaternion[0];
  18911. var position = BABYLON.Tmp.Vector3[0];
  18912. var scale = BABYLON.Tmp.Vector3[1];
  18913. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18914. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18915. this.computeWorldMatrix(true);
  18916. node.computeWorldMatrix(true);
  18917. node.getWorldMatrix().invertToRef(invParentMatrix);
  18918. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18919. diffMatrix.decompose(scale, rotation, position);
  18920. if (this.rotationQuaternion) {
  18921. this.rotationQuaternion.copyFrom(rotation);
  18922. }
  18923. else {
  18924. rotation.toEulerAnglesToRef(this.rotation);
  18925. }
  18926. this.position.x = position.x;
  18927. this.position.y = position.y;
  18928. this.position.z = position.z;
  18929. this.scaling.x = scale.x;
  18930. this.scaling.y = scale.y;
  18931. this.scaling.z = scale.z;
  18932. }
  18933. this.parent = node;
  18934. return this;
  18935. };
  18936. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18937. get: function () {
  18938. return this._nonUniformScaling;
  18939. },
  18940. enumerable: true,
  18941. configurable: true
  18942. });
  18943. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18944. if (this._nonUniformScaling === value) {
  18945. return false;
  18946. }
  18947. this._nonUniformScaling = true;
  18948. return true;
  18949. };
  18950. /**
  18951. * Attach the current TransformNode to another TransformNode associated with a bone
  18952. * @param bone Bone affecting the TransformNode
  18953. * @param affectedTransformNode TransformNode associated with the bone
  18954. */
  18955. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18956. this._transformToBoneReferal = affectedTransformNode;
  18957. this.parent = bone;
  18958. if (bone.getWorldMatrix().determinant() < 0) {
  18959. this.scalingDeterminant *= -1;
  18960. }
  18961. return this;
  18962. };
  18963. TransformNode.prototype.detachFromBone = function () {
  18964. if (!this.parent) {
  18965. return this;
  18966. }
  18967. if (this.parent.getWorldMatrix().determinant() < 0) {
  18968. this.scalingDeterminant *= -1;
  18969. }
  18970. this._transformToBoneReferal = null;
  18971. this.parent = null;
  18972. return this;
  18973. };
  18974. /**
  18975. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18976. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18977. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18978. * The passed axis is also normalized.
  18979. * Returns the TransformNode.
  18980. */
  18981. TransformNode.prototype.rotate = function (axis, amount, space) {
  18982. axis.normalize();
  18983. if (!this.rotationQuaternion) {
  18984. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18985. this.rotation = BABYLON.Vector3.Zero();
  18986. }
  18987. var rotationQuaternion;
  18988. if (!space || space === BABYLON.Space.LOCAL) {
  18989. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18990. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18991. }
  18992. else {
  18993. if (this.parent) {
  18994. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18995. invertParentWorldMatrix.invert();
  18996. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18997. }
  18998. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18999. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19000. }
  19001. return this;
  19002. };
  19003. /**
  19004. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19005. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19006. * The passed axis is also normalized.
  19007. * Returns the TransformNode.
  19008. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19009. */
  19010. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19011. axis.normalize();
  19012. if (!this.rotationQuaternion) {
  19013. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19014. this.rotation.copyFromFloats(0, 0, 0);
  19015. }
  19016. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19017. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19018. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19019. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19020. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19021. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19022. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19023. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19024. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19025. return this;
  19026. };
  19027. /**
  19028. * Translates the mesh along the axis vector for the passed distance in the given space.
  19029. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19030. * Returns the TransformNode.
  19031. */
  19032. TransformNode.prototype.translate = function (axis, distance, space) {
  19033. var displacementVector = axis.scale(distance);
  19034. if (!space || space === BABYLON.Space.LOCAL) {
  19035. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19036. this.setPositionWithLocalVector(tempV3);
  19037. }
  19038. else {
  19039. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19040. }
  19041. return this;
  19042. };
  19043. /**
  19044. * Adds a rotation step to the mesh current rotation.
  19045. * x, y, z are Euler angles expressed in radians.
  19046. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19047. * This means this rotation is made in the mesh local space only.
  19048. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19049. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19050. * ```javascript
  19051. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19052. * ```
  19053. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19054. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  19055. * Returns the TransformNode.
  19056. */
  19057. TransformNode.prototype.addRotation = function (x, y, z) {
  19058. var rotationQuaternion;
  19059. if (this.rotationQuaternion) {
  19060. rotationQuaternion = this.rotationQuaternion;
  19061. }
  19062. else {
  19063. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19064. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19065. }
  19066. var accumulation = BABYLON.Tmp.Quaternion[0];
  19067. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19068. rotationQuaternion.multiplyInPlace(accumulation);
  19069. if (!this.rotationQuaternion) {
  19070. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19071. }
  19072. return this;
  19073. };
  19074. /**
  19075. * Computes the mesh World matrix and returns it.
  19076. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19077. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19078. * If the parameter `force`is set to `true`, the actual computation is done.
  19079. * Returns the mesh World Matrix.
  19080. */
  19081. TransformNode.prototype.computeWorldMatrix = function (force) {
  19082. if (this._isWorldMatrixFrozen) {
  19083. return this._worldMatrix;
  19084. }
  19085. if (!force && this.isSynchronized(true)) {
  19086. this._currentRenderId = this.getScene().getRenderId();
  19087. return this._worldMatrix;
  19088. }
  19089. this._cache.position.copyFrom(this.position);
  19090. this._cache.scaling.copyFrom(this.scaling);
  19091. this._cache.pivotMatrixUpdated = false;
  19092. this._cache.billboardMode = this.billboardMode;
  19093. this._currentRenderId = this.getScene().getRenderId();
  19094. this._childRenderId = this.getScene().getRenderId();
  19095. this._isDirty = false;
  19096. // Scaling
  19097. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19098. // Rotation
  19099. //rotate, if quaternion is set and rotation was used
  19100. if (this.rotationQuaternion) {
  19101. var len = this.rotation.length();
  19102. if (len) {
  19103. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19104. this.rotation.copyFromFloats(0, 0, 0);
  19105. }
  19106. }
  19107. if (this.rotationQuaternion) {
  19108. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19109. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19110. }
  19111. else {
  19112. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19113. this._cache.rotation.copyFrom(this.rotation);
  19114. }
  19115. // Translation
  19116. var camera = this.getScene().activeCamera;
  19117. if (this.infiniteDistance && !this.parent && camera) {
  19118. var cameraWorldMatrix = camera.getWorldMatrix();
  19119. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19120. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19121. }
  19122. else {
  19123. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19124. }
  19125. // Composing transformations
  19126. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19127. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19128. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19129. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19130. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19131. // Need to decompose each rotation here
  19132. var currentPosition = BABYLON.Tmp.Vector3[3];
  19133. if (this.parent && this.parent.getWorldMatrix) {
  19134. if (this._transformToBoneReferal) {
  19135. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19136. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19137. }
  19138. else {
  19139. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19140. }
  19141. }
  19142. else {
  19143. currentPosition.copyFrom(this.position);
  19144. }
  19145. currentPosition.subtractInPlace(camera.globalPosition);
  19146. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19147. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19148. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19149. }
  19150. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19151. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19152. }
  19153. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19154. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19155. }
  19156. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19157. }
  19158. else {
  19159. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19160. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19161. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19162. }
  19163. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19164. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19165. }
  19166. // Local world
  19167. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19168. // Parent
  19169. if (this.parent && this.parent.getWorldMatrix) {
  19170. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19171. if (this._transformToBoneReferal) {
  19172. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19173. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19174. }
  19175. else {
  19176. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19177. }
  19178. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19179. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19180. this._worldMatrix.copyFrom(this._localWorld);
  19181. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19182. }
  19183. else {
  19184. if (this._transformToBoneReferal) {
  19185. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19186. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19187. }
  19188. else {
  19189. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19190. }
  19191. }
  19192. this._markSyncedWithParent();
  19193. }
  19194. else {
  19195. this._worldMatrix.copyFrom(this._localWorld);
  19196. }
  19197. // Post multiply inverse of pivotMatrix
  19198. if (this._postMultiplyPivotMatrix) {
  19199. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19200. }
  19201. // Normal matrix
  19202. if (this.scaling.isNonUniform) {
  19203. this._updateNonUniformScalingState(true);
  19204. }
  19205. else if (this.parent && this.parent._nonUniformScaling) {
  19206. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19207. }
  19208. else {
  19209. this._updateNonUniformScalingState(false);
  19210. }
  19211. this._afterComputeWorldMatrix();
  19212. // Absolute position
  19213. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19214. // Callbacks
  19215. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19216. if (!this._poseMatrix) {
  19217. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19218. }
  19219. // Cache the determinant
  19220. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19221. return this._worldMatrix;
  19222. };
  19223. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19224. };
  19225. /**
  19226. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19227. * @param func: callback function to add
  19228. *
  19229. * Returns the TransformNode.
  19230. */
  19231. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19232. this.onAfterWorldMatrixUpdateObservable.add(func);
  19233. return this;
  19234. };
  19235. /**
  19236. * Removes a registered callback function.
  19237. * Returns the TransformNode.
  19238. */
  19239. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19240. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19241. return this;
  19242. };
  19243. /**
  19244. * Clone the current transform node
  19245. * Returns the new transform node
  19246. * @param name Name of the new clone
  19247. * @param newParent New parent for the clone
  19248. * @param doNotCloneChildren Do not clone children hierarchy
  19249. */
  19250. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19251. var _this = this;
  19252. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19253. result.name = name;
  19254. result.id = name;
  19255. if (newParent) {
  19256. result.parent = newParent;
  19257. }
  19258. if (!doNotCloneChildren) {
  19259. // Children
  19260. var directDescendants = this.getDescendants(true);
  19261. for (var index = 0; index < directDescendants.length; index++) {
  19262. var child = directDescendants[index];
  19263. if (child.clone) {
  19264. child.clone(name + "." + child.name, result);
  19265. }
  19266. }
  19267. }
  19268. return result;
  19269. };
  19270. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19271. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19272. serializationObject.type = this.getClassName();
  19273. // Parent
  19274. if (this.parent) {
  19275. serializationObject.parentId = this.parent.id;
  19276. }
  19277. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19278. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19279. }
  19280. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19281. serializationObject.isEnabled = this.isEnabled();
  19282. // Parent
  19283. if (this.parent) {
  19284. serializationObject.parentId = this.parent.id;
  19285. }
  19286. return serializationObject;
  19287. };
  19288. // Statics
  19289. /**
  19290. * Returns a new TransformNode object parsed from the source provided.
  19291. * The parameter `parsedMesh` is the source.
  19292. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19293. */
  19294. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19295. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19296. if (BABYLON.Tags) {
  19297. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19298. }
  19299. if (parsedTransformNode.localMatrix) {
  19300. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19301. }
  19302. else if (parsedTransformNode.pivotMatrix) {
  19303. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19304. }
  19305. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19306. // Parent
  19307. if (parsedTransformNode.parentId) {
  19308. transformNode._waitingParentId = parsedTransformNode.parentId;
  19309. }
  19310. return transformNode;
  19311. };
  19312. /**
  19313. * Releases resources associated with this transform node.
  19314. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19315. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19316. */
  19317. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19318. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19319. // Animations
  19320. this.getScene().stopAnimation(this);
  19321. // Remove from scene
  19322. this.getScene().removeTransformNode(this);
  19323. this.onAfterWorldMatrixUpdateObservable.clear();
  19324. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19325. };
  19326. // Statics
  19327. TransformNode.BILLBOARDMODE_NONE = 0;
  19328. TransformNode.BILLBOARDMODE_X = 1;
  19329. TransformNode.BILLBOARDMODE_Y = 2;
  19330. TransformNode.BILLBOARDMODE_Z = 4;
  19331. TransformNode.BILLBOARDMODE_ALL = 7;
  19332. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19333. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19334. __decorate([
  19335. BABYLON.serializeAsVector3()
  19336. ], TransformNode.prototype, "_rotation", void 0);
  19337. __decorate([
  19338. BABYLON.serializeAsQuaternion()
  19339. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19340. __decorate([
  19341. BABYLON.serializeAsVector3()
  19342. ], TransformNode.prototype, "_scaling", void 0);
  19343. __decorate([
  19344. BABYLON.serialize()
  19345. ], TransformNode.prototype, "billboardMode", void 0);
  19346. __decorate([
  19347. BABYLON.serialize()
  19348. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19349. __decorate([
  19350. BABYLON.serialize()
  19351. ], TransformNode.prototype, "infiniteDistance", void 0);
  19352. __decorate([
  19353. BABYLON.serializeAsVector3()
  19354. ], TransformNode.prototype, "position", void 0);
  19355. return TransformNode;
  19356. }(BABYLON.Node));
  19357. BABYLON.TransformNode = TransformNode;
  19358. })(BABYLON || (BABYLON = {}));
  19359. //# sourceMappingURL=babylon.transformNode.js.map
  19360. var BABYLON;
  19361. (function (BABYLON) {
  19362. /**
  19363. * Class used to store all common mesh properties
  19364. */
  19365. var AbstractMesh = /** @class */ (function (_super) {
  19366. __extends(AbstractMesh, _super);
  19367. // Constructor
  19368. /**
  19369. * Creates a new AbstractMesh
  19370. * @param name defines the name of the mesh
  19371. * @param scene defines the hosting scene
  19372. */
  19373. function AbstractMesh(name, scene) {
  19374. if (scene === void 0) { scene = null; }
  19375. var _this = _super.call(this, name, scene, false) || this;
  19376. _this._facetNb = 0; // facet number
  19377. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19378. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19379. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19380. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19381. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19382. _this._subDiv = {
  19383. max: 1,
  19384. X: 1,
  19385. Y: 1,
  19386. Z: 1
  19387. };
  19388. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19389. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19390. // Events
  19391. /**
  19392. * An event triggered when this mesh collides with another one
  19393. */
  19394. _this.onCollideObservable = new BABYLON.Observable();
  19395. /**
  19396. * An event triggered when the collision's position changes
  19397. */
  19398. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19399. /**
  19400. * An event triggered when material is changed
  19401. */
  19402. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19403. // Properties
  19404. /**
  19405. * Gets or sets the orientation for POV movement & rotation
  19406. */
  19407. _this.definedFacingForward = true;
  19408. /**
  19409. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19410. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19411. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19412. * @see http://doc.babylonjs.com/features/occlusionquery
  19413. */
  19414. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19415. /**
  19416. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19417. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19418. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19419. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19420. * @see http://doc.babylonjs.com/features/occlusionquery
  19421. */
  19422. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19423. /**
  19424. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19425. * The default value is -1 which means don't break the query and wait till the result
  19426. * @see http://doc.babylonjs.com/features/occlusionquery
  19427. */
  19428. _this.occlusionRetryCount = -1;
  19429. _this._occlusionInternalRetryCounter = 0;
  19430. _this._isOccluded = false;
  19431. _this._isOcclusionQueryInProgress = false;
  19432. _this._visibility = 1.0;
  19433. /** Gets or sets the alpha index used to sort transparent meshes
  19434. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19435. */
  19436. _this.alphaIndex = Number.MAX_VALUE;
  19437. /**
  19438. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19439. */
  19440. _this.isVisible = true;
  19441. /**
  19442. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19443. */
  19444. _this.isPickable = true;
  19445. /**
  19446. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19447. */
  19448. _this.showBoundingBox = false;
  19449. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19450. _this.showSubMeshesBoundingBox = false;
  19451. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19452. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19453. */
  19454. _this.isBlocker = false;
  19455. /**
  19456. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19457. */
  19458. _this.enablePointerMoveEvents = false;
  19459. /**
  19460. * Specifies the rendering group id for this mesh (0 by default)
  19461. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19462. */
  19463. _this.renderingGroupId = 0;
  19464. _this._receiveShadows = false;
  19465. /**
  19466. * Gets or sets a boolean indicating if the outline must be rendered as well
  19467. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19468. */
  19469. _this.renderOutline = false;
  19470. /** Defines color to use when rendering outline */
  19471. _this.outlineColor = BABYLON.Color3.Red();
  19472. /** Define width to use when rendering outline */
  19473. _this.outlineWidth = 0.02;
  19474. /**
  19475. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19476. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19477. */
  19478. _this.renderOverlay = false;
  19479. /** Defines color to use when rendering overlay */
  19480. _this.overlayColor = BABYLON.Color3.Red();
  19481. /** Defines alpha to use when rendering overlay */
  19482. _this.overlayAlpha = 0.5;
  19483. _this._hasVertexAlpha = false;
  19484. _this._useVertexColors = true;
  19485. _this._computeBonesUsingShaders = true;
  19486. _this._numBoneInfluencers = 4;
  19487. _this._applyFog = true;
  19488. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19489. _this.useOctreeForRenderingSelection = true;
  19490. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19491. _this.useOctreeForPicking = true;
  19492. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19493. _this.useOctreeForCollisions = true;
  19494. _this._layerMask = 0x0FFFFFFF;
  19495. /**
  19496. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19497. */
  19498. _this.alwaysSelectAsActiveMesh = false;
  19499. /**
  19500. * Gets or sets the current action manager
  19501. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19502. */
  19503. _this.actionManager = null;
  19504. /**
  19505. * Gets or sets impostor used for physic simulation
  19506. * @see http://doc.babylonjs.com/features/physics_engine
  19507. */
  19508. _this.physicsImpostor = null;
  19509. // Collisions
  19510. _this._checkCollisions = false;
  19511. _this._collisionMask = -1;
  19512. _this._collisionGroup = -1;
  19513. /**
  19514. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19515. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19516. */
  19517. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19518. /**
  19519. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19520. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19521. */
  19522. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19523. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19524. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19525. // Edges
  19526. /**
  19527. * Defines edge width used when edgesRenderer is enabled
  19528. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19529. */
  19530. _this.edgesWidth = 1;
  19531. /**
  19532. * Defines edge color used when edgesRenderer is enabled
  19533. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19534. */
  19535. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19536. // Cache
  19537. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19538. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19539. /** @hidden */
  19540. _this._renderId = 0;
  19541. /** @hidden */
  19542. _this._intersectionsInProgress = new Array();
  19543. /** @hidden */
  19544. _this._unIndexed = false;
  19545. /** @hidden */
  19546. _this._lightSources = new Array();
  19547. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19548. if (collidedMesh === void 0) { collidedMesh = null; }
  19549. //TODO move this to the collision coordinator!
  19550. if (_this.getScene().workerCollisions)
  19551. newPosition.multiplyInPlace(_this._collider._radius);
  19552. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19553. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19554. _this.position.addInPlace(_this._diffPositionForCollisions);
  19555. }
  19556. if (collidedMesh) {
  19557. _this.onCollideObservable.notifyObservers(collidedMesh);
  19558. }
  19559. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19560. };
  19561. _this.getScene().addMesh(_this);
  19562. _this._resyncLightSources();
  19563. return _this;
  19564. }
  19565. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19566. /**
  19567. * No billboard
  19568. */
  19569. get: function () {
  19570. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19571. },
  19572. enumerable: true,
  19573. configurable: true
  19574. });
  19575. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19576. /** Billboard on X axis */
  19577. get: function () {
  19578. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19579. },
  19580. enumerable: true,
  19581. configurable: true
  19582. });
  19583. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19584. /** Billboard on Y axis */
  19585. get: function () {
  19586. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19592. /** Billboard on Z axis */
  19593. get: function () {
  19594. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19595. },
  19596. enumerable: true,
  19597. configurable: true
  19598. });
  19599. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19600. /** Billboard on all axes */
  19601. get: function () {
  19602. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19603. },
  19604. enumerable: true,
  19605. configurable: true
  19606. });
  19607. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19608. /**
  19609. * Gets the number of facets in the mesh
  19610. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19611. */
  19612. get: function () {
  19613. return this._facetNb;
  19614. },
  19615. enumerable: true,
  19616. configurable: true
  19617. });
  19618. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19619. /**
  19620. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19621. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19622. */
  19623. get: function () {
  19624. return this._partitioningSubdivisions;
  19625. },
  19626. set: function (nb) {
  19627. this._partitioningSubdivisions = nb;
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19633. /**
  19634. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19635. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19636. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19637. */
  19638. get: function () {
  19639. return this._partitioningBBoxRatio;
  19640. },
  19641. set: function (ratio) {
  19642. this._partitioningBBoxRatio = ratio;
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19648. /**
  19649. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19650. * Works only for updatable meshes.
  19651. * Doesn't work with multi-materials
  19652. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19653. */
  19654. get: function () {
  19655. return this._facetDepthSort;
  19656. },
  19657. set: function (sort) {
  19658. this._facetDepthSort = sort;
  19659. },
  19660. enumerable: true,
  19661. configurable: true
  19662. });
  19663. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19664. /**
  19665. * The location (Vector3) where the facet depth sort must be computed from.
  19666. * By default, the active camera position.
  19667. * Used only when facet depth sort is enabled
  19668. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19669. */
  19670. get: function () {
  19671. return this._facetDepthSortFrom;
  19672. },
  19673. set: function (location) {
  19674. this._facetDepthSortFrom = location;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19680. /**
  19681. * gets a boolean indicating if facetData is enabled
  19682. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19683. */
  19684. get: function () {
  19685. return this._facetDataEnabled;
  19686. },
  19687. enumerable: true,
  19688. configurable: true
  19689. });
  19690. /** @hidden */
  19691. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19692. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19693. return false;
  19694. }
  19695. this._markSubMeshesAsMiscDirty();
  19696. return true;
  19697. };
  19698. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19699. /** Set a function to call when this mesh collides with another one */
  19700. set: function (callback) {
  19701. if (this._onCollideObserver) {
  19702. this.onCollideObservable.remove(this._onCollideObserver);
  19703. }
  19704. this._onCollideObserver = this.onCollideObservable.add(callback);
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19710. /** Set a function to call when the collision's position changes */
  19711. set: function (callback) {
  19712. if (this._onCollisionPositionChangeObserver) {
  19713. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19714. }
  19715. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19721. /**
  19722. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19723. * @see http://doc.babylonjs.com/features/occlusionquery
  19724. */
  19725. get: function () {
  19726. return this._isOccluded;
  19727. },
  19728. set: function (value) {
  19729. this._isOccluded = value;
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19735. /**
  19736. * Flag to check the progress status of the query
  19737. * @see http://doc.babylonjs.com/features/occlusionquery
  19738. */
  19739. get: function () {
  19740. return this._isOcclusionQueryInProgress;
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19746. /**
  19747. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19748. */
  19749. get: function () {
  19750. return this._visibility;
  19751. },
  19752. /**
  19753. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19754. */
  19755. set: function (value) {
  19756. if (this._visibility === value) {
  19757. return;
  19758. }
  19759. this._visibility = value;
  19760. this._markSubMeshesAsMiscDirty();
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(AbstractMesh.prototype, "material", {
  19766. /** Gets or sets current material */
  19767. get: function () {
  19768. return this._material;
  19769. },
  19770. set: function (value) {
  19771. if (this._material === value) {
  19772. return;
  19773. }
  19774. this._material = value;
  19775. if (this.onMaterialChangedObservable.hasObservers) {
  19776. this.onMaterialChangedObservable.notifyObservers(this);
  19777. }
  19778. if (!this.subMeshes) {
  19779. return;
  19780. }
  19781. this._unBindEffect();
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19787. /**
  19788. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19789. * @see http://doc.babylonjs.com/babylon101/shadows
  19790. */
  19791. get: function () {
  19792. return this._receiveShadows;
  19793. },
  19794. set: function (value) {
  19795. if (this._receiveShadows === value) {
  19796. return;
  19797. }
  19798. this._receiveShadows = value;
  19799. this._markSubMeshesAsLightDirty();
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19805. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19806. get: function () {
  19807. return this._hasVertexAlpha;
  19808. },
  19809. set: function (value) {
  19810. if (this._hasVertexAlpha === value) {
  19811. return;
  19812. }
  19813. this._hasVertexAlpha = value;
  19814. this._markSubMeshesAsAttributesDirty();
  19815. this._markSubMeshesAsMiscDirty();
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19821. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19822. get: function () {
  19823. return this._useVertexColors;
  19824. },
  19825. set: function (value) {
  19826. if (this._useVertexColors === value) {
  19827. return;
  19828. }
  19829. this._useVertexColors = value;
  19830. this._markSubMeshesAsAttributesDirty();
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19836. /**
  19837. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19838. */
  19839. get: function () {
  19840. return this._computeBonesUsingShaders;
  19841. },
  19842. set: function (value) {
  19843. if (this._computeBonesUsingShaders === value) {
  19844. return;
  19845. }
  19846. this._computeBonesUsingShaders = value;
  19847. this._markSubMeshesAsAttributesDirty();
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19853. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19854. get: function () {
  19855. return this._numBoneInfluencers;
  19856. },
  19857. set: function (value) {
  19858. if (this._numBoneInfluencers === value) {
  19859. return;
  19860. }
  19861. this._numBoneInfluencers = value;
  19862. this._markSubMeshesAsAttributesDirty();
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19868. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19869. get: function () {
  19870. return this._applyFog;
  19871. },
  19872. set: function (value) {
  19873. if (this._applyFog === value) {
  19874. return;
  19875. }
  19876. this._applyFog = value;
  19877. this._markSubMeshesAsMiscDirty();
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19883. /**
  19884. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19885. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19886. */
  19887. get: function () {
  19888. return this._layerMask;
  19889. },
  19890. set: function (value) {
  19891. if (value === this._layerMask) {
  19892. return;
  19893. }
  19894. this._layerMask = value;
  19895. this._resyncLightSources();
  19896. },
  19897. enumerable: true,
  19898. configurable: true
  19899. });
  19900. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19901. /**
  19902. * Gets or sets a collision mask used to mask collisions (default is -1).
  19903. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19904. */
  19905. get: function () {
  19906. return this._collisionMask;
  19907. },
  19908. set: function (mask) {
  19909. this._collisionMask = !isNaN(mask) ? mask : -1;
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19915. /**
  19916. * Gets or sets the current collision group mask (-1 by default).
  19917. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19918. */
  19919. get: function () {
  19920. return this._collisionGroup;
  19921. },
  19922. set: function (mask) {
  19923. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19924. },
  19925. enumerable: true,
  19926. configurable: true
  19927. });
  19928. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19929. /** @hidden */
  19930. get: function () {
  19931. return null;
  19932. },
  19933. enumerable: true,
  19934. configurable: true
  19935. });
  19936. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19937. get: function () {
  19938. return this._skeleton;
  19939. },
  19940. /**
  19941. * Gets or sets a skeleton to apply skining transformations
  19942. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19943. */
  19944. set: function (value) {
  19945. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19946. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19947. }
  19948. if (value && value.needInitialSkinMatrix) {
  19949. value._registerMeshWithPoseMatrix(this);
  19950. }
  19951. this._skeleton = value;
  19952. if (!this._skeleton) {
  19953. this._bonesTransformMatrices = null;
  19954. }
  19955. this._markSubMeshesAsAttributesDirty();
  19956. },
  19957. enumerable: true,
  19958. configurable: true
  19959. });
  19960. /**
  19961. * Returns the string "AbstractMesh"
  19962. * @returns "AbstractMesh"
  19963. */
  19964. AbstractMesh.prototype.getClassName = function () {
  19965. return "AbstractMesh";
  19966. };
  19967. /**
  19968. * Gets a string representation of the current mesh
  19969. * @param fullDetails defines a boolean indicating if full details must be included
  19970. * @returns a string representation of the current mesh
  19971. */
  19972. AbstractMesh.prototype.toString = function (fullDetails) {
  19973. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19974. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19975. if (this._skeleton) {
  19976. ret += ", skeleton: " + this._skeleton.name;
  19977. }
  19978. if (fullDetails) {
  19979. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19980. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19981. }
  19982. return ret;
  19983. };
  19984. /** @hidden */
  19985. AbstractMesh.prototype._rebuild = function () {
  19986. if (this._occlusionQuery) {
  19987. this._occlusionQuery = null;
  19988. }
  19989. if (this._edgesRenderer) {
  19990. this._edgesRenderer._rebuild();
  19991. }
  19992. if (!this.subMeshes) {
  19993. return;
  19994. }
  19995. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19996. var subMesh = _a[_i];
  19997. subMesh._rebuild();
  19998. }
  19999. };
  20000. /** @hidden */
  20001. AbstractMesh.prototype._resyncLightSources = function () {
  20002. this._lightSources.length = 0;
  20003. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20004. var light = _a[_i];
  20005. if (!light.isEnabled()) {
  20006. continue;
  20007. }
  20008. if (light.canAffectMesh(this)) {
  20009. this._lightSources.push(light);
  20010. }
  20011. }
  20012. this._markSubMeshesAsLightDirty();
  20013. };
  20014. /** @hidden */
  20015. AbstractMesh.prototype._resyncLighSource = function (light) {
  20016. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20017. var index = this._lightSources.indexOf(light);
  20018. if (index === -1) {
  20019. if (!isIn) {
  20020. return;
  20021. }
  20022. this._lightSources.push(light);
  20023. }
  20024. else {
  20025. if (isIn) {
  20026. return;
  20027. }
  20028. this._lightSources.splice(index, 1);
  20029. }
  20030. this._markSubMeshesAsLightDirty();
  20031. };
  20032. /** @hidden */
  20033. AbstractMesh.prototype._unBindEffect = function () {
  20034. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20035. var subMesh = _a[_i];
  20036. subMesh.setEffect(null);
  20037. }
  20038. };
  20039. /** @hidden */
  20040. AbstractMesh.prototype._removeLightSource = function (light) {
  20041. var index = this._lightSources.indexOf(light);
  20042. if (index === -1) {
  20043. return;
  20044. }
  20045. this._lightSources.splice(index, 1);
  20046. this._markSubMeshesAsLightDirty();
  20047. };
  20048. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20049. if (!this.subMeshes) {
  20050. return;
  20051. }
  20052. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20053. var subMesh = _a[_i];
  20054. if (subMesh._materialDefines) {
  20055. func(subMesh._materialDefines);
  20056. }
  20057. }
  20058. };
  20059. /** @hidden */
  20060. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20061. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20062. };
  20063. /** @hidden */
  20064. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20065. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20066. };
  20067. /** @hidden */
  20068. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20069. if (!this.subMeshes) {
  20070. return;
  20071. }
  20072. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20073. var subMesh = _a[_i];
  20074. var material = subMesh.getMaterial();
  20075. if (material) {
  20076. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20077. }
  20078. }
  20079. };
  20080. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20081. /**
  20082. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20083. */
  20084. get: function () {
  20085. return this._scaling;
  20086. },
  20087. set: function (newScaling) {
  20088. this._scaling = newScaling;
  20089. if (this.physicsImpostor) {
  20090. this.physicsImpostor.forceUpdate();
  20091. }
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. // Methods
  20097. /**
  20098. * Disables the mesh edge rendering mode
  20099. * @returns the currentAbstractMesh
  20100. */
  20101. AbstractMesh.prototype.disableEdgesRendering = function () {
  20102. if (this._edgesRenderer) {
  20103. this._edgesRenderer.dispose();
  20104. this._edgesRenderer = null;
  20105. }
  20106. return this;
  20107. };
  20108. /**
  20109. * Enables the edge rendering mode on the mesh.
  20110. * This mode makes the mesh edges visible
  20111. * @param epsilon defines the maximal distance between two angles to detect a face
  20112. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20113. * @returns the currentAbstractMesh
  20114. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20115. */
  20116. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20117. if (epsilon === void 0) { epsilon = 0.95; }
  20118. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20119. this.disableEdgesRendering();
  20120. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20121. return this;
  20122. };
  20123. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20124. /**
  20125. * Returns true if the mesh is blocked. Implemented by child classes
  20126. */
  20127. get: function () {
  20128. return false;
  20129. },
  20130. enumerable: true,
  20131. configurable: true
  20132. });
  20133. /**
  20134. * Returns the mesh itself by default. Implemented by child classes
  20135. * @param camera defines the camera to use to pick the right LOD level
  20136. * @returns the currentAbstractMesh
  20137. */
  20138. AbstractMesh.prototype.getLOD = function (camera) {
  20139. return this;
  20140. };
  20141. /**
  20142. * Returns 0 by default. Implemented by child classes
  20143. * @returns an integer
  20144. */
  20145. AbstractMesh.prototype.getTotalVertices = function () {
  20146. return 0;
  20147. };
  20148. /**
  20149. * Returns null by default. Implemented by child classes
  20150. * @returns null
  20151. */
  20152. AbstractMesh.prototype.getIndices = function () {
  20153. return null;
  20154. };
  20155. /**
  20156. * Returns the array of the requested vertex data kind. Implemented by child classes
  20157. * @param kind defines the vertex data kind to use
  20158. * @returns null
  20159. */
  20160. AbstractMesh.prototype.getVerticesData = function (kind) {
  20161. return null;
  20162. };
  20163. /**
  20164. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20165. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20166. * Note that a new underlying VertexBuffer object is created each call.
  20167. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20168. * @param kind defines vertex data kind:
  20169. * * BABYLON.VertexBuffer.PositionKind
  20170. * * BABYLON.VertexBuffer.UVKind
  20171. * * BABYLON.VertexBuffer.UV2Kind
  20172. * * BABYLON.VertexBuffer.UV3Kind
  20173. * * BABYLON.VertexBuffer.UV4Kind
  20174. * * BABYLON.VertexBuffer.UV5Kind
  20175. * * BABYLON.VertexBuffer.UV6Kind
  20176. * * BABYLON.VertexBuffer.ColorKind
  20177. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20178. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20179. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20180. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20181. * @param data defines the data source
  20182. * @param updatable defines if the data must be flagged as updatable (or static)
  20183. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20184. * @returns the current mesh
  20185. */
  20186. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20187. return this;
  20188. };
  20189. /**
  20190. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20191. * If the mesh has no geometry, it is simply returned as it is.
  20192. * @param kind defines vertex data kind:
  20193. * * BABYLON.VertexBuffer.PositionKind
  20194. * * BABYLON.VertexBuffer.UVKind
  20195. * * BABYLON.VertexBuffer.UV2Kind
  20196. * * BABYLON.VertexBuffer.UV3Kind
  20197. * * BABYLON.VertexBuffer.UV4Kind
  20198. * * BABYLON.VertexBuffer.UV5Kind
  20199. * * BABYLON.VertexBuffer.UV6Kind
  20200. * * BABYLON.VertexBuffer.ColorKind
  20201. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20202. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20203. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20204. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20205. * @param data defines the data source
  20206. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20207. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20208. * @returns the current mesh
  20209. */
  20210. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20211. return this;
  20212. };
  20213. /**
  20214. * Sets the mesh indices,
  20215. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20216. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20217. * @param totalVertices Defines the total number of vertices
  20218. * @returns the current mesh
  20219. */
  20220. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20221. return this;
  20222. };
  20223. /**
  20224. * Gets a boolean indicating if specific vertex data is present
  20225. * @param kind defines the vertex data kind to use
  20226. * @returns true is data kind is present
  20227. */
  20228. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20229. return false;
  20230. };
  20231. /**
  20232. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20233. * @returns a BoundingInfo
  20234. */
  20235. AbstractMesh.prototype.getBoundingInfo = function () {
  20236. if (this._masterMesh) {
  20237. return this._masterMesh.getBoundingInfo();
  20238. }
  20239. if (!this._boundingInfo) {
  20240. // this._boundingInfo is being created here
  20241. this._updateBoundingInfo();
  20242. }
  20243. // cannot be null.
  20244. return this._boundingInfo;
  20245. };
  20246. /**
  20247. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20248. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20249. * @returns the current mesh
  20250. */
  20251. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20252. if (includeDescendants === void 0) { includeDescendants = true; }
  20253. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20254. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20255. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20256. if (maxDimension === 0) {
  20257. return this;
  20258. }
  20259. var scale = 1 / maxDimension;
  20260. this.scaling.scaleInPlace(scale);
  20261. return this;
  20262. };
  20263. /**
  20264. * Overwrite the current bounding info
  20265. * @param boundingInfo defines the new bounding info
  20266. * @returns the current mesh
  20267. */
  20268. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20269. this._boundingInfo = boundingInfo;
  20270. return this;
  20271. };
  20272. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20273. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20274. get: function () {
  20275. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20276. },
  20277. enumerable: true,
  20278. configurable: true
  20279. });
  20280. /** @hidden */
  20281. AbstractMesh.prototype._preActivate = function () {
  20282. };
  20283. /** @hidden */
  20284. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20285. };
  20286. /** @hidden */
  20287. AbstractMesh.prototype._activate = function (renderId) {
  20288. this._renderId = renderId;
  20289. };
  20290. /**
  20291. * Gets the current world matrix
  20292. * @returns a Matrix
  20293. */
  20294. AbstractMesh.prototype.getWorldMatrix = function () {
  20295. if (this._masterMesh) {
  20296. return this._masterMesh.getWorldMatrix();
  20297. }
  20298. return _super.prototype.getWorldMatrix.call(this);
  20299. };
  20300. /** @hidden */
  20301. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20302. if (this._masterMesh) {
  20303. return this._masterMesh._getWorldMatrixDeterminant();
  20304. }
  20305. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20306. };
  20307. // ================================== Point of View Movement =================================
  20308. /**
  20309. * Perform relative position change from the point of view of behind the front of the mesh.
  20310. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20311. * Supports definition of mesh facing forward or backward
  20312. * @param amountRight defines the distance on the right axis
  20313. * @param amountUp defines the distance on the up axis
  20314. * @param amountForward defines the distance on the forward axis
  20315. * @returns the current mesh
  20316. */
  20317. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20318. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20319. return this;
  20320. };
  20321. /**
  20322. * Calculate relative position change from the point of view of behind the front of the mesh.
  20323. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20324. * Supports definition of mesh facing forward or backward
  20325. * @param amountRight defines the distance on the right axis
  20326. * @param amountUp defines the distance on the up axis
  20327. * @param amountForward defines the distance on the forward axis
  20328. * @returns the new displacement vector
  20329. */
  20330. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20331. var rotMatrix = new BABYLON.Matrix();
  20332. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20333. rotQuaternion.toRotationMatrix(rotMatrix);
  20334. var translationDelta = BABYLON.Vector3.Zero();
  20335. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20336. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20337. return translationDelta;
  20338. };
  20339. // ================================== Point of View Rotation =================================
  20340. /**
  20341. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20342. * Supports definition of mesh facing forward or backward
  20343. * @param flipBack defines the flip
  20344. * @param twirlClockwise defines the twirl
  20345. * @param tiltRight defines the tilt
  20346. * @returns the current mesh
  20347. */
  20348. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20349. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20350. return this;
  20351. };
  20352. /**
  20353. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20354. * Supports definition of mesh facing forward or backward.
  20355. * @param flipBack defines the flip
  20356. * @param twirlClockwise defines the twirl
  20357. * @param tiltRight defines the tilt
  20358. * @returns the new rotation vector
  20359. */
  20360. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20361. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20362. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20363. };
  20364. /**
  20365. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20366. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20367. * @returns the new bounding vectors
  20368. */
  20369. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20370. if (includeDescendants === void 0) { includeDescendants = true; }
  20371. // Ensures that all world matrix will be recomputed.
  20372. this.getScene().incrementRenderId();
  20373. this.computeWorldMatrix(true);
  20374. var min;
  20375. var max;
  20376. var boundingInfo = this.getBoundingInfo();
  20377. if (!this.subMeshes) {
  20378. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20379. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20380. }
  20381. else {
  20382. min = boundingInfo.boundingBox.minimumWorld;
  20383. max = boundingInfo.boundingBox.maximumWorld;
  20384. }
  20385. if (includeDescendants) {
  20386. var descendants = this.getDescendants(false);
  20387. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20388. var descendant = descendants_1[_i];
  20389. var childMesh = descendant;
  20390. childMesh.computeWorldMatrix(true);
  20391. //make sure we have the needed params to get mix and max
  20392. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20393. continue;
  20394. }
  20395. var childBoundingInfo = childMesh.getBoundingInfo();
  20396. var boundingBox = childBoundingInfo.boundingBox;
  20397. var minBox = boundingBox.minimumWorld;
  20398. var maxBox = boundingBox.maximumWorld;
  20399. BABYLON.Tools.CheckExtends(minBox, min, max);
  20400. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20401. }
  20402. }
  20403. return {
  20404. min: min,
  20405. max: max
  20406. };
  20407. };
  20408. /** @hidden */
  20409. AbstractMesh.prototype._updateBoundingInfo = function () {
  20410. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20411. this._boundingInfo.update(this.worldMatrixFromCache);
  20412. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20413. return this;
  20414. };
  20415. /** @hidden */
  20416. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20417. if (!this.subMeshes) {
  20418. return this;
  20419. }
  20420. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20421. var subMesh = this.subMeshes[subIndex];
  20422. if (!subMesh.IsGlobal) {
  20423. subMesh.updateBoundingInfo(matrix);
  20424. }
  20425. }
  20426. return this;
  20427. };
  20428. /** @hidden */
  20429. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20430. // Bounding info
  20431. this._updateBoundingInfo();
  20432. };
  20433. /**
  20434. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20435. * A mesh is in the frustum if its bounding box intersects the frustum
  20436. * @param frustumPlanes defines the frustum to test
  20437. * @returns true if the mesh is in the frustum planes
  20438. */
  20439. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20440. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20441. };
  20442. /**
  20443. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20444. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20445. * @param frustumPlanes defines the frustum to test
  20446. * @returns true if the mesh is completely in the frustum planes
  20447. */
  20448. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20449. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20450. };
  20451. /**
  20452. * True if the mesh intersects another mesh or a SolidParticle object
  20453. * @param mesh defines a target mesh or SolidParticle to test
  20454. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20455. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20456. * @returns true if there is an intersection
  20457. */
  20458. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20459. if (precise === void 0) { precise = false; }
  20460. if (!this._boundingInfo || !mesh._boundingInfo) {
  20461. return false;
  20462. }
  20463. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20464. return true;
  20465. }
  20466. if (includeDescendants) {
  20467. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20468. var child = _a[_i];
  20469. if (child.intersectsMesh(mesh, precise, true)) {
  20470. return true;
  20471. }
  20472. }
  20473. }
  20474. return false;
  20475. };
  20476. /**
  20477. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20478. * @param point defines the point to test
  20479. * @returns true if there is an intersection
  20480. */
  20481. AbstractMesh.prototype.intersectsPoint = function (point) {
  20482. if (!this._boundingInfo) {
  20483. return false;
  20484. }
  20485. return this._boundingInfo.intersectsPoint(point);
  20486. };
  20487. /**
  20488. * Gets the current physics impostor
  20489. * @see http://doc.babylonjs.com/features/physics_engine
  20490. * @returns a physics impostor or null
  20491. */
  20492. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20493. return this.physicsImpostor;
  20494. };
  20495. /**
  20496. * Gets the position of the current mesh in camera space
  20497. * @param camera defines the camera to use
  20498. * @returns a position
  20499. */
  20500. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20501. if (camera === void 0) { camera = null; }
  20502. if (!camera) {
  20503. camera = this.getScene().activeCamera;
  20504. }
  20505. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20506. };
  20507. /**
  20508. * Returns the distance from the mesh to the active camera
  20509. * @param camera defines the camera to use
  20510. * @returns the distance
  20511. */
  20512. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20513. if (camera === void 0) { camera = null; }
  20514. if (!camera) {
  20515. camera = this.getScene().activeCamera;
  20516. }
  20517. return this.absolutePosition.subtract(camera.position).length();
  20518. };
  20519. /**
  20520. * Apply a physic impulse to the mesh
  20521. * @param force defines the force to apply
  20522. * @param contactPoint defines where to apply the force
  20523. * @returns the current mesh
  20524. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20525. */
  20526. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20527. if (!this.physicsImpostor) {
  20528. return this;
  20529. }
  20530. this.physicsImpostor.applyImpulse(force, contactPoint);
  20531. return this;
  20532. };
  20533. /**
  20534. * Creates a physic joint between two meshes
  20535. * @param otherMesh defines the other mesh to use
  20536. * @param pivot1 defines the pivot to use on this mesh
  20537. * @param pivot2 defines the pivot to use on the other mesh
  20538. * @param options defines additional options (can be plugin dependent)
  20539. * @returns the current mesh
  20540. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20541. */
  20542. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20543. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20544. return this;
  20545. }
  20546. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20547. mainPivot: pivot1,
  20548. connectedPivot: pivot2,
  20549. nativeParams: options
  20550. });
  20551. return this;
  20552. };
  20553. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20554. // Collisions
  20555. /**
  20556. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20557. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20558. */
  20559. get: function () {
  20560. return this._checkCollisions;
  20561. },
  20562. set: function (collisionEnabled) {
  20563. this._checkCollisions = collisionEnabled;
  20564. if (this.getScene().workerCollisions) {
  20565. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20566. }
  20567. },
  20568. enumerable: true,
  20569. configurable: true
  20570. });
  20571. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20572. /**
  20573. * Gets Collider object used to compute collisions (not physics)
  20574. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20575. */
  20576. get: function () {
  20577. return this._collider;
  20578. },
  20579. enumerable: true,
  20580. configurable: true
  20581. });
  20582. /**
  20583. * Move the mesh using collision engine
  20584. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20585. * @param displacement defines the requested displacement vector
  20586. * @returns the current mesh
  20587. */
  20588. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20589. var globalPosition = this.getAbsolutePosition();
  20590. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20591. if (!this._collider) {
  20592. this._collider = new BABYLON.Collider();
  20593. }
  20594. this._collider._radius = this.ellipsoid;
  20595. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20596. return this;
  20597. };
  20598. // Submeshes octree
  20599. /**
  20600. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20601. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20602. * @param maxCapacity defines the maximum size of each block (64 by default)
  20603. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20604. * @returns the new octree
  20605. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20606. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20607. */
  20608. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20609. if (maxCapacity === void 0) { maxCapacity = 64; }
  20610. if (maxDepth === void 0) { maxDepth = 2; }
  20611. if (!this._submeshesOctree) {
  20612. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20613. }
  20614. this.computeWorldMatrix(true);
  20615. var boundingInfo = this.getBoundingInfo();
  20616. // Update octree
  20617. var bbox = boundingInfo.boundingBox;
  20618. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20619. return this._submeshesOctree;
  20620. };
  20621. // Collisions
  20622. /** @hidden */
  20623. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20624. this._generatePointsArray();
  20625. if (!this._positions) {
  20626. return this;
  20627. }
  20628. // Transformation
  20629. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20630. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20631. subMesh._lastColliderWorldVertices = [];
  20632. subMesh._trianglePlanes = [];
  20633. var start = subMesh.verticesStart;
  20634. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20635. for (var i = start; i < end; i++) {
  20636. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20637. }
  20638. }
  20639. // Collide
  20640. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20641. if (collider.collisionFound) {
  20642. collider.collidedMesh = this;
  20643. }
  20644. return this;
  20645. };
  20646. /** @hidden */
  20647. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20648. var subMeshes;
  20649. var len;
  20650. // Octrees
  20651. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20652. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20653. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20654. len = intersections.length;
  20655. subMeshes = intersections.data;
  20656. }
  20657. else {
  20658. subMeshes = this.subMeshes;
  20659. len = subMeshes.length;
  20660. }
  20661. for (var index = 0; index < len; index++) {
  20662. var subMesh = subMeshes[index];
  20663. // Bounding test
  20664. if (len > 1 && !subMesh._checkCollision(collider))
  20665. continue;
  20666. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20667. }
  20668. return this;
  20669. };
  20670. /** @hidden */
  20671. AbstractMesh.prototype._checkCollision = function (collider) {
  20672. // Bounding box test
  20673. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20674. return this;
  20675. // Transformation matrix
  20676. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20677. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20678. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20679. return this;
  20680. };
  20681. // Picking
  20682. /** @hidden */
  20683. AbstractMesh.prototype._generatePointsArray = function () {
  20684. return false;
  20685. };
  20686. /**
  20687. * Checks if the passed Ray intersects with the mesh
  20688. * @param ray defines the ray to use
  20689. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20690. * @returns the picking info
  20691. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20692. */
  20693. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20694. var pickingInfo = new BABYLON.PickingInfo();
  20695. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20696. return pickingInfo;
  20697. }
  20698. if (!this._generatePointsArray()) {
  20699. return pickingInfo;
  20700. }
  20701. var intersectInfo = null;
  20702. // Octrees
  20703. var subMeshes;
  20704. var len;
  20705. if (this._submeshesOctree && this.useOctreeForPicking) {
  20706. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20707. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20708. len = intersections.length;
  20709. subMeshes = intersections.data;
  20710. }
  20711. else {
  20712. subMeshes = this.subMeshes;
  20713. len = subMeshes.length;
  20714. }
  20715. for (var index = 0; index < len; index++) {
  20716. var subMesh = subMeshes[index];
  20717. // Bounding test
  20718. if (len > 1 && !subMesh.canIntersects(ray))
  20719. continue;
  20720. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20721. if (currentIntersectInfo) {
  20722. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20723. intersectInfo = currentIntersectInfo;
  20724. intersectInfo.subMeshId = index;
  20725. if (fastCheck) {
  20726. break;
  20727. }
  20728. }
  20729. }
  20730. }
  20731. if (intersectInfo) {
  20732. // Get picked point
  20733. var world = this.getWorldMatrix();
  20734. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20735. var direction = ray.direction.clone();
  20736. direction = direction.scale(intersectInfo.distance);
  20737. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20738. var pickedPoint = worldOrigin.add(worldDirection);
  20739. // Return result
  20740. pickingInfo.hit = true;
  20741. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20742. pickingInfo.pickedPoint = pickedPoint;
  20743. pickingInfo.pickedMesh = this;
  20744. pickingInfo.bu = intersectInfo.bu || 0;
  20745. pickingInfo.bv = intersectInfo.bv || 0;
  20746. pickingInfo.faceId = intersectInfo.faceId;
  20747. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20748. return pickingInfo;
  20749. }
  20750. return pickingInfo;
  20751. };
  20752. /**
  20753. * Clones the current mesh
  20754. * @param name defines the mesh name
  20755. * @param newParent defines the new mesh parent
  20756. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20757. * @returns the new mesh
  20758. */
  20759. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20760. return null;
  20761. };
  20762. /**
  20763. * Disposes all the submeshes of the current meshnp
  20764. * @returns the current mesh
  20765. */
  20766. AbstractMesh.prototype.releaseSubMeshes = function () {
  20767. if (this.subMeshes) {
  20768. while (this.subMeshes.length) {
  20769. this.subMeshes[0].dispose();
  20770. }
  20771. }
  20772. else {
  20773. this.subMeshes = new Array();
  20774. }
  20775. return this;
  20776. };
  20777. /**
  20778. * Releases resources associated with this abstract mesh.
  20779. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20780. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20781. */
  20782. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20783. var _this = this;
  20784. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20785. var index;
  20786. // Smart Array Retainers.
  20787. this.getScene().freeActiveMeshes();
  20788. this.getScene().freeRenderingGroups();
  20789. // Action manager
  20790. if (this.actionManager !== undefined && this.actionManager !== null) {
  20791. this.actionManager.dispose();
  20792. this.actionManager = null;
  20793. }
  20794. // Skeleton
  20795. this._skeleton = null;
  20796. // Physics
  20797. if (this.physicsImpostor) {
  20798. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20799. }
  20800. // Intersections in progress
  20801. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20802. var other = this._intersectionsInProgress[index];
  20803. var pos = other._intersectionsInProgress.indexOf(this);
  20804. other._intersectionsInProgress.splice(pos, 1);
  20805. }
  20806. this._intersectionsInProgress = [];
  20807. // Lights
  20808. var lights = this.getScene().lights;
  20809. lights.forEach(function (light) {
  20810. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20811. if (meshIndex !== -1) {
  20812. light.includedOnlyMeshes.splice(meshIndex, 1);
  20813. }
  20814. meshIndex = light.excludedMeshes.indexOf(_this);
  20815. if (meshIndex !== -1) {
  20816. light.excludedMeshes.splice(meshIndex, 1);
  20817. }
  20818. // Shadow generators
  20819. var generator = light.getShadowGenerator();
  20820. if (generator) {
  20821. var shadowMap = generator.getShadowMap();
  20822. if (shadowMap && shadowMap.renderList) {
  20823. meshIndex = shadowMap.renderList.indexOf(_this);
  20824. if (meshIndex !== -1) {
  20825. shadowMap.renderList.splice(meshIndex, 1);
  20826. }
  20827. }
  20828. }
  20829. });
  20830. // Edges
  20831. if (this._edgesRenderer) {
  20832. this._edgesRenderer.dispose();
  20833. this._edgesRenderer = null;
  20834. }
  20835. // SubMeshes
  20836. if (this.getClassName() !== "InstancedMesh") {
  20837. this.releaseSubMeshes();
  20838. }
  20839. // Octree
  20840. var sceneOctree = this.getScene().selectionOctree;
  20841. if (sceneOctree !== undefined && sceneOctree !== null) {
  20842. var index = sceneOctree.dynamicContent.indexOf(this);
  20843. if (index !== -1) {
  20844. sceneOctree.dynamicContent.splice(index, 1);
  20845. }
  20846. }
  20847. // Query
  20848. var engine = this.getScene().getEngine();
  20849. if (this._occlusionQuery) {
  20850. this._isOcclusionQueryInProgress = false;
  20851. engine.deleteQuery(this._occlusionQuery);
  20852. this._occlusionQuery = null;
  20853. }
  20854. // Engine
  20855. engine.wipeCaches();
  20856. // Remove from scene
  20857. this.getScene().removeMesh(this);
  20858. if (disposeMaterialAndTextures) {
  20859. if (this.material) {
  20860. this.material.dispose(false, true);
  20861. }
  20862. }
  20863. if (!doNotRecurse) {
  20864. // Particles
  20865. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20866. if (this.getScene().particleSystems[index].emitter === this) {
  20867. this.getScene().particleSystems[index].dispose();
  20868. index--;
  20869. }
  20870. }
  20871. }
  20872. // facet data
  20873. if (this._facetDataEnabled) {
  20874. this.disableFacetData();
  20875. }
  20876. this.onAfterWorldMatrixUpdateObservable.clear();
  20877. this.onCollideObservable.clear();
  20878. this.onCollisionPositionChangeObservable.clear();
  20879. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20880. };
  20881. /**
  20882. * Adds the passed mesh as a child to the current mesh
  20883. * @param mesh defines the child mesh
  20884. * @returns the current mesh
  20885. */
  20886. AbstractMesh.prototype.addChild = function (mesh) {
  20887. mesh.setParent(this);
  20888. return this;
  20889. };
  20890. /**
  20891. * Removes the passed mesh from the current mesh children list
  20892. * @param mesh defines the child mesh
  20893. * @returns the current mesh
  20894. */
  20895. AbstractMesh.prototype.removeChild = function (mesh) {
  20896. mesh.setParent(null);
  20897. return this;
  20898. };
  20899. // Facet data
  20900. /** @hidden */
  20901. AbstractMesh.prototype._initFacetData = function () {
  20902. if (!this._facetNormals) {
  20903. this._facetNormals = new Array();
  20904. }
  20905. if (!this._facetPositions) {
  20906. this._facetPositions = new Array();
  20907. }
  20908. if (!this._facetPartitioning) {
  20909. this._facetPartitioning = new Array();
  20910. }
  20911. this._facetNb = (this.getIndices().length / 3) | 0;
  20912. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20913. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20914. for (var f = 0; f < this._facetNb; f++) {
  20915. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20916. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20917. }
  20918. this._facetDataEnabled = true;
  20919. return this;
  20920. };
  20921. /**
  20922. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20923. * This method can be called within the render loop.
  20924. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation
  20925. * @returns the current mesh
  20926. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20927. */
  20928. AbstractMesh.prototype.updateFacetData = function () {
  20929. if (!this._facetDataEnabled) {
  20930. this._initFacetData();
  20931. }
  20932. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20933. var indices = this.getIndices();
  20934. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20935. var bInfo = this.getBoundingInfo();
  20936. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20937. // init arrays, matrix and sort function on first call
  20938. this._facetDepthSortEnabled = true;
  20939. if (indices instanceof Uint16Array) {
  20940. this._depthSortedIndices = new Uint16Array(indices);
  20941. }
  20942. else if (indices instanceof Uint32Array) {
  20943. this._depthSortedIndices = new Uint32Array(indices);
  20944. }
  20945. else {
  20946. var needs32bits = false;
  20947. for (var i = 0; i < indices.length; i++) {
  20948. if (indices[i] > 65535) {
  20949. needs32bits = true;
  20950. break;
  20951. }
  20952. }
  20953. if (needs32bits) {
  20954. this._depthSortedIndices = new Uint32Array(indices);
  20955. }
  20956. else {
  20957. this._depthSortedIndices = new Uint16Array(indices);
  20958. }
  20959. }
  20960. this._facetDepthSortFunction = function (f1, f2) {
  20961. return (f2.sqDistance - f1.sqDistance);
  20962. };
  20963. if (!this._facetDepthSortFrom) {
  20964. var camera = this.getScene().activeCamera;
  20965. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20966. }
  20967. this._depthSortedFacets = [];
  20968. for (var f = 0; f < this._facetNb; f++) {
  20969. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20970. this._depthSortedFacets.push(depthSortedFacet);
  20971. }
  20972. this._invertedMatrix = BABYLON.Matrix.Identity();
  20973. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20974. }
  20975. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20976. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20977. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20978. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20979. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20980. this._subDiv.max = this._partitioningSubdivisions;
  20981. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20982. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20983. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20984. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20985. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20986. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20987. // set the parameters for ComputeNormals()
  20988. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20989. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20990. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20991. this._facetParameters.bInfo = bInfo;
  20992. this._facetParameters.bbSize = this._bbSize;
  20993. this._facetParameters.subDiv = this._subDiv;
  20994. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20995. this._facetParameters.depthSort = this._facetDepthSort;
  20996. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20997. this.computeWorldMatrix(true);
  20998. this._worldMatrix.invertToRef(this._invertedMatrix);
  20999. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21000. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21001. }
  21002. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21003. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21004. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21005. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21006. var l = (this._depthSortedIndices.length / 3) | 0;
  21007. for (var f = 0; f < l; f++) {
  21008. var sind = this._depthSortedFacets[f].ind;
  21009. this._depthSortedIndices[f * 3] = indices[sind];
  21010. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21011. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21012. }
  21013. this.updateIndices(this._depthSortedIndices);
  21014. }
  21015. return this;
  21016. };
  21017. /**
  21018. * Returns the facetLocalNormals array.
  21019. * The normals are expressed in the mesh local spac
  21020. * @returns an array of Vector3
  21021. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21022. */
  21023. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21024. if (!this._facetNormals) {
  21025. this.updateFacetData();
  21026. }
  21027. return this._facetNormals;
  21028. };
  21029. /**
  21030. * Returns the facetLocalPositions array.
  21031. * The facet positions are expressed in the mesh local space
  21032. * @returns an array of Vector3
  21033. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21034. */
  21035. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21036. if (!this._facetPositions) {
  21037. this.updateFacetData();
  21038. }
  21039. return this._facetPositions;
  21040. };
  21041. /**
  21042. * Returns the facetLocalPartioning array
  21043. * @returns an array of array of numbers
  21044. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21045. */
  21046. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21047. if (!this._facetPartitioning) {
  21048. this.updateFacetData();
  21049. }
  21050. return this._facetPartitioning;
  21051. };
  21052. /**
  21053. * Returns the i-th facet position in the world system.
  21054. * This method allocates a new Vector3 per call
  21055. * @param i defines the facet index
  21056. * @returns a new Vector3
  21057. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21058. */
  21059. AbstractMesh.prototype.getFacetPosition = function (i) {
  21060. var pos = BABYLON.Vector3.Zero();
  21061. this.getFacetPositionToRef(i, pos);
  21062. return pos;
  21063. };
  21064. /**
  21065. * Sets the reference Vector3 with the i-th facet position in the world system
  21066. * @param i defines the facet index
  21067. * @param ref defines the target vector
  21068. * @returns the current mesh
  21069. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21070. */
  21071. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21072. var localPos = (this.getFacetLocalPositions())[i];
  21073. var world = this.getWorldMatrix();
  21074. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21075. return this;
  21076. };
  21077. /**
  21078. * Returns the i-th facet normal in the world system.
  21079. * This method allocates a new Vector3 per call
  21080. * @param i defines the facet index
  21081. * @returns a new Vector3
  21082. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21083. */
  21084. AbstractMesh.prototype.getFacetNormal = function (i) {
  21085. var norm = BABYLON.Vector3.Zero();
  21086. this.getFacetNormalToRef(i, norm);
  21087. return norm;
  21088. };
  21089. /**
  21090. * Sets the reference Vector3 with the i-th facet normal in the world system
  21091. * @param i defines the facet index
  21092. * @param ref defines the target vector
  21093. * @returns the current mesh
  21094. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21095. */
  21096. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21097. var localNorm = (this.getFacetLocalNormals())[i];
  21098. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21099. return this;
  21100. };
  21101. /**
  21102. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)
  21103. * @param x defines x coordinate
  21104. * @param y defines y coordinate
  21105. * @param z defines z coordinate
  21106. * @returns the array of facet indexes
  21107. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21108. */
  21109. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21110. var bInfo = this.getBoundingInfo();
  21111. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21112. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21113. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21114. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21115. return null;
  21116. }
  21117. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21118. };
  21119. /**
  21120. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21121. * @param projected sets as the (x,y,z) world projection on the facet
  21122. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21123. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21124. * @param x defines x coordinate
  21125. * @param y defines y coordinate
  21126. * @param z defines z coordinate
  21127. * @returns the face index if found (or null instead)
  21128. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21129. */
  21130. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21131. if (checkFace === void 0) { checkFace = false; }
  21132. if (facing === void 0) { facing = true; }
  21133. var world = this.getWorldMatrix();
  21134. var invMat = BABYLON.Tmp.Matrix[5];
  21135. world.invertToRef(invMat);
  21136. var invVect = BABYLON.Tmp.Vector3[8];
  21137. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21138. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21139. if (projected) {
  21140. // tranform the local computed projected vector to world coordinates
  21141. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21142. }
  21143. return closest;
  21144. };
  21145. /**
  21146. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21147. * @param projected sets as the (x,y,z) local projection on the facet
  21148. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21149. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21150. * @param x defines x coordinate
  21151. * @param y defines y coordinate
  21152. * @param z defines z coordinate
  21153. * @returns the face index if found (or null instead)
  21154. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21155. */
  21156. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21157. if (checkFace === void 0) { checkFace = false; }
  21158. if (facing === void 0) { facing = true; }
  21159. var closest = null;
  21160. var tmpx = 0.0;
  21161. var tmpy = 0.0;
  21162. var tmpz = 0.0;
  21163. var d = 0.0; // tmp dot facet normal * facet position
  21164. var t0 = 0.0;
  21165. var projx = 0.0;
  21166. var projy = 0.0;
  21167. var projz = 0.0;
  21168. // Get all the facets in the same partitioning block than (x, y, z)
  21169. var facetPositions = this.getFacetLocalPositions();
  21170. var facetNormals = this.getFacetLocalNormals();
  21171. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21172. if (!facetsInBlock) {
  21173. return null;
  21174. }
  21175. // Get the closest facet to (x, y, z)
  21176. var shortest = Number.MAX_VALUE; // init distance vars
  21177. var tmpDistance = shortest;
  21178. var fib; // current facet in the block
  21179. var norm; // current facet normal
  21180. var p0; // current facet barycenter position
  21181. // loop on all the facets in the current partitioning block
  21182. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21183. fib = facetsInBlock[idx];
  21184. norm = facetNormals[fib];
  21185. p0 = facetPositions[fib];
  21186. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21187. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21188. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21189. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21190. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21191. projx = x + norm.x * t0;
  21192. projy = y + norm.y * t0;
  21193. projz = z + norm.z * t0;
  21194. tmpx = projx - x;
  21195. tmpy = projy - y;
  21196. tmpz = projz - z;
  21197. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21198. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21199. shortest = tmpDistance;
  21200. closest = fib;
  21201. if (projected) {
  21202. projected.x = projx;
  21203. projected.y = projy;
  21204. projected.z = projz;
  21205. }
  21206. }
  21207. }
  21208. }
  21209. return closest;
  21210. };
  21211. /**
  21212. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21213. * @returns the parameters
  21214. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21215. */
  21216. AbstractMesh.prototype.getFacetDataParameters = function () {
  21217. return this._facetParameters;
  21218. };
  21219. /**
  21220. * Disables the feature FacetData and frees the related memory
  21221. * @returns the current mesh
  21222. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21223. */
  21224. AbstractMesh.prototype.disableFacetData = function () {
  21225. if (this._facetDataEnabled) {
  21226. this._facetDataEnabled = false;
  21227. this._facetPositions = new Array();
  21228. this._facetNormals = new Array();
  21229. this._facetPartitioning = new Array();
  21230. this._facetParameters = null;
  21231. this._depthSortedIndices = new Uint32Array(0);
  21232. }
  21233. return this;
  21234. };
  21235. /**
  21236. * Updates the AbstractMesh indices array
  21237. * @param indices defines the data source
  21238. * @returns the current mesh
  21239. */
  21240. AbstractMesh.prototype.updateIndices = function (indices) {
  21241. return this;
  21242. };
  21243. /**
  21244. * Creates new normals data for the mesh
  21245. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21246. * @returns the current mesh
  21247. */
  21248. AbstractMesh.prototype.createNormals = function (updatable) {
  21249. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21250. var indices = this.getIndices();
  21251. var normals;
  21252. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21253. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21254. }
  21255. else {
  21256. normals = [];
  21257. }
  21258. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21259. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21260. return this;
  21261. };
  21262. /**
  21263. * Align the mesh with a normal
  21264. * @param normal defines the normal to use
  21265. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21266. * @returns the current mesh
  21267. */
  21268. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21269. if (!upDirection) {
  21270. upDirection = BABYLON.Axis.Y;
  21271. }
  21272. var axisX = BABYLON.Tmp.Vector3[0];
  21273. var axisZ = BABYLON.Tmp.Vector3[1];
  21274. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21275. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21276. if (this.rotationQuaternion) {
  21277. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21278. }
  21279. else {
  21280. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21281. }
  21282. return this;
  21283. };
  21284. /** @hidden */
  21285. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21286. var engine = this.getEngine();
  21287. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21288. this._isOccluded = false;
  21289. return;
  21290. }
  21291. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21292. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21293. if (isOcclusionQueryAvailable) {
  21294. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21295. this._isOcclusionQueryInProgress = false;
  21296. this._occlusionInternalRetryCounter = 0;
  21297. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21298. }
  21299. else {
  21300. this._occlusionInternalRetryCounter++;
  21301. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21302. this._isOcclusionQueryInProgress = false;
  21303. this._occlusionInternalRetryCounter = 0;
  21304. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21305. // if strict continue the last state of the object.
  21306. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21307. }
  21308. else {
  21309. return;
  21310. }
  21311. }
  21312. }
  21313. var scene = this.getScene();
  21314. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21315. if (!this._occlusionQuery) {
  21316. this._occlusionQuery = engine.createQuery();
  21317. }
  21318. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21319. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21320. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21321. this._isOcclusionQueryInProgress = true;
  21322. };
  21323. /** No occlusion */
  21324. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21325. /** Occlusion set to optimisitic */
  21326. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21327. /** Occlusion set to strict */
  21328. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21329. /** Use an accurante occlusion algorithm */
  21330. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21331. /** Use a conservative occlusion algorithm */
  21332. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21333. return AbstractMesh;
  21334. }(BABYLON.TransformNode));
  21335. BABYLON.AbstractMesh = AbstractMesh;
  21336. })(BABYLON || (BABYLON = {}));
  21337. //# sourceMappingURL=babylon.abstractMesh.js.map
  21338. var BABYLON;
  21339. (function (BABYLON) {
  21340. /**
  21341. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21342. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21343. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  21344. */
  21345. var Light = /** @class */ (function (_super) {
  21346. __extends(Light, _super);
  21347. /**
  21348. * Creates a Light object in the scene.
  21349. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21350. * @param name The firendly name of the light
  21351. * @param scene The scene the light belongs too
  21352. */
  21353. function Light(name, scene) {
  21354. var _this = _super.call(this, name, scene) || this;
  21355. /**
  21356. * Diffuse gives the basic color to an object.
  21357. */
  21358. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21359. /**
  21360. * Specular produces a highlight color on an object.
  21361. * Note: This is note affecting PBR materials.
  21362. */
  21363. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21364. /**
  21365. * Strength of the light.
  21366. * Note: By default it is define in the framework own unit.
  21367. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21368. */
  21369. _this.intensity = 1.0;
  21370. /**
  21371. * Defines how far from the source the light is impacting in scene units.
  21372. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21373. */
  21374. _this.range = Number.MAX_VALUE;
  21375. /**
  21376. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21377. * of light.
  21378. */
  21379. _this._photometricScale = 1.0;
  21380. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21381. _this._radius = 0.00001;
  21382. /**
  21383. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21384. * exceeding the number allowed of the materials.
  21385. */
  21386. _this.renderPriority = 0;
  21387. _this._shadowEnabled = true;
  21388. _this._excludeWithLayerMask = 0;
  21389. _this._includeOnlyWithLayerMask = 0;
  21390. _this._lightmapMode = 0;
  21391. /**
  21392. * @hidden Internal use only.
  21393. */
  21394. _this._excludedMeshesIds = new Array();
  21395. /**
  21396. * @hidden Internal use only.
  21397. */
  21398. _this._includedOnlyMeshesIds = new Array();
  21399. _this.getScene().addLight(_this);
  21400. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21401. _this._buildUniformLayout();
  21402. _this.includedOnlyMeshes = new Array();
  21403. _this.excludedMeshes = new Array();
  21404. _this._resyncMeshes();
  21405. return _this;
  21406. }
  21407. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21408. /**
  21409. * If every light affecting the material is in this lightmapMode,
  21410. * material.lightmapTexture adds or multiplies
  21411. * (depends on material.useLightmapAsShadowmap)
  21412. * after every other light calculations.
  21413. */
  21414. get: function () {
  21415. return Light._LIGHTMAP_DEFAULT;
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21421. /**
  21422. * material.lightmapTexture as only diffuse lighting from this light
  21423. * adds only specular lighting from this light
  21424. * adds dynamic shadows
  21425. */
  21426. get: function () {
  21427. return Light._LIGHTMAP_SPECULAR;
  21428. },
  21429. enumerable: true,
  21430. configurable: true
  21431. });
  21432. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21433. /**
  21434. * material.lightmapTexture as only lighting
  21435. * no light calculation from this light
  21436. * only adds dynamic shadows from this light
  21437. */
  21438. get: function () {
  21439. return Light._LIGHTMAP_SHADOWSONLY;
  21440. },
  21441. enumerable: true,
  21442. configurable: true
  21443. });
  21444. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21445. /**
  21446. * Each light type uses the default quantity according to its type:
  21447. * point/spot lights use luminous intensity
  21448. * directional lights use illuminance
  21449. */
  21450. get: function () {
  21451. return Light._INTENSITYMODE_AUTOMATIC;
  21452. },
  21453. enumerable: true,
  21454. configurable: true
  21455. });
  21456. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21457. /**
  21458. * lumen (lm)
  21459. */
  21460. get: function () {
  21461. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21462. },
  21463. enumerable: true,
  21464. configurable: true
  21465. });
  21466. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21467. /**
  21468. * candela (lm/sr)
  21469. */
  21470. get: function () {
  21471. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21472. },
  21473. enumerable: true,
  21474. configurable: true
  21475. });
  21476. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21477. /**
  21478. * lux (lm/m^2)
  21479. */
  21480. get: function () {
  21481. return Light._INTENSITYMODE_ILLUMINANCE;
  21482. },
  21483. enumerable: true,
  21484. configurable: true
  21485. });
  21486. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21487. /**
  21488. * nit (cd/m^2)
  21489. */
  21490. get: function () {
  21491. return Light._INTENSITYMODE_LUMINANCE;
  21492. },
  21493. enumerable: true,
  21494. configurable: true
  21495. });
  21496. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21497. /**
  21498. * Light type const id of the point light.
  21499. */
  21500. get: function () {
  21501. return Light._LIGHTTYPEID_POINTLIGHT;
  21502. },
  21503. enumerable: true,
  21504. configurable: true
  21505. });
  21506. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21507. /**
  21508. * Light type const id of the directional light.
  21509. */
  21510. get: function () {
  21511. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21517. /**
  21518. * Light type const id of the spot light.
  21519. */
  21520. get: function () {
  21521. return Light._LIGHTTYPEID_SPOTLIGHT;
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21527. /**
  21528. * Light type const id of the hemispheric light.
  21529. */
  21530. get: function () {
  21531. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21532. },
  21533. enumerable: true,
  21534. configurable: true
  21535. });
  21536. Object.defineProperty(Light.prototype, "intensityMode", {
  21537. /**
  21538. * Gets the photometric scale used to interpret the intensity.
  21539. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21540. */
  21541. get: function () {
  21542. return this._intensityMode;
  21543. },
  21544. /**
  21545. * Sets the photometric scale used to interpret the intensity.
  21546. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21547. */
  21548. set: function (value) {
  21549. this._intensityMode = value;
  21550. this._computePhotometricScale();
  21551. },
  21552. enumerable: true,
  21553. configurable: true
  21554. });
  21555. ;
  21556. ;
  21557. Object.defineProperty(Light.prototype, "radius", {
  21558. /**
  21559. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21560. */
  21561. get: function () {
  21562. return this._radius;
  21563. },
  21564. /**
  21565. * sets the light radius used by PBR Materials to simulate soft area lights.
  21566. */
  21567. set: function (value) {
  21568. this._radius = value;
  21569. this._computePhotometricScale();
  21570. },
  21571. enumerable: true,
  21572. configurable: true
  21573. });
  21574. ;
  21575. ;
  21576. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21577. /**
  21578. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21579. * the current shadow generator.
  21580. */
  21581. get: function () {
  21582. return this._shadowEnabled;
  21583. },
  21584. /**
  21585. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21586. * the current shadow generator.
  21587. */
  21588. set: function (value) {
  21589. if (this._shadowEnabled === value) {
  21590. return;
  21591. }
  21592. this._shadowEnabled = value;
  21593. this._markMeshesAsLightDirty();
  21594. },
  21595. enumerable: true,
  21596. configurable: true
  21597. });
  21598. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21599. /**
  21600. * Gets the only meshes impacted by this light.
  21601. */
  21602. get: function () {
  21603. return this._includedOnlyMeshes;
  21604. },
  21605. /**
  21606. * Sets the only meshes impacted by this light.
  21607. */
  21608. set: function (value) {
  21609. this._includedOnlyMeshes = value;
  21610. this._hookArrayForIncludedOnly(value);
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21616. /**
  21617. * Gets the meshes not impacted by this light.
  21618. */
  21619. get: function () {
  21620. return this._excludedMeshes;
  21621. },
  21622. /**
  21623. * Sets the meshes not impacted by this light.
  21624. */
  21625. set: function (value) {
  21626. this._excludedMeshes = value;
  21627. this._hookArrayForExcluded(value);
  21628. },
  21629. enumerable: true,
  21630. configurable: true
  21631. });
  21632. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21633. /**
  21634. * Gets the layer id use to find what meshes are not impacted by the light.
  21635. * Inactive if 0
  21636. */
  21637. get: function () {
  21638. return this._excludeWithLayerMask;
  21639. },
  21640. /**
  21641. * Sets the layer id use to find what meshes are not impacted by the light.
  21642. * Inactive if 0
  21643. */
  21644. set: function (value) {
  21645. this._excludeWithLayerMask = value;
  21646. this._resyncMeshes();
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21652. /**
  21653. * Gets the layer id use to find what meshes are impacted by the light.
  21654. * Inactive if 0
  21655. */
  21656. get: function () {
  21657. return this._includeOnlyWithLayerMask;
  21658. },
  21659. /**
  21660. * Sets the layer id use to find what meshes are impacted by the light.
  21661. * Inactive if 0
  21662. */
  21663. set: function (value) {
  21664. this._includeOnlyWithLayerMask = value;
  21665. this._resyncMeshes();
  21666. },
  21667. enumerable: true,
  21668. configurable: true
  21669. });
  21670. Object.defineProperty(Light.prototype, "lightmapMode", {
  21671. /**
  21672. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21673. */
  21674. get: function () {
  21675. return this._lightmapMode;
  21676. },
  21677. /**
  21678. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21679. */
  21680. set: function (value) {
  21681. if (this._lightmapMode === value) {
  21682. return;
  21683. }
  21684. this._lightmapMode = value;
  21685. this._markMeshesAsLightDirty();
  21686. },
  21687. enumerable: true,
  21688. configurable: true
  21689. });
  21690. /**
  21691. * Returns the string "Light".
  21692. * @returns the class name
  21693. */
  21694. Light.prototype.getClassName = function () {
  21695. return "Light";
  21696. };
  21697. /**
  21698. * Converts the light information to a readable string for debug purpose.
  21699. * @param fullDetails Supports for multiple levels of logging within scene loading
  21700. * @returns the human readable light info
  21701. */
  21702. Light.prototype.toString = function (fullDetails) {
  21703. var ret = "Name: " + this.name;
  21704. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21705. if (this.animations) {
  21706. for (var i = 0; i < this.animations.length; i++) {
  21707. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21708. }
  21709. }
  21710. if (fullDetails) {
  21711. }
  21712. return ret;
  21713. };
  21714. /**
  21715. * Set the enabled state of this node.
  21716. * @param value - the new enabled state
  21717. */
  21718. Light.prototype.setEnabled = function (value) {
  21719. _super.prototype.setEnabled.call(this, value);
  21720. this._resyncMeshes();
  21721. };
  21722. /**
  21723. * Returns the Light associated shadow generator if any.
  21724. * @return the associated shadow generator.
  21725. */
  21726. Light.prototype.getShadowGenerator = function () {
  21727. return this._shadowGenerator;
  21728. };
  21729. /**
  21730. * Returns a Vector3, the absolute light position in the World.
  21731. * @returns the world space position of the light
  21732. */
  21733. Light.prototype.getAbsolutePosition = function () {
  21734. return BABYLON.Vector3.Zero();
  21735. };
  21736. /**
  21737. * Specifies if the light will affect the passed mesh.
  21738. * @param mesh The mesh to test against the light
  21739. * @return true the mesh is affected otherwise, false.
  21740. */
  21741. Light.prototype.canAffectMesh = function (mesh) {
  21742. if (!mesh) {
  21743. return true;
  21744. }
  21745. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21746. return false;
  21747. }
  21748. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21749. return false;
  21750. }
  21751. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21752. return false;
  21753. }
  21754. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21755. return false;
  21756. }
  21757. return true;
  21758. };
  21759. /**
  21760. * Computes and Returns the light World matrix.
  21761. * @returns the world matrix
  21762. */
  21763. Light.prototype.getWorldMatrix = function () {
  21764. this._currentRenderId = this.getScene().getRenderId();
  21765. this._childRenderId = this._currentRenderId;
  21766. var worldMatrix = this._getWorldMatrix();
  21767. if (this.parent && this.parent.getWorldMatrix) {
  21768. if (!this._parentedWorldMatrix) {
  21769. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21770. }
  21771. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21772. this._markSyncedWithParent();
  21773. return this._parentedWorldMatrix;
  21774. }
  21775. return worldMatrix;
  21776. };
  21777. /**
  21778. * Sort function to order lights for rendering.
  21779. * @param a First Light object to compare to second.
  21780. * @param b Second Light object to compare first.
  21781. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21782. */
  21783. Light.CompareLightsPriority = function (a, b) {
  21784. //shadow-casting lights have priority over non-shadow-casting lights
  21785. //the renderPrioirty is a secondary sort criterion
  21786. if (a.shadowEnabled !== b.shadowEnabled) {
  21787. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21788. }
  21789. return b.renderPriority - a.renderPriority;
  21790. };
  21791. /**
  21792. * Releases resources associated with this node.
  21793. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21794. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21795. */
  21796. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21797. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21798. if (this._shadowGenerator) {
  21799. this._shadowGenerator.dispose();
  21800. this._shadowGenerator = null;
  21801. }
  21802. // Animations
  21803. this.getScene().stopAnimation(this);
  21804. // Remove from meshes
  21805. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21806. var mesh = _a[_i];
  21807. mesh._removeLightSource(this);
  21808. }
  21809. this._uniformBuffer.dispose();
  21810. // Remove from scene
  21811. this.getScene().removeLight(this);
  21812. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21813. };
  21814. /**
  21815. * Returns the light type ID (integer).
  21816. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21817. */
  21818. Light.prototype.getTypeID = function () {
  21819. return 0;
  21820. };
  21821. /**
  21822. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21823. * @returns the scaled intensity in intensity mode unit
  21824. */
  21825. Light.prototype.getScaledIntensity = function () {
  21826. return this._photometricScale * this.intensity;
  21827. };
  21828. /**
  21829. * Returns a new Light object, named "name", from the current one.
  21830. * @param name The name of the cloned light
  21831. * @returns the new created light
  21832. */
  21833. Light.prototype.clone = function (name) {
  21834. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21835. if (!constructor) {
  21836. return null;
  21837. }
  21838. return BABYLON.SerializationHelper.Clone(constructor, this);
  21839. };
  21840. /**
  21841. * Serializes the current light into a Serialization object.
  21842. * @returns the serialized object.
  21843. */
  21844. Light.prototype.serialize = function () {
  21845. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21846. // Type
  21847. serializationObject.type = this.getTypeID();
  21848. // Parent
  21849. if (this.parent) {
  21850. serializationObject.parentId = this.parent.id;
  21851. }
  21852. // Inclusion / exclusions
  21853. if (this.excludedMeshes.length > 0) {
  21854. serializationObject.excludedMeshesIds = [];
  21855. this.excludedMeshes.forEach(function (mesh) {
  21856. serializationObject.excludedMeshesIds.push(mesh.id);
  21857. });
  21858. }
  21859. if (this.includedOnlyMeshes.length > 0) {
  21860. serializationObject.includedOnlyMeshesIds = [];
  21861. this.includedOnlyMeshes.forEach(function (mesh) {
  21862. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21863. });
  21864. }
  21865. // Animations
  21866. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21867. serializationObject.ranges = this.serializeAnimationRanges();
  21868. return serializationObject;
  21869. };
  21870. /**
  21871. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21872. * This new light is named "name" and added to the passed scene.
  21873. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21874. * @param name The friendly name of the light
  21875. * @param scene The scene the new light will belong to
  21876. * @returns the constructor function
  21877. */
  21878. Light.GetConstructorFromName = function (type, name, scene) {
  21879. switch (type) {
  21880. case 0:
  21881. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21882. case 1:
  21883. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21884. case 2:
  21885. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21886. case 3:
  21887. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21888. }
  21889. return null;
  21890. };
  21891. /**
  21892. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21893. * @param parsedLight The JSON representation of the light
  21894. * @param scene The scene to create the parsed light in
  21895. * @returns the created light after parsing
  21896. */
  21897. Light.Parse = function (parsedLight, scene) {
  21898. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21899. if (!constructor) {
  21900. return null;
  21901. }
  21902. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21903. // Inclusion / exclusions
  21904. if (parsedLight.excludedMeshesIds) {
  21905. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21906. }
  21907. if (parsedLight.includedOnlyMeshesIds) {
  21908. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21909. }
  21910. // Parent
  21911. if (parsedLight.parentId) {
  21912. light._waitingParentId = parsedLight.parentId;
  21913. }
  21914. // Animations
  21915. if (parsedLight.animations) {
  21916. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21917. var parsedAnimation = parsedLight.animations[animationIndex];
  21918. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21919. }
  21920. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21921. }
  21922. if (parsedLight.autoAnimate) {
  21923. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21924. }
  21925. return light;
  21926. };
  21927. Light.prototype._hookArrayForExcluded = function (array) {
  21928. var _this = this;
  21929. var oldPush = array.push;
  21930. array.push = function () {
  21931. var items = [];
  21932. for (var _i = 0; _i < arguments.length; _i++) {
  21933. items[_i] = arguments[_i];
  21934. }
  21935. var result = oldPush.apply(array, items);
  21936. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21937. var item = items_1[_a];
  21938. item._resyncLighSource(_this);
  21939. }
  21940. return result;
  21941. };
  21942. var oldSplice = array.splice;
  21943. array.splice = function (index, deleteCount) {
  21944. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21945. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21946. var item = deleted_1[_i];
  21947. item._resyncLighSource(_this);
  21948. }
  21949. return deleted;
  21950. };
  21951. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21952. var item = array_1[_i];
  21953. item._resyncLighSource(this);
  21954. }
  21955. };
  21956. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21957. var _this = this;
  21958. var oldPush = array.push;
  21959. array.push = function () {
  21960. var items = [];
  21961. for (var _i = 0; _i < arguments.length; _i++) {
  21962. items[_i] = arguments[_i];
  21963. }
  21964. var result = oldPush.apply(array, items);
  21965. _this._resyncMeshes();
  21966. return result;
  21967. };
  21968. var oldSplice = array.splice;
  21969. array.splice = function (index, deleteCount) {
  21970. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21971. _this._resyncMeshes();
  21972. return deleted;
  21973. };
  21974. this._resyncMeshes();
  21975. };
  21976. Light.prototype._resyncMeshes = function () {
  21977. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21978. var mesh = _a[_i];
  21979. mesh._resyncLighSource(this);
  21980. }
  21981. };
  21982. /**
  21983. * Forces the meshes to update their light related information in their rendering used effects
  21984. * @hidden Internal Use Only
  21985. */
  21986. Light.prototype._markMeshesAsLightDirty = function () {
  21987. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21988. var mesh = _a[_i];
  21989. if (mesh._lightSources.indexOf(this) !== -1) {
  21990. mesh._markSubMeshesAsLightDirty();
  21991. }
  21992. }
  21993. };
  21994. /**
  21995. * Recomputes the cached photometric scale if needed.
  21996. */
  21997. Light.prototype._computePhotometricScale = function () {
  21998. this._photometricScale = this._getPhotometricScale();
  21999. this.getScene().resetCachedMaterial();
  22000. };
  22001. /**
  22002. * Returns the Photometric Scale according to the light type and intensity mode.
  22003. */
  22004. Light.prototype._getPhotometricScale = function () {
  22005. var photometricScale = 0.0;
  22006. var lightTypeID = this.getTypeID();
  22007. //get photometric mode
  22008. var photometricMode = this.intensityMode;
  22009. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22010. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22011. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22012. }
  22013. else {
  22014. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22015. }
  22016. }
  22017. //compute photometric scale
  22018. switch (lightTypeID) {
  22019. case Light.LIGHTTYPEID_POINTLIGHT:
  22020. case Light.LIGHTTYPEID_SPOTLIGHT:
  22021. switch (photometricMode) {
  22022. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22023. photometricScale = 1.0 / (4.0 * Math.PI);
  22024. break;
  22025. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22026. photometricScale = 1.0;
  22027. break;
  22028. case Light.INTENSITYMODE_LUMINANCE:
  22029. photometricScale = this.radius * this.radius;
  22030. break;
  22031. }
  22032. break;
  22033. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22034. switch (photometricMode) {
  22035. case Light.INTENSITYMODE_ILLUMINANCE:
  22036. photometricScale = 1.0;
  22037. break;
  22038. case Light.INTENSITYMODE_LUMINANCE:
  22039. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22040. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22041. var apexAngleRadians = this.radius;
  22042. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22043. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22044. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22045. photometricScale = solidAngle;
  22046. break;
  22047. }
  22048. break;
  22049. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22050. // No fall off in hemisperic light.
  22051. photometricScale = 1.0;
  22052. break;
  22053. }
  22054. return photometricScale;
  22055. };
  22056. /**
  22057. * Reorder the light in the scene according to their defined priority.
  22058. * @hidden Internal Use Only
  22059. */
  22060. Light.prototype._reorderLightsInScene = function () {
  22061. var scene = this.getScene();
  22062. if (this._renderPriority != 0) {
  22063. scene.requireLightSorting = true;
  22064. }
  22065. this.getScene().sortLightsByPriority();
  22066. };
  22067. //lightmapMode Consts
  22068. Light._LIGHTMAP_DEFAULT = 0;
  22069. Light._LIGHTMAP_SPECULAR = 1;
  22070. Light._LIGHTMAP_SHADOWSONLY = 2;
  22071. // Intensity Mode Consts
  22072. Light._INTENSITYMODE_AUTOMATIC = 0;
  22073. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22074. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22075. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22076. Light._INTENSITYMODE_LUMINANCE = 4;
  22077. // Light types ids const.
  22078. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22079. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22080. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22081. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22082. __decorate([
  22083. BABYLON.serializeAsColor3()
  22084. ], Light.prototype, "diffuse", void 0);
  22085. __decorate([
  22086. BABYLON.serializeAsColor3()
  22087. ], Light.prototype, "specular", void 0);
  22088. __decorate([
  22089. BABYLON.serialize()
  22090. ], Light.prototype, "intensity", void 0);
  22091. __decorate([
  22092. BABYLON.serialize()
  22093. ], Light.prototype, "range", void 0);
  22094. __decorate([
  22095. BABYLON.serialize()
  22096. ], Light.prototype, "intensityMode", null);
  22097. __decorate([
  22098. BABYLON.serialize()
  22099. ], Light.prototype, "radius", null);
  22100. __decorate([
  22101. BABYLON.serialize()
  22102. ], Light.prototype, "_renderPriority", void 0);
  22103. __decorate([
  22104. BABYLON.expandToProperty("_reorderLightsInScene")
  22105. ], Light.prototype, "renderPriority", void 0);
  22106. __decorate([
  22107. BABYLON.serialize("shadowEnabled")
  22108. ], Light.prototype, "_shadowEnabled", void 0);
  22109. __decorate([
  22110. BABYLON.serialize("excludeWithLayerMask")
  22111. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22112. __decorate([
  22113. BABYLON.serialize("includeOnlyWithLayerMask")
  22114. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22115. __decorate([
  22116. BABYLON.serialize("lightmapMode")
  22117. ], Light.prototype, "_lightmapMode", void 0);
  22118. return Light;
  22119. }(BABYLON.Node));
  22120. BABYLON.Light = Light;
  22121. })(BABYLON || (BABYLON = {}));
  22122. //# sourceMappingURL=babylon.light.js.map
  22123. var BABYLON;
  22124. (function (BABYLON) {
  22125. var Camera = /** @class */ (function (_super) {
  22126. __extends(Camera, _super);
  22127. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22128. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22129. var _this = _super.call(this, name, scene) || this;
  22130. /**
  22131. * The vector the camera should consider as up.
  22132. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22133. */
  22134. _this.upVector = BABYLON.Vector3.Up();
  22135. _this.orthoLeft = null;
  22136. _this.orthoRight = null;
  22137. _this.orthoBottom = null;
  22138. _this.orthoTop = null;
  22139. /**
  22140. * FOV is set in Radians. (default is 0.8)
  22141. */
  22142. _this.fov = 0.8;
  22143. _this.minZ = 1;
  22144. _this.maxZ = 10000.0;
  22145. _this.inertia = 0.9;
  22146. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22147. _this.isIntermediate = false;
  22148. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22149. /**
  22150. * Restricts the camera to viewing objects with the same layerMask.
  22151. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22152. */
  22153. _this.layerMask = 0x0FFFFFFF;
  22154. /**
  22155. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22156. */
  22157. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22158. // Camera rig members
  22159. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22160. _this._rigCameras = new Array();
  22161. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22162. _this._skipRendering = false;
  22163. _this.customRenderTargets = new Array();
  22164. // Observables
  22165. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22166. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22167. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22168. _this.onRestoreStateObservable = new BABYLON.Observable();
  22169. // Cache
  22170. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22171. _this._projectionMatrix = new BABYLON.Matrix();
  22172. _this._doNotComputeProjectionMatrix = false;
  22173. _this._worldMatrix = BABYLON.Matrix.Identity();
  22174. _this._postProcesses = new Array();
  22175. _this._transformMatrix = BABYLON.Matrix.Zero();
  22176. _this._activeMeshes = new BABYLON.SmartArray(256);
  22177. _this._globalPosition = BABYLON.Vector3.Zero();
  22178. _this._refreshFrustumPlanes = true;
  22179. _this.getScene().addCamera(_this);
  22180. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22181. _this.getScene().activeCamera = _this;
  22182. }
  22183. _this.position = position;
  22184. return _this;
  22185. }
  22186. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22187. get: function () {
  22188. return Camera._PERSPECTIVE_CAMERA;
  22189. },
  22190. enumerable: true,
  22191. configurable: true
  22192. });
  22193. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22194. get: function () {
  22195. return Camera._ORTHOGRAPHIC_CAMERA;
  22196. },
  22197. enumerable: true,
  22198. configurable: true
  22199. });
  22200. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22201. /**
  22202. * This is the default FOV mode for perspective cameras.
  22203. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22204. *
  22205. */
  22206. get: function () {
  22207. return Camera._FOVMODE_VERTICAL_FIXED;
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22213. /**
  22214. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22215. *
  22216. */
  22217. get: function () {
  22218. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22219. },
  22220. enumerable: true,
  22221. configurable: true
  22222. });
  22223. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22224. get: function () {
  22225. return Camera._RIG_MODE_NONE;
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22231. get: function () {
  22232. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22233. },
  22234. enumerable: true,
  22235. configurable: true
  22236. });
  22237. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22238. get: function () {
  22239. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22245. get: function () {
  22246. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22247. },
  22248. enumerable: true,
  22249. configurable: true
  22250. });
  22251. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22252. get: function () {
  22253. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22254. },
  22255. enumerable: true,
  22256. configurable: true
  22257. });
  22258. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22259. get: function () {
  22260. return Camera._RIG_MODE_VR;
  22261. },
  22262. enumerable: true,
  22263. configurable: true
  22264. });
  22265. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22266. get: function () {
  22267. return Camera._RIG_MODE_WEBVR;
  22268. },
  22269. enumerable: true,
  22270. configurable: true
  22271. });
  22272. /**
  22273. * Store current camera state (fov, position, etc..)
  22274. */
  22275. Camera.prototype.storeState = function () {
  22276. this._stateStored = true;
  22277. this._storedFov = this.fov;
  22278. return this;
  22279. };
  22280. /**
  22281. * Restores the camera state values if it has been stored. You must call storeState() first
  22282. */
  22283. Camera.prototype._restoreStateValues = function () {
  22284. if (!this._stateStored) {
  22285. return false;
  22286. }
  22287. this.fov = this._storedFov;
  22288. return true;
  22289. };
  22290. /**
  22291. * Restored camera state. You must call storeState() first
  22292. */
  22293. Camera.prototype.restoreState = function () {
  22294. if (this._restoreStateValues()) {
  22295. this.onRestoreStateObservable.notifyObservers(this);
  22296. return true;
  22297. }
  22298. return false;
  22299. };
  22300. Camera.prototype.getClassName = function () {
  22301. return "Camera";
  22302. };
  22303. /**
  22304. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22305. */
  22306. Camera.prototype.toString = function (fullDetails) {
  22307. var ret = "Name: " + this.name;
  22308. ret += ", type: " + this.getClassName();
  22309. if (this.animations) {
  22310. for (var i = 0; i < this.animations.length; i++) {
  22311. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22312. }
  22313. }
  22314. if (fullDetails) {
  22315. }
  22316. return ret;
  22317. };
  22318. Object.defineProperty(Camera.prototype, "globalPosition", {
  22319. get: function () {
  22320. return this._globalPosition;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Camera.prototype.getActiveMeshes = function () {
  22326. return this._activeMeshes;
  22327. };
  22328. Camera.prototype.isActiveMesh = function (mesh) {
  22329. return (this._activeMeshes.indexOf(mesh) !== -1);
  22330. };
  22331. /**
  22332. * Is this camera ready to be used/rendered
  22333. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22334. * @return true if the camera is ready
  22335. */
  22336. Camera.prototype.isReady = function (completeCheck) {
  22337. if (completeCheck === void 0) { completeCheck = false; }
  22338. if (completeCheck) {
  22339. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22340. var pp = _a[_i];
  22341. if (pp && !pp.isReady()) {
  22342. return false;
  22343. }
  22344. }
  22345. }
  22346. return _super.prototype.isReady.call(this, completeCheck);
  22347. };
  22348. //Cache
  22349. Camera.prototype._initCache = function () {
  22350. _super.prototype._initCache.call(this);
  22351. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22352. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22353. this._cache.mode = undefined;
  22354. this._cache.minZ = undefined;
  22355. this._cache.maxZ = undefined;
  22356. this._cache.fov = undefined;
  22357. this._cache.fovMode = undefined;
  22358. this._cache.aspectRatio = undefined;
  22359. this._cache.orthoLeft = undefined;
  22360. this._cache.orthoRight = undefined;
  22361. this._cache.orthoBottom = undefined;
  22362. this._cache.orthoTop = undefined;
  22363. this._cache.renderWidth = undefined;
  22364. this._cache.renderHeight = undefined;
  22365. };
  22366. Camera.prototype._updateCache = function (ignoreParentClass) {
  22367. if (!ignoreParentClass) {
  22368. _super.prototype._updateCache.call(this);
  22369. }
  22370. this._cache.position.copyFrom(this.position);
  22371. this._cache.upVector.copyFrom(this.upVector);
  22372. };
  22373. // Synchronized
  22374. Camera.prototype._isSynchronized = function () {
  22375. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22376. };
  22377. Camera.prototype._isSynchronizedViewMatrix = function () {
  22378. if (!_super.prototype._isSynchronized.call(this))
  22379. return false;
  22380. return this._cache.position.equals(this.position)
  22381. && this._cache.upVector.equals(this.upVector)
  22382. && this.isSynchronizedWithParent();
  22383. };
  22384. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22385. var check = this._cache.mode === this.mode
  22386. && this._cache.minZ === this.minZ
  22387. && this._cache.maxZ === this.maxZ;
  22388. if (!check) {
  22389. return false;
  22390. }
  22391. var engine = this.getEngine();
  22392. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22393. check = this._cache.fov === this.fov
  22394. && this._cache.fovMode === this.fovMode
  22395. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22396. }
  22397. else {
  22398. check = this._cache.orthoLeft === this.orthoLeft
  22399. && this._cache.orthoRight === this.orthoRight
  22400. && this._cache.orthoBottom === this.orthoBottom
  22401. && this._cache.orthoTop === this.orthoTop
  22402. && this._cache.renderWidth === engine.getRenderWidth()
  22403. && this._cache.renderHeight === engine.getRenderHeight();
  22404. }
  22405. return check;
  22406. };
  22407. // Controls
  22408. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22409. };
  22410. Camera.prototype.detachControl = function (element) {
  22411. };
  22412. Camera.prototype.update = function () {
  22413. this._checkInputs();
  22414. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22415. this._updateRigCameras();
  22416. }
  22417. };
  22418. Camera.prototype._checkInputs = function () {
  22419. this.onAfterCheckInputsObservable.notifyObservers(this);
  22420. };
  22421. Object.defineProperty(Camera.prototype, "rigCameras", {
  22422. get: function () {
  22423. return this._rigCameras;
  22424. },
  22425. enumerable: true,
  22426. configurable: true
  22427. });
  22428. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22429. get: function () {
  22430. return this._rigPostProcess;
  22431. },
  22432. enumerable: true,
  22433. configurable: true
  22434. });
  22435. /**
  22436. * Internal, gets the first post proces.
  22437. * @returns the first post process to be run on this camera.
  22438. */
  22439. Camera.prototype._getFirstPostProcess = function () {
  22440. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22441. if (this._postProcesses[ppIndex] !== null) {
  22442. return this._postProcesses[ppIndex];
  22443. }
  22444. }
  22445. return null;
  22446. };
  22447. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22448. // invalidate framebuffer
  22449. var firstPostProcess = this._getFirstPostProcess();
  22450. if (firstPostProcess) {
  22451. firstPostProcess.markTextureDirty();
  22452. }
  22453. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22454. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22455. var cam = this._rigCameras[i];
  22456. var rigPostProcess = cam._rigPostProcess;
  22457. // for VR rig, there does not have to be a post process
  22458. if (rigPostProcess) {
  22459. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22460. if (isPass) {
  22461. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22462. cam.isIntermediate = this._postProcesses.length === 0;
  22463. }
  22464. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22465. rigPostProcess.markTextureDirty();
  22466. }
  22467. else {
  22468. cam._postProcesses = this._postProcesses.slice(0);
  22469. }
  22470. }
  22471. };
  22472. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22473. if (insertAt === void 0) { insertAt = null; }
  22474. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22475. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22476. return 0;
  22477. }
  22478. if (insertAt == null || insertAt < 0) {
  22479. this._postProcesses.push(postProcess);
  22480. }
  22481. else if (this._postProcesses[insertAt] === null) {
  22482. this._postProcesses[insertAt] = postProcess;
  22483. }
  22484. else {
  22485. this._postProcesses.splice(insertAt, 0, postProcess);
  22486. }
  22487. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22488. return this._postProcesses.indexOf(postProcess);
  22489. };
  22490. Camera.prototype.detachPostProcess = function (postProcess) {
  22491. var idx = this._postProcesses.indexOf(postProcess);
  22492. if (idx !== -1) {
  22493. this._postProcesses[idx] = null;
  22494. }
  22495. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22496. };
  22497. Camera.prototype.getWorldMatrix = function () {
  22498. if (this._isSynchronizedViewMatrix()) {
  22499. return this._worldMatrix;
  22500. }
  22501. // Getting the the view matrix will also compute the world matrix.
  22502. this.getViewMatrix();
  22503. return this._worldMatrix;
  22504. };
  22505. Camera.prototype._getViewMatrix = function () {
  22506. return BABYLON.Matrix.Identity();
  22507. };
  22508. Camera.prototype.getViewMatrix = function (force) {
  22509. if (!force && this._isSynchronizedViewMatrix()) {
  22510. return this._computedViewMatrix;
  22511. }
  22512. this.updateCache();
  22513. this._computedViewMatrix = this._getViewMatrix();
  22514. this._currentRenderId = this.getScene().getRenderId();
  22515. this._childRenderId = this._currentRenderId;
  22516. this._refreshFrustumPlanes = true;
  22517. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22518. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22519. }
  22520. this.onViewMatrixChangedObservable.notifyObservers(this);
  22521. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22522. return this._computedViewMatrix;
  22523. };
  22524. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22525. this._doNotComputeProjectionMatrix = true;
  22526. if (projection !== undefined) {
  22527. this._projectionMatrix = projection;
  22528. }
  22529. };
  22530. ;
  22531. Camera.prototype.unfreezeProjectionMatrix = function () {
  22532. this._doNotComputeProjectionMatrix = false;
  22533. };
  22534. ;
  22535. Camera.prototype.getProjectionMatrix = function (force) {
  22536. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22537. return this._projectionMatrix;
  22538. }
  22539. // Cache
  22540. this._cache.mode = this.mode;
  22541. this._cache.minZ = this.minZ;
  22542. this._cache.maxZ = this.maxZ;
  22543. // Matrix
  22544. this._refreshFrustumPlanes = true;
  22545. var engine = this.getEngine();
  22546. var scene = this.getScene();
  22547. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22548. this._cache.fov = this.fov;
  22549. this._cache.fovMode = this.fovMode;
  22550. this._cache.aspectRatio = engine.getAspectRatio(this);
  22551. if (this.minZ <= 0) {
  22552. this.minZ = 0.1;
  22553. }
  22554. if (scene.useRightHandedSystem) {
  22555. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22556. }
  22557. else {
  22558. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22559. }
  22560. }
  22561. else {
  22562. var halfWidth = engine.getRenderWidth() / 2.0;
  22563. var halfHeight = engine.getRenderHeight() / 2.0;
  22564. if (scene.useRightHandedSystem) {
  22565. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22566. }
  22567. else {
  22568. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22569. }
  22570. this._cache.orthoLeft = this.orthoLeft;
  22571. this._cache.orthoRight = this.orthoRight;
  22572. this._cache.orthoBottom = this.orthoBottom;
  22573. this._cache.orthoTop = this.orthoTop;
  22574. this._cache.renderWidth = engine.getRenderWidth();
  22575. this._cache.renderHeight = engine.getRenderHeight();
  22576. }
  22577. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22578. return this._projectionMatrix;
  22579. };
  22580. Camera.prototype.getTranformationMatrix = function () {
  22581. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22582. return this._transformMatrix;
  22583. };
  22584. Camera.prototype.updateFrustumPlanes = function () {
  22585. if (!this._refreshFrustumPlanes) {
  22586. return;
  22587. }
  22588. this.getTranformationMatrix();
  22589. if (!this._frustumPlanes) {
  22590. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22591. }
  22592. else {
  22593. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22594. }
  22595. this._refreshFrustumPlanes = false;
  22596. };
  22597. Camera.prototype.isInFrustum = function (target) {
  22598. this.updateFrustumPlanes();
  22599. return target.isInFrustum(this._frustumPlanes);
  22600. };
  22601. Camera.prototype.isCompletelyInFrustum = function (target) {
  22602. this.updateFrustumPlanes();
  22603. return target.isCompletelyInFrustum(this._frustumPlanes);
  22604. };
  22605. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22606. if (length === void 0) { length = 100; }
  22607. if (!transform) {
  22608. transform = this.getWorldMatrix();
  22609. }
  22610. if (!origin) {
  22611. origin = this.position;
  22612. }
  22613. var forward = new BABYLON.Vector3(0, 0, 1);
  22614. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22615. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22616. return new BABYLON.Ray(origin, direction, length);
  22617. };
  22618. /**
  22619. * Releases resources associated with this node.
  22620. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22621. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22622. */
  22623. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22624. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22625. // Observables
  22626. this.onViewMatrixChangedObservable.clear();
  22627. this.onProjectionMatrixChangedObservable.clear();
  22628. this.onAfterCheckInputsObservable.clear();
  22629. this.onRestoreStateObservable.clear();
  22630. // Inputs
  22631. if (this.inputs) {
  22632. this.inputs.clear();
  22633. }
  22634. // Animations
  22635. this.getScene().stopAnimation(this);
  22636. // Remove from scene
  22637. this.getScene().removeCamera(this);
  22638. while (this._rigCameras.length > 0) {
  22639. var camera = this._rigCameras.pop();
  22640. if (camera) {
  22641. camera.dispose();
  22642. }
  22643. }
  22644. // Postprocesses
  22645. if (this._rigPostProcess) {
  22646. this._rigPostProcess.dispose(this);
  22647. this._rigPostProcess = null;
  22648. this._postProcesses = [];
  22649. }
  22650. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22651. this._rigPostProcess = null;
  22652. this._postProcesses = [];
  22653. }
  22654. else {
  22655. var i = this._postProcesses.length;
  22656. while (--i >= 0) {
  22657. var postProcess = this._postProcesses[i];
  22658. if (postProcess) {
  22659. postProcess.dispose(this);
  22660. }
  22661. }
  22662. }
  22663. // Render targets
  22664. var i = this.customRenderTargets.length;
  22665. while (--i >= 0) {
  22666. this.customRenderTargets[i].dispose();
  22667. }
  22668. this.customRenderTargets = [];
  22669. // Active Meshes
  22670. this._activeMeshes.dispose();
  22671. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22672. };
  22673. Object.defineProperty(Camera.prototype, "leftCamera", {
  22674. // ---- Camera rigs section ----
  22675. get: function () {
  22676. if (this._rigCameras.length < 1) {
  22677. return null;
  22678. }
  22679. return this._rigCameras[0];
  22680. },
  22681. enumerable: true,
  22682. configurable: true
  22683. });
  22684. Object.defineProperty(Camera.prototype, "rightCamera", {
  22685. get: function () {
  22686. if (this._rigCameras.length < 2) {
  22687. return null;
  22688. }
  22689. return this._rigCameras[1];
  22690. },
  22691. enumerable: true,
  22692. configurable: true
  22693. });
  22694. Camera.prototype.getLeftTarget = function () {
  22695. if (this._rigCameras.length < 1) {
  22696. return null;
  22697. }
  22698. return this._rigCameras[0].getTarget();
  22699. };
  22700. Camera.prototype.getRightTarget = function () {
  22701. if (this._rigCameras.length < 2) {
  22702. return null;
  22703. }
  22704. return this._rigCameras[1].getTarget();
  22705. };
  22706. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22707. if (this.cameraRigMode === mode) {
  22708. return;
  22709. }
  22710. while (this._rigCameras.length > 0) {
  22711. var camera = this._rigCameras.pop();
  22712. if (camera) {
  22713. camera.dispose();
  22714. }
  22715. }
  22716. this.cameraRigMode = mode;
  22717. this._cameraRigParams = {};
  22718. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22719. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22720. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22721. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22722. // create the rig cameras, unless none
  22723. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22724. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22725. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22726. if (leftCamera && rightCamera) {
  22727. this._rigCameras.push(leftCamera);
  22728. this._rigCameras.push(rightCamera);
  22729. }
  22730. }
  22731. switch (this.cameraRigMode) {
  22732. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22733. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22734. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22735. break;
  22736. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22737. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22738. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22739. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22740. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22741. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22742. break;
  22743. case Camera.RIG_MODE_VR:
  22744. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22745. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22746. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22747. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22748. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22749. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22750. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22751. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22752. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22753. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22754. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22755. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22756. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22757. if (metrics.compensateDistortion) {
  22758. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22759. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22760. }
  22761. break;
  22762. case Camera.RIG_MODE_WEBVR:
  22763. if (rigParams.vrDisplay) {
  22764. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22765. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22766. //Left eye
  22767. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22768. this._rigCameras[0].setCameraRigParameter("left", true);
  22769. //leaving this for future reference
  22770. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22771. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22772. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22773. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22774. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22775. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22776. this._rigCameras[0].parent = this;
  22777. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22778. //Right eye
  22779. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22780. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22781. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22782. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22783. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22784. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22785. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22786. this._rigCameras[1].parent = this;
  22787. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22788. if (Camera.UseAlternateWebVRRendering) {
  22789. this._rigCameras[1]._skipRendering = true;
  22790. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22791. }
  22792. }
  22793. break;
  22794. }
  22795. this._cascadePostProcessesToRigCams();
  22796. this.update();
  22797. };
  22798. Camera.prototype._getVRProjectionMatrix = function () {
  22799. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22800. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22801. return this._projectionMatrix;
  22802. };
  22803. Camera.prototype._updateCameraRotationMatrix = function () {
  22804. //Here for WebVR
  22805. };
  22806. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22807. //Here for WebVR
  22808. };
  22809. /**
  22810. * This function MUST be overwritten by the different WebVR cameras available.
  22811. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22812. */
  22813. Camera.prototype._getWebVRProjectionMatrix = function () {
  22814. return BABYLON.Matrix.Identity();
  22815. };
  22816. /**
  22817. * This function MUST be overwritten by the different WebVR cameras available.
  22818. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22819. */
  22820. Camera.prototype._getWebVRViewMatrix = function () {
  22821. return BABYLON.Matrix.Identity();
  22822. };
  22823. Camera.prototype.setCameraRigParameter = function (name, value) {
  22824. if (!this._cameraRigParams) {
  22825. this._cameraRigParams = {};
  22826. }
  22827. this._cameraRigParams[name] = value;
  22828. //provisionnally:
  22829. if (name === "interaxialDistance") {
  22830. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22831. }
  22832. };
  22833. /**
  22834. * needs to be overridden by children so sub has required properties to be copied
  22835. */
  22836. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22837. return null;
  22838. };
  22839. /**
  22840. * May need to be overridden by children
  22841. */
  22842. Camera.prototype._updateRigCameras = function () {
  22843. for (var i = 0; i < this._rigCameras.length; i++) {
  22844. this._rigCameras[i].minZ = this.minZ;
  22845. this._rigCameras[i].maxZ = this.maxZ;
  22846. this._rigCameras[i].fov = this.fov;
  22847. }
  22848. // only update viewport when ANAGLYPH
  22849. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22850. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22851. }
  22852. };
  22853. Camera.prototype._setupInputs = function () {
  22854. };
  22855. Camera.prototype.serialize = function () {
  22856. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22857. // Type
  22858. serializationObject.type = this.getClassName();
  22859. // Parent
  22860. if (this.parent) {
  22861. serializationObject.parentId = this.parent.id;
  22862. }
  22863. if (this.inputs) {
  22864. this.inputs.serialize(serializationObject);
  22865. }
  22866. // Animations
  22867. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22868. serializationObject.ranges = this.serializeAnimationRanges();
  22869. return serializationObject;
  22870. };
  22871. Camera.prototype.clone = function (name) {
  22872. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22873. };
  22874. Camera.prototype.getDirection = function (localAxis) {
  22875. var result = BABYLON.Vector3.Zero();
  22876. this.getDirectionToRef(localAxis, result);
  22877. return result;
  22878. };
  22879. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22880. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22881. };
  22882. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22883. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22884. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22885. switch (type) {
  22886. case "ArcRotateCamera":
  22887. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22888. case "DeviceOrientationCamera":
  22889. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22890. case "FollowCamera":
  22891. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22892. case "ArcFollowCamera":
  22893. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22894. case "GamepadCamera":
  22895. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22896. case "TouchCamera":
  22897. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22898. case "VirtualJoysticksCamera":
  22899. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22900. case "WebVRFreeCamera":
  22901. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22902. case "WebVRGamepadCamera":
  22903. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22904. case "VRDeviceOrientationFreeCamera":
  22905. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22906. case "VRDeviceOrientationGamepadCamera":
  22907. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22908. case "AnaglyphArcRotateCamera":
  22909. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22910. case "AnaglyphFreeCamera":
  22911. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22912. case "AnaglyphGamepadCamera":
  22913. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22914. case "AnaglyphUniversalCamera":
  22915. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22916. case "StereoscopicArcRotateCamera":
  22917. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22918. case "StereoscopicFreeCamera":
  22919. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22920. case "StereoscopicGamepadCamera":
  22921. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22922. case "StereoscopicUniversalCamera":
  22923. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22924. case "FreeCamera": // Forcing Universal here
  22925. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22926. default: // Universal Camera is the default value
  22927. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22928. }
  22929. };
  22930. Camera.prototype.computeWorldMatrix = function () {
  22931. return this.getWorldMatrix();
  22932. };
  22933. Camera.Parse = function (parsedCamera, scene) {
  22934. var type = parsedCamera.type;
  22935. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22936. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22937. // Parent
  22938. if (parsedCamera.parentId) {
  22939. camera._waitingParentId = parsedCamera.parentId;
  22940. }
  22941. //If camera has an input manager, let it parse inputs settings
  22942. if (camera.inputs) {
  22943. camera.inputs.parse(parsedCamera);
  22944. camera._setupInputs();
  22945. }
  22946. if (camera.setPosition) { // need to force position
  22947. camera.position.copyFromFloats(0, 0, 0);
  22948. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22949. }
  22950. // Target
  22951. if (parsedCamera.target) {
  22952. if (camera.setTarget) {
  22953. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22954. }
  22955. }
  22956. // Apply 3d rig, when found
  22957. if (parsedCamera.cameraRigMode) {
  22958. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22959. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22960. }
  22961. // Animations
  22962. if (parsedCamera.animations) {
  22963. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22964. var parsedAnimation = parsedCamera.animations[animationIndex];
  22965. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22966. }
  22967. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22968. }
  22969. if (parsedCamera.autoAnimate) {
  22970. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22971. }
  22972. return camera;
  22973. };
  22974. // Statics
  22975. Camera._PERSPECTIVE_CAMERA = 0;
  22976. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22977. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22978. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22979. Camera._RIG_MODE_NONE = 0;
  22980. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22981. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22982. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22983. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22984. Camera._RIG_MODE_VR = 20;
  22985. Camera._RIG_MODE_WEBVR = 21;
  22986. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22987. Camera.UseAlternateWebVRRendering = false;
  22988. __decorate([
  22989. BABYLON.serializeAsVector3()
  22990. ], Camera.prototype, "position", void 0);
  22991. __decorate([
  22992. BABYLON.serializeAsVector3()
  22993. ], Camera.prototype, "upVector", void 0);
  22994. __decorate([
  22995. BABYLON.serialize()
  22996. ], Camera.prototype, "orthoLeft", void 0);
  22997. __decorate([
  22998. BABYLON.serialize()
  22999. ], Camera.prototype, "orthoRight", void 0);
  23000. __decorate([
  23001. BABYLON.serialize()
  23002. ], Camera.prototype, "orthoBottom", void 0);
  23003. __decorate([
  23004. BABYLON.serialize()
  23005. ], Camera.prototype, "orthoTop", void 0);
  23006. __decorate([
  23007. BABYLON.serialize()
  23008. ], Camera.prototype, "fov", void 0);
  23009. __decorate([
  23010. BABYLON.serialize()
  23011. ], Camera.prototype, "minZ", void 0);
  23012. __decorate([
  23013. BABYLON.serialize()
  23014. ], Camera.prototype, "maxZ", void 0);
  23015. __decorate([
  23016. BABYLON.serialize()
  23017. ], Camera.prototype, "inertia", void 0);
  23018. __decorate([
  23019. BABYLON.serialize()
  23020. ], Camera.prototype, "mode", void 0);
  23021. __decorate([
  23022. BABYLON.serialize()
  23023. ], Camera.prototype, "layerMask", void 0);
  23024. __decorate([
  23025. BABYLON.serialize()
  23026. ], Camera.prototype, "fovMode", void 0);
  23027. __decorate([
  23028. BABYLON.serialize()
  23029. ], Camera.prototype, "cameraRigMode", void 0);
  23030. __decorate([
  23031. BABYLON.serialize()
  23032. ], Camera.prototype, "interaxialDistance", void 0);
  23033. __decorate([
  23034. BABYLON.serialize()
  23035. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23036. return Camera;
  23037. }(BABYLON.Node));
  23038. BABYLON.Camera = Camera;
  23039. })(BABYLON || (BABYLON = {}));
  23040. //# sourceMappingURL=babylon.camera.js.map
  23041. var BABYLON;
  23042. (function (BABYLON) {
  23043. var RenderingManager = /** @class */ (function () {
  23044. function RenderingManager(scene) {
  23045. this._renderingGroups = new Array();
  23046. this._autoClearDepthStencil = {};
  23047. this._customOpaqueSortCompareFn = {};
  23048. this._customAlphaTestSortCompareFn = {};
  23049. this._customTransparentSortCompareFn = {};
  23050. this._renderinGroupInfo = null;
  23051. this._scene = scene;
  23052. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23053. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23054. }
  23055. }
  23056. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23057. if (depth === void 0) { depth = true; }
  23058. if (stencil === void 0) { stencil = true; }
  23059. if (this._depthStencilBufferAlreadyCleaned) {
  23060. return;
  23061. }
  23062. this._scene.getEngine().clear(null, false, depth, stencil);
  23063. this._depthStencilBufferAlreadyCleaned = true;
  23064. };
  23065. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23066. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23067. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23068. var info = null;
  23069. if (observable) {
  23070. if (!this._renderinGroupInfo) {
  23071. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23072. }
  23073. info = this._renderinGroupInfo;
  23074. info.scene = this._scene;
  23075. info.camera = this._scene.activeCamera;
  23076. }
  23077. // Dispatch sprites
  23078. if (renderSprites) {
  23079. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23080. var manager = this._scene.spriteManagers[index];
  23081. this.dispatchSprites(manager);
  23082. }
  23083. }
  23084. // Render
  23085. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23086. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23087. var renderingGroup = this._renderingGroups[index];
  23088. if (!renderingGroup && !observable)
  23089. continue;
  23090. var renderingGroupMask = 0;
  23091. // Fire PRECLEAR stage
  23092. if (observable && info) {
  23093. renderingGroupMask = Math.pow(2, index);
  23094. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23095. info.renderingGroupId = index;
  23096. observable.notifyObservers(info, renderingGroupMask);
  23097. }
  23098. // Clear depth/stencil if needed
  23099. if (RenderingManager.AUTOCLEAR) {
  23100. var autoClear = this._autoClearDepthStencil[index];
  23101. if (autoClear && autoClear.autoClear) {
  23102. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23103. }
  23104. }
  23105. if (observable && info) {
  23106. // Fire PREOPAQUE stage
  23107. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23108. observable.notifyObservers(info, renderingGroupMask);
  23109. // Fire PRETRANSPARENT stage
  23110. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23111. observable.notifyObservers(info, renderingGroupMask);
  23112. }
  23113. if (renderingGroup)
  23114. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23115. // Fire POSTTRANSPARENT stage
  23116. if (observable && info) {
  23117. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23118. observable.notifyObservers(info, renderingGroupMask);
  23119. }
  23120. }
  23121. };
  23122. RenderingManager.prototype.reset = function () {
  23123. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23124. var renderingGroup = this._renderingGroups[index];
  23125. if (renderingGroup) {
  23126. renderingGroup.prepare();
  23127. }
  23128. }
  23129. };
  23130. RenderingManager.prototype.dispose = function () {
  23131. this.freeRenderingGroups();
  23132. this._renderingGroups.length = 0;
  23133. };
  23134. /**
  23135. * Clear the info related to rendering groups preventing retention points during dispose.
  23136. */
  23137. RenderingManager.prototype.freeRenderingGroups = function () {
  23138. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23139. var renderingGroup = this._renderingGroups[index];
  23140. if (renderingGroup) {
  23141. renderingGroup.dispose();
  23142. }
  23143. }
  23144. };
  23145. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23146. if (this._renderingGroups[renderingGroupId] === undefined) {
  23147. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23148. }
  23149. };
  23150. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23151. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23152. this._prepareRenderingGroup(renderingGroupId);
  23153. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23154. };
  23155. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23156. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23157. this._prepareRenderingGroup(renderingGroupId);
  23158. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23159. };
  23160. /**
  23161. * @param subMesh The submesh to dispatch
  23162. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23163. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23164. */
  23165. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23166. if (mesh === undefined) {
  23167. mesh = subMesh.getMesh();
  23168. }
  23169. var renderingGroupId = mesh.renderingGroupId || 0;
  23170. this._prepareRenderingGroup(renderingGroupId);
  23171. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23172. };
  23173. /**
  23174. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23175. * This allowed control for front to back rendering or reversly depending of the special needs.
  23176. *
  23177. * @param renderingGroupId The rendering group id corresponding to its index
  23178. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23179. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23180. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23181. */
  23182. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23183. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23184. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23185. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23186. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23187. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23188. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23189. if (this._renderingGroups[renderingGroupId]) {
  23190. var group = this._renderingGroups[renderingGroupId];
  23191. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23192. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23193. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23194. }
  23195. };
  23196. /**
  23197. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23198. *
  23199. * @param renderingGroupId The rendering group id corresponding to its index
  23200. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23201. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23202. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23203. */
  23204. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23205. if (depth === void 0) { depth = true; }
  23206. if (stencil === void 0) { stencil = true; }
  23207. this._autoClearDepthStencil[renderingGroupId] = {
  23208. autoClear: autoClearDepthStencil,
  23209. depth: depth,
  23210. stencil: stencil
  23211. };
  23212. };
  23213. /**
  23214. * The max id used for rendering groups (not included)
  23215. */
  23216. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23217. /**
  23218. * The min id used for rendering groups (included)
  23219. */
  23220. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23221. /**
  23222. * Used to globally prevent autoclearing scenes.
  23223. */
  23224. RenderingManager.AUTOCLEAR = true;
  23225. return RenderingManager;
  23226. }());
  23227. BABYLON.RenderingManager = RenderingManager;
  23228. })(BABYLON || (BABYLON = {}));
  23229. //# sourceMappingURL=babylon.renderingManager.js.map
  23230. var BABYLON;
  23231. (function (BABYLON) {
  23232. var RenderingGroup = /** @class */ (function () {
  23233. /**
  23234. * Creates a new rendering group.
  23235. * @param index The rendering group index
  23236. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23237. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23238. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23239. */
  23240. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23241. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23242. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23243. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23244. this.index = index;
  23245. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23246. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23247. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23248. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23249. this._particleSystems = new BABYLON.SmartArray(256);
  23250. this._spriteManagers = new BABYLON.SmartArray(256);
  23251. this._edgesRenderers = new BABYLON.SmartArray(16);
  23252. this._scene = scene;
  23253. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23254. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23255. this.transparentSortCompareFn = transparentSortCompareFn;
  23256. }
  23257. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23258. /**
  23259. * Set the opaque sort comparison function.
  23260. * If null the sub meshes will be render in the order they were created
  23261. */
  23262. set: function (value) {
  23263. this._opaqueSortCompareFn = value;
  23264. if (value) {
  23265. this._renderOpaque = this.renderOpaqueSorted;
  23266. }
  23267. else {
  23268. this._renderOpaque = RenderingGroup.renderUnsorted;
  23269. }
  23270. },
  23271. enumerable: true,
  23272. configurable: true
  23273. });
  23274. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23275. /**
  23276. * Set the alpha test sort comparison function.
  23277. * If null the sub meshes will be render in the order they were created
  23278. */
  23279. set: function (value) {
  23280. this._alphaTestSortCompareFn = value;
  23281. if (value) {
  23282. this._renderAlphaTest = this.renderAlphaTestSorted;
  23283. }
  23284. else {
  23285. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23286. }
  23287. },
  23288. enumerable: true,
  23289. configurable: true
  23290. });
  23291. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23292. /**
  23293. * Set the transparent sort comparison function.
  23294. * If null the sub meshes will be render in the order they were created
  23295. */
  23296. set: function (value) {
  23297. if (value) {
  23298. this._transparentSortCompareFn = value;
  23299. }
  23300. else {
  23301. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23302. }
  23303. this._renderTransparent = this.renderTransparentSorted;
  23304. },
  23305. enumerable: true,
  23306. configurable: true
  23307. });
  23308. /**
  23309. * Render all the sub meshes contained in the group.
  23310. * @param customRenderFunction Used to override the default render behaviour of the group.
  23311. * @returns true if rendered some submeshes.
  23312. */
  23313. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23314. if (customRenderFunction) {
  23315. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23316. return;
  23317. }
  23318. var engine = this._scene.getEngine();
  23319. // Depth only
  23320. if (this._depthOnlySubMeshes.length !== 0) {
  23321. engine.setColorWrite(false);
  23322. this._renderAlphaTest(this._depthOnlySubMeshes);
  23323. engine.setColorWrite(true);
  23324. }
  23325. // Opaque
  23326. if (this._opaqueSubMeshes.length !== 0) {
  23327. this._renderOpaque(this._opaqueSubMeshes);
  23328. }
  23329. // Alpha test
  23330. if (this._alphaTestSubMeshes.length !== 0) {
  23331. this._renderAlphaTest(this._alphaTestSubMeshes);
  23332. }
  23333. var stencilState = engine.getStencilBuffer();
  23334. engine.setStencilBuffer(false);
  23335. // Sprites
  23336. if (renderSprites) {
  23337. this._renderSprites();
  23338. }
  23339. // Particles
  23340. if (renderParticles) {
  23341. this._renderParticles(activeMeshes);
  23342. }
  23343. if (this.onBeforeTransparentRendering) {
  23344. this.onBeforeTransparentRendering();
  23345. }
  23346. // Transparent
  23347. if (this._transparentSubMeshes.length !== 0) {
  23348. this._renderTransparent(this._transparentSubMeshes);
  23349. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23350. }
  23351. // Set back stencil to false in case it changes before the edge renderer.
  23352. engine.setStencilBuffer(false);
  23353. // Edges
  23354. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23355. this._edgesRenderers.data[edgesRendererIndex].render();
  23356. }
  23357. // Restore Stencil state.
  23358. engine.setStencilBuffer(stencilState);
  23359. };
  23360. /**
  23361. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23362. * @param subMeshes The submeshes to render
  23363. */
  23364. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23365. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23366. };
  23367. /**
  23368. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23369. * @param subMeshes The submeshes to render
  23370. */
  23371. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23372. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23373. };
  23374. /**
  23375. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23376. * @param subMeshes The submeshes to render
  23377. */
  23378. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23379. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23380. };
  23381. /**
  23382. * Renders the submeshes in a specified order.
  23383. * @param subMeshes The submeshes to sort before render
  23384. * @param sortCompareFn The comparison function use to sort
  23385. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23386. * @param transparent Specifies to activate blending if true
  23387. */
  23388. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23389. var subIndex = 0;
  23390. var subMesh;
  23391. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23392. for (; subIndex < subMeshes.length; subIndex++) {
  23393. subMesh = subMeshes.data[subIndex];
  23394. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23395. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23396. }
  23397. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23398. if (sortCompareFn) {
  23399. sortedArray.sort(sortCompareFn);
  23400. }
  23401. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23402. subMesh = sortedArray[subIndex];
  23403. if (transparent) {
  23404. var material = subMesh.getMaterial();
  23405. if (material && material.needDepthPrePass) {
  23406. var engine = material.getScene().getEngine();
  23407. engine.setColorWrite(false);
  23408. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23409. subMesh.render(false);
  23410. engine.setColorWrite(true);
  23411. }
  23412. }
  23413. subMesh.render(transparent);
  23414. }
  23415. };
  23416. /**
  23417. * Renders the submeshes in the order they were dispatched (no sort applied).
  23418. * @param subMeshes The submeshes to render
  23419. */
  23420. RenderingGroup.renderUnsorted = function (subMeshes) {
  23421. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23422. var submesh = subMeshes.data[subIndex];
  23423. submesh.render(false);
  23424. }
  23425. };
  23426. /**
  23427. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23428. * are rendered back to front if in the same alpha index.
  23429. *
  23430. * @param a The first submesh
  23431. * @param b The second submesh
  23432. * @returns The result of the comparison
  23433. */
  23434. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23435. // Alpha index first
  23436. if (a._alphaIndex > b._alphaIndex) {
  23437. return 1;
  23438. }
  23439. if (a._alphaIndex < b._alphaIndex) {
  23440. return -1;
  23441. }
  23442. // Then distance to camera
  23443. return RenderingGroup.backToFrontSortCompare(a, b);
  23444. };
  23445. /**
  23446. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23447. * are rendered back to front.
  23448. *
  23449. * @param a The first submesh
  23450. * @param b The second submesh
  23451. * @returns The result of the comparison
  23452. */
  23453. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23454. // Then distance to camera
  23455. if (a._distanceToCamera < b._distanceToCamera) {
  23456. return 1;
  23457. }
  23458. if (a._distanceToCamera > b._distanceToCamera) {
  23459. return -1;
  23460. }
  23461. return 0;
  23462. };
  23463. /**
  23464. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23465. * are rendered front to back (prevent overdraw).
  23466. *
  23467. * @param a The first submesh
  23468. * @param b The second submesh
  23469. * @returns The result of the comparison
  23470. */
  23471. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23472. // Then distance to camera
  23473. if (a._distanceToCamera < b._distanceToCamera) {
  23474. return -1;
  23475. }
  23476. if (a._distanceToCamera > b._distanceToCamera) {
  23477. return 1;
  23478. }
  23479. return 0;
  23480. };
  23481. /**
  23482. * Resets the different lists of submeshes to prepare a new frame.
  23483. */
  23484. RenderingGroup.prototype.prepare = function () {
  23485. this._opaqueSubMeshes.reset();
  23486. this._transparentSubMeshes.reset();
  23487. this._alphaTestSubMeshes.reset();
  23488. this._depthOnlySubMeshes.reset();
  23489. this._particleSystems.reset();
  23490. this._spriteManagers.reset();
  23491. this._edgesRenderers.reset();
  23492. };
  23493. RenderingGroup.prototype.dispose = function () {
  23494. this._opaqueSubMeshes.dispose();
  23495. this._transparentSubMeshes.dispose();
  23496. this._alphaTestSubMeshes.dispose();
  23497. this._depthOnlySubMeshes.dispose();
  23498. this._particleSystems.dispose();
  23499. this._spriteManagers.dispose();
  23500. this._edgesRenderers.dispose();
  23501. };
  23502. /**
  23503. * Inserts the submesh in its correct queue depending on its material.
  23504. * @param subMesh The submesh to dispatch
  23505. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23506. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23507. */
  23508. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23509. // Get mesh and materials if not provided
  23510. if (mesh === undefined) {
  23511. mesh = subMesh.getMesh();
  23512. }
  23513. if (material === undefined) {
  23514. material = subMesh.getMaterial();
  23515. }
  23516. if (material === null || material === undefined) {
  23517. return;
  23518. }
  23519. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23520. this._transparentSubMeshes.push(subMesh);
  23521. }
  23522. else if (material.needAlphaTesting()) { // Alpha test
  23523. if (material.needDepthPrePass) {
  23524. this._depthOnlySubMeshes.push(subMesh);
  23525. }
  23526. this._alphaTestSubMeshes.push(subMesh);
  23527. }
  23528. else {
  23529. if (material.needDepthPrePass) {
  23530. this._depthOnlySubMeshes.push(subMesh);
  23531. }
  23532. this._opaqueSubMeshes.push(subMesh); // Opaque
  23533. }
  23534. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23535. this._edgesRenderers.push(mesh._edgesRenderer);
  23536. }
  23537. };
  23538. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23539. this._spriteManagers.push(spriteManager);
  23540. };
  23541. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23542. this._particleSystems.push(particleSystem);
  23543. };
  23544. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23545. if (this._particleSystems.length === 0) {
  23546. return;
  23547. }
  23548. // Particles
  23549. var activeCamera = this._scene.activeCamera;
  23550. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23551. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23552. var particleSystem = this._particleSystems.data[particleIndex];
  23553. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23554. continue;
  23555. }
  23556. var emitter = particleSystem.emitter;
  23557. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23558. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23559. }
  23560. }
  23561. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23562. };
  23563. RenderingGroup.prototype._renderSprites = function () {
  23564. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23565. return;
  23566. }
  23567. // Sprites
  23568. var activeCamera = this._scene.activeCamera;
  23569. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23570. for (var id = 0; id < this._spriteManagers.length; id++) {
  23571. var spriteManager = this._spriteManagers.data[id];
  23572. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23573. spriteManager.render();
  23574. }
  23575. }
  23576. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23577. };
  23578. return RenderingGroup;
  23579. }());
  23580. BABYLON.RenderingGroup = RenderingGroup;
  23581. })(BABYLON || (BABYLON = {}));
  23582. //# sourceMappingURL=babylon.renderingGroup.js.map
  23583. var BABYLON;
  23584. (function (BABYLON) {
  23585. /** @hidden */
  23586. var ClickInfo = /** @class */ (function () {
  23587. function ClickInfo() {
  23588. this._singleClick = false;
  23589. this._doubleClick = false;
  23590. this._hasSwiped = false;
  23591. this._ignore = false;
  23592. }
  23593. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23594. get: function () {
  23595. return this._singleClick;
  23596. },
  23597. set: function (b) {
  23598. this._singleClick = b;
  23599. },
  23600. enumerable: true,
  23601. configurable: true
  23602. });
  23603. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23604. get: function () {
  23605. return this._doubleClick;
  23606. },
  23607. set: function (b) {
  23608. this._doubleClick = b;
  23609. },
  23610. enumerable: true,
  23611. configurable: true
  23612. });
  23613. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23614. get: function () {
  23615. return this._hasSwiped;
  23616. },
  23617. set: function (b) {
  23618. this._hasSwiped = b;
  23619. },
  23620. enumerable: true,
  23621. configurable: true
  23622. });
  23623. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23624. get: function () {
  23625. return this._ignore;
  23626. },
  23627. set: function (b) {
  23628. this._ignore = b;
  23629. },
  23630. enumerable: true,
  23631. configurable: true
  23632. });
  23633. return ClickInfo;
  23634. }());
  23635. /**
  23636. * This class is used by the onRenderingGroupObservable
  23637. */
  23638. var RenderingGroupInfo = /** @class */ (function () {
  23639. function RenderingGroupInfo() {
  23640. }
  23641. /**
  23642. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23643. * This stage will be fired no matter what
  23644. */
  23645. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23646. /**
  23647. * Called before opaque object are rendered.
  23648. * This stage will be fired only if there's 3D Opaque content to render
  23649. */
  23650. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23651. /**
  23652. * Called after the opaque objects are rendered and before the transparent ones
  23653. * This stage will be fired only if there's 3D transparent content to render
  23654. */
  23655. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23656. /**
  23657. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23658. * This stage will be fired no matter what
  23659. */
  23660. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23661. return RenderingGroupInfo;
  23662. }());
  23663. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23664. /**
  23665. * Represents a scene to be rendered by the engine.
  23666. * @see http://doc.babylonjs.com/features/scene
  23667. */
  23668. var Scene = /** @class */ (function () {
  23669. /**
  23670. * Creates a new Scene
  23671. * @param engine defines the engine to use to render this scene
  23672. */
  23673. function Scene(engine) {
  23674. // Members
  23675. /**
  23676. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23677. */
  23678. this.autoClear = true;
  23679. /**
  23680. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23681. */
  23682. this.autoClearDepthAndStencil = true;
  23683. /**
  23684. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23685. */
  23686. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23687. /**
  23688. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23689. */
  23690. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23691. this._forceWireframe = false;
  23692. this._forcePointsCloud = false;
  23693. /**
  23694. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23695. */
  23696. this.forceShowBoundingBoxes = false;
  23697. /**
  23698. * Gets or sets a boolean indicating if animations are enabled
  23699. */
  23700. this.animationsEnabled = true;
  23701. this._animationPropertiesOverride = null;
  23702. /**
  23703. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23704. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23705. */
  23706. this.useConstantAnimationDeltaTime = false;
  23707. /**
  23708. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23709. * Please note that it requires to run a ray cast through the scene on every frame
  23710. */
  23711. this.constantlyUpdateMeshUnderPointer = false;
  23712. /**
  23713. * Defines the HTML cursor to use when hovering over interactive elements
  23714. */
  23715. this.hoverCursor = "pointer";
  23716. /**
  23717. * Defines the HTML default cursor to use (empty by default)
  23718. */
  23719. this.defaultCursor = "";
  23720. /**
  23721. * This is used to call preventDefault() on pointer down
  23722. * in order to block unwanted artifacts like system double clicks
  23723. */
  23724. this.preventDefaultOnPointerDown = true;
  23725. // Metadata
  23726. /**
  23727. * Gets or sets user defined metadata
  23728. */
  23729. this.metadata = null;
  23730. /**
  23731. * Use this array to add regular expressions used to disable offline support for specific urls
  23732. */
  23733. this.disableOfflineSupportExceptionRules = new Array();
  23734. /**
  23735. * An event triggered when the scene is disposed.
  23736. */
  23737. this.onDisposeObservable = new BABYLON.Observable();
  23738. this._onDisposeObserver = null;
  23739. /**
  23740. * An event triggered before rendering the scene (right after animations and physics)
  23741. */
  23742. this.onBeforeRenderObservable = new BABYLON.Observable();
  23743. this._onBeforeRenderObserver = null;
  23744. /**
  23745. * An event triggered after rendering the scene
  23746. */
  23747. this.onAfterRenderObservable = new BABYLON.Observable();
  23748. this._onAfterRenderObserver = null;
  23749. /**
  23750. * An event triggered before animating the scene
  23751. */
  23752. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23753. /**
  23754. * An event triggered after animations processing
  23755. */
  23756. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23757. /**
  23758. * An event triggered before draw calls are ready to be sent
  23759. */
  23760. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23761. /**
  23762. * An event triggered after draw calls have been sent
  23763. */
  23764. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23765. /**
  23766. * An event triggered when physic simulation is about to be run
  23767. */
  23768. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23769. /**
  23770. * An event triggered when physic simulation has been done
  23771. */
  23772. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23773. /**
  23774. * An event triggered when the scene is ready
  23775. */
  23776. this.onReadyObservable = new BABYLON.Observable();
  23777. /**
  23778. * An event triggered before rendering a camera
  23779. */
  23780. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23781. this._onBeforeCameraRenderObserver = null;
  23782. /**
  23783. * An event triggered after rendering a camera
  23784. */
  23785. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23786. this._onAfterCameraRenderObserver = null;
  23787. /**
  23788. * An event triggered when active meshes evaluation is about to start
  23789. */
  23790. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23791. /**
  23792. * An event triggered when active meshes evaluation is done
  23793. */
  23794. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23795. /**
  23796. * An event triggered when particles rendering is about to start
  23797. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23798. */
  23799. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23800. /**
  23801. * An event triggered when particles rendering is done
  23802. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23803. */
  23804. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23805. /**
  23806. * An event triggered when sprites rendering is about to start
  23807. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23808. */
  23809. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23810. /**
  23811. * An event triggered when sprites rendering is done
  23812. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23813. */
  23814. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23815. /**
  23816. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23817. */
  23818. this.onDataLoadedObservable = new BABYLON.Observable();
  23819. /**
  23820. * An event triggered when a camera is created
  23821. */
  23822. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23823. /**
  23824. * An event triggered when a camera is removed
  23825. */
  23826. this.onCameraRemovedObservable = new BABYLON.Observable();
  23827. /**
  23828. * An event triggered when a light is created
  23829. */
  23830. this.onNewLightAddedObservable = new BABYLON.Observable();
  23831. /**
  23832. * An event triggered when a light is removed
  23833. */
  23834. this.onLightRemovedObservable = new BABYLON.Observable();
  23835. /**
  23836. * An event triggered when a geometry is created
  23837. */
  23838. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23839. /**
  23840. * An event triggered when a geometry is removed
  23841. */
  23842. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23843. /**
  23844. * An event triggered when a transform node is created
  23845. */
  23846. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23847. /**
  23848. * An event triggered when a transform node is removed
  23849. */
  23850. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23851. /**
  23852. * An event triggered when a mesh is created
  23853. */
  23854. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23855. /**
  23856. * An event triggered when a mesh is removed
  23857. */
  23858. this.onMeshRemovedObservable = new BABYLON.Observable();
  23859. /**
  23860. * An event triggered when render targets are about to be rendered
  23861. * Can happen multiple times per frame.
  23862. */
  23863. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23864. /**
  23865. * An event triggered when render targets were rendered.
  23866. * Can happen multiple times per frame.
  23867. */
  23868. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23869. /**
  23870. * An event triggered before calculating deterministic simulation step
  23871. */
  23872. this.onBeforeStepObservable = new BABYLON.Observable();
  23873. /**
  23874. * An event triggered after calculating deterministic simulation step
  23875. */
  23876. this.onAfterStepObservable = new BABYLON.Observable();
  23877. /**
  23878. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23879. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23880. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  23881. */
  23882. this.onRenderingGroupObservable = new BABYLON.Observable();
  23883. // Animations
  23884. /**
  23885. * Gets a list of Animations associated with the scene
  23886. */
  23887. this.animations = [];
  23888. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23889. /**
  23890. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  23891. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23892. */
  23893. this.onPrePointerObservable = new BABYLON.Observable();
  23894. /**
  23895. * Observable event triggered each time an input event is received from the rendering canvas
  23896. */
  23897. this.onPointerObservable = new BABYLON.Observable();
  23898. this._meshPickProceed = false;
  23899. this._currentPickResult = null;
  23900. this._previousPickResult = null;
  23901. this._totalPointersPressed = 0;
  23902. this._doubleClickOccured = false;
  23903. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23904. this.cameraToUseForPointers = null;
  23905. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23906. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23907. this._startingPointerTime = 0;
  23908. this._previousStartingPointerTime = 0;
  23909. this._pointerCaptures = {};
  23910. // Deterministic lockstep
  23911. this._timeAccumulator = 0;
  23912. this._currentStepId = 0;
  23913. this._currentInternalStep = 0;
  23914. // Keyboard
  23915. /**
  23916. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23917. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23918. */
  23919. this.onPreKeyboardObservable = new BABYLON.Observable();
  23920. /**
  23921. * Observable event triggered each time an keyboard event is received from the hosting window
  23922. */
  23923. this.onKeyboardObservable = new BABYLON.Observable();
  23924. // Coordinates system
  23925. this._useRightHandedSystem = false;
  23926. // Fog
  23927. this._fogEnabled = true;
  23928. this._fogMode = Scene.FOGMODE_NONE;
  23929. /**
  23930. * Gets or sets the fog color to use
  23931. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23932. */
  23933. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23934. /**
  23935. * Gets or sets the fog density to use
  23936. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23937. */
  23938. this.fogDensity = 0.1;
  23939. /**
  23940. * Gets or sets the fog start distance to use
  23941. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23942. */
  23943. this.fogStart = 0;
  23944. /**
  23945. * Gets or sets the fog end distance to use
  23946. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23947. */
  23948. this.fogEnd = 1000.0;
  23949. // Lights
  23950. this._shadowsEnabled = true;
  23951. this._lightsEnabled = true;
  23952. /**
  23953. * All of the lights added to this scene
  23954. * @see http://doc.babylonjs.com/babylon101/lights
  23955. */
  23956. this.lights = new Array();
  23957. // Cameras
  23958. /** All of the cameras added to this scene.
  23959. * @see http://doc.babylonjs.com/babylon101/cameras
  23960. */
  23961. this.cameras = new Array();
  23962. /** All of the active cameras added to this scene. */
  23963. this.activeCameras = new Array();
  23964. // Meshes
  23965. /**
  23966. * All of the tranform nodes added to this scene
  23967. * @see http://doc.babylonjs.com/how_to/transformnode
  23968. */
  23969. this.transformNodes = new Array();
  23970. /**
  23971. * All of the (abstract) meshes added to this scene
  23972. */
  23973. this.meshes = new Array();
  23974. /**
  23975. * All of the animation groups added to this scene
  23976. * @see http://doc.babylonjs.com/how_to/group
  23977. */
  23978. this.animationGroups = new Array();
  23979. // Geometries
  23980. this._geometries = new Array();
  23981. /**
  23982. * All of the materials added to this scene
  23983. * @see http://doc.babylonjs.com/babylon101/materials
  23984. */
  23985. this.materials = new Array();
  23986. /**
  23987. * All of the multi-materials added to this scene
  23988. * @see http://doc.babylonjs.com/how_to/multi_materials
  23989. */
  23990. this.multiMaterials = new Array();
  23991. // Textures
  23992. this._texturesEnabled = true;
  23993. /**
  23994. * All of the textures added to this scene
  23995. */
  23996. this.textures = new Array();
  23997. // Particles
  23998. /**
  23999. * Gets or sets a boolean indicating if particles are enabled on this scene
  24000. */
  24001. this.particlesEnabled = true;
  24002. /**
  24003. * All of the particle systems added to this scene
  24004. * @see http://doc.babylonjs.com/babylon101/particles
  24005. */
  24006. this.particleSystems = new Array();
  24007. // Sprites
  24008. /**
  24009. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24010. */
  24011. this.spritesEnabled = true;
  24012. /**
  24013. * All of the sprite managers added to this scene
  24014. * @see http://doc.babylonjs.com/babylon101/sprites
  24015. */
  24016. this.spriteManagers = new Array();
  24017. /**
  24018. * The list of layers (background and foreground) of the scene
  24019. */
  24020. this.layers = new Array();
  24021. /**
  24022. * The list of effect layers (highlights/glow) added to the scene
  24023. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24024. * @see http://doc.babylonjs.com/how_to/glow_layer
  24025. */
  24026. this.effectLayers = new Array();
  24027. // Skeletons
  24028. this._skeletonsEnabled = true;
  24029. /**
  24030. * The list of skeletons added to the scene
  24031. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24032. */
  24033. this.skeletons = new Array();
  24034. // Morph targets
  24035. /**
  24036. * The list of morph target managers added to the scene
  24037. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24038. */
  24039. this.morphTargetManagers = new Array();
  24040. // Lens flares
  24041. /**
  24042. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24043. */
  24044. this.lensFlaresEnabled = true;
  24045. /**
  24046. * The list of lens flare system added to the scene
  24047. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24048. */
  24049. this.lensFlareSystems = new Array();
  24050. // Collisions
  24051. /**
  24052. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24053. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24054. */
  24055. this.collisionsEnabled = true;
  24056. /**
  24057. * Defines the gravity applied to this scene (used only for collisions)
  24058. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24059. */
  24060. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24061. // Postprocesses
  24062. /**
  24063. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24064. */
  24065. this.postProcessesEnabled = true;
  24066. /**
  24067. * The list of postprocesses added to the scene
  24068. */
  24069. this.postProcesses = new Array();
  24070. // Customs render targets
  24071. /**
  24072. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24073. */
  24074. this.renderTargetsEnabled = true;
  24075. /**
  24076. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24077. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24078. */
  24079. this.dumpNextRenderTargets = false;
  24080. /**
  24081. * The list of user defined render targets added to the scene
  24082. */
  24083. this.customRenderTargets = new Array();
  24084. /**
  24085. * Gets the list of meshes imported to the scene through SceneLoader
  24086. */
  24087. this.importedMeshesFiles = new Array();
  24088. // Probes
  24089. /**
  24090. * Gets or sets a boolean indicating if probes are enabled on this scene
  24091. */
  24092. this.probesEnabled = true;
  24093. /**
  24094. * The list of reflection probes added to the scene
  24095. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24096. */
  24097. this.reflectionProbes = new Array();
  24098. /** @hidden */
  24099. this._actionManagers = new Array();
  24100. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24101. // Procedural textures
  24102. /**
  24103. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24104. */
  24105. this.proceduralTexturesEnabled = true;
  24106. /**
  24107. * The list of procedural textures added to the scene
  24108. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24109. */
  24110. this.proceduralTextures = new Array();
  24111. /**
  24112. * The list of sound tracks added to the scene
  24113. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24114. */
  24115. this.soundTracks = new Array();
  24116. this._audioEnabled = true;
  24117. this._headphone = false;
  24118. // Performance counters
  24119. this._totalVertices = new BABYLON.PerfCounter();
  24120. /** @hidden */
  24121. this._activeIndices = new BABYLON.PerfCounter();
  24122. /** @hidden */
  24123. this._activeParticles = new BABYLON.PerfCounter();
  24124. /** @hidden */
  24125. this._activeBones = new BABYLON.PerfCounter();
  24126. this._animationTime = 0;
  24127. /**
  24128. * Gets or sets a general scale for animation speed
  24129. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24130. */
  24131. this.animationTimeScale = 1;
  24132. this._renderId = 0;
  24133. this._executeWhenReadyTimeoutId = -1;
  24134. this._intermediateRendering = false;
  24135. this._viewUpdateFlag = -1;
  24136. this._projectionUpdateFlag = -1;
  24137. this._alternateViewUpdateFlag = -1;
  24138. this._alternateProjectionUpdateFlag = -1;
  24139. /** @hidden */
  24140. this._toBeDisposed = new BABYLON.SmartArray(256);
  24141. this._activeRequests = new Array();
  24142. this._pendingData = new Array();
  24143. this._isDisposed = false;
  24144. /**
  24145. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24146. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24147. */
  24148. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24149. this._activeMeshes = new BABYLON.SmartArray(256);
  24150. this._processedMaterials = new BABYLON.SmartArray(256);
  24151. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24152. /** @hidden */
  24153. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24154. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24155. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24156. /** @hidden */
  24157. this._activeAnimatables = new Array();
  24158. this._transformMatrix = BABYLON.Matrix.Zero();
  24159. this._useAlternateCameraConfiguration = false;
  24160. this._alternateRendering = false;
  24161. /**
  24162. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24163. * This is useful if there are more lights that the maximum simulteanous authorized
  24164. */
  24165. this.requireLightSorting = false;
  24166. this._depthRenderer = {};
  24167. this._activeMeshesFrozen = false;
  24168. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24169. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24170. this._engine.scenes.push(this);
  24171. this._uid = null;
  24172. this._renderingManager = new BABYLON.RenderingManager(this);
  24173. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24174. if (BABYLON.OutlineRenderer) {
  24175. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24176. }
  24177. if (BABYLON.Tools.IsWindowObjectExist()) {
  24178. this.attachControl();
  24179. }
  24180. //simplification queue
  24181. if (BABYLON.SimplificationQueue) {
  24182. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24183. }
  24184. //collision coordinator initialization. For now legacy per default.
  24185. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24186. // Uniform Buffer
  24187. this._createUbo();
  24188. // Default Image processing definition.
  24189. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24190. }
  24191. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24192. /** The fog is deactivated */
  24193. get: function () {
  24194. return Scene._FOGMODE_NONE;
  24195. },
  24196. enumerable: true,
  24197. configurable: true
  24198. });
  24199. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24200. /** The fog density is following an exponential function */
  24201. get: function () {
  24202. return Scene._FOGMODE_EXP;
  24203. },
  24204. enumerable: true,
  24205. configurable: true
  24206. });
  24207. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24208. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24209. get: function () {
  24210. return Scene._FOGMODE_EXP2;
  24211. },
  24212. enumerable: true,
  24213. configurable: true
  24214. });
  24215. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24216. /** The fog density is following a linear function. */
  24217. get: function () {
  24218. return Scene._FOGMODE_LINEAR;
  24219. },
  24220. enumerable: true,
  24221. configurable: true
  24222. });
  24223. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24224. /**
  24225. * Texture used in all pbr material as the reflection texture.
  24226. * As in the majority of the scene they are the same (exception for multi room and so on),
  24227. * this is easier to reference from here than from all the materials.
  24228. */
  24229. get: function () {
  24230. return this._environmentTexture;
  24231. },
  24232. /**
  24233. * Texture used in all pbr material as the reflection texture.
  24234. * As in the majority of the scene they are the same (exception for multi room and so on),
  24235. * this is easier to set here than in all the materials.
  24236. */
  24237. set: function (value) {
  24238. if (this._environmentTexture === value) {
  24239. return;
  24240. }
  24241. this._environmentTexture = value;
  24242. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24248. /**
  24249. * Default image processing configuration used either in the rendering
  24250. * Forward main pass or through the imageProcessingPostProcess if present.
  24251. * As in the majority of the scene they are the same (exception for multi camera),
  24252. * this is easier to reference from here than from all the materials and post process.
  24253. *
  24254. * No setter as we it is a shared configuration, you can set the values instead.
  24255. */
  24256. get: function () {
  24257. return this._imageProcessingConfiguration;
  24258. },
  24259. enumerable: true,
  24260. configurable: true
  24261. });
  24262. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24263. get: function () {
  24264. return this._forceWireframe;
  24265. },
  24266. /**
  24267. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24268. */
  24269. set: function (value) {
  24270. if (this._forceWireframe === value) {
  24271. return;
  24272. }
  24273. this._forceWireframe = value;
  24274. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24275. },
  24276. enumerable: true,
  24277. configurable: true
  24278. });
  24279. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24280. get: function () {
  24281. return this._forcePointsCloud;
  24282. },
  24283. /**
  24284. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24285. */
  24286. set: function (value) {
  24287. if (this._forcePointsCloud === value) {
  24288. return;
  24289. }
  24290. this._forcePointsCloud = value;
  24291. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24292. },
  24293. enumerable: true,
  24294. configurable: true
  24295. });
  24296. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24297. /**
  24298. * Gets or sets the animation properties override
  24299. */
  24300. get: function () {
  24301. return this._animationPropertiesOverride;
  24302. },
  24303. set: function (value) {
  24304. this._animationPropertiesOverride = value;
  24305. },
  24306. enumerable: true,
  24307. configurable: true
  24308. });
  24309. Object.defineProperty(Scene.prototype, "onDispose", {
  24310. /** Sets a function to be executed when this scene is disposed. */
  24311. set: function (callback) {
  24312. if (this._onDisposeObserver) {
  24313. this.onDisposeObservable.remove(this._onDisposeObserver);
  24314. }
  24315. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24316. },
  24317. enumerable: true,
  24318. configurable: true
  24319. });
  24320. Object.defineProperty(Scene.prototype, "beforeRender", {
  24321. /** Sets a function to be executed before rendering this scene */
  24322. set: function (callback) {
  24323. if (this._onBeforeRenderObserver) {
  24324. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24325. }
  24326. if (callback) {
  24327. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24328. }
  24329. },
  24330. enumerable: true,
  24331. configurable: true
  24332. });
  24333. Object.defineProperty(Scene.prototype, "afterRender", {
  24334. /** Sets a function to be executed after rendering this scene */
  24335. set: function (callback) {
  24336. if (this._onAfterRenderObserver) {
  24337. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24338. }
  24339. if (callback) {
  24340. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24341. }
  24342. },
  24343. enumerable: true,
  24344. configurable: true
  24345. });
  24346. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24347. /** Sets a function to be executed before rendering a camera*/
  24348. set: function (callback) {
  24349. if (this._onBeforeCameraRenderObserver) {
  24350. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24351. }
  24352. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24353. },
  24354. enumerable: true,
  24355. configurable: true
  24356. });
  24357. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24358. /** Sets a function to be executed after rendering a camera*/
  24359. set: function (callback) {
  24360. if (this._onAfterCameraRenderObserver) {
  24361. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24362. }
  24363. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24364. },
  24365. enumerable: true,
  24366. configurable: true
  24367. });
  24368. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24369. /**
  24370. * Gets the gamepad manager associated with the scene
  24371. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24372. */
  24373. get: function () {
  24374. if (!this._gamepadManager) {
  24375. this._gamepadManager = new BABYLON.GamepadManager(this);
  24376. }
  24377. return this._gamepadManager;
  24378. },
  24379. enumerable: true,
  24380. configurable: true
  24381. });
  24382. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24383. /**
  24384. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24385. */
  24386. get: function () {
  24387. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24388. },
  24389. enumerable: true,
  24390. configurable: true
  24391. });
  24392. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24393. get: function () {
  24394. return this._useRightHandedSystem;
  24395. },
  24396. /**
  24397. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24398. */
  24399. set: function (value) {
  24400. if (this._useRightHandedSystem === value) {
  24401. return;
  24402. }
  24403. this._useRightHandedSystem = value;
  24404. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24405. },
  24406. enumerable: true,
  24407. configurable: true
  24408. });
  24409. /**
  24410. * Sets the step Id used by deterministic lock step
  24411. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24412. * @param newStepId defines the step Id
  24413. */
  24414. Scene.prototype.setStepId = function (newStepId) {
  24415. this._currentStepId = newStepId;
  24416. };
  24417. ;
  24418. /**
  24419. * Gets the step Id used by deterministic lock step
  24420. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24421. * @returns the step Id
  24422. */
  24423. Scene.prototype.getStepId = function () {
  24424. return this._currentStepId;
  24425. };
  24426. ;
  24427. /**
  24428. * Gets the internal step used by deterministic lock step
  24429. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24430. * @returns the internal step
  24431. */
  24432. Scene.prototype.getInternalStep = function () {
  24433. return this._currentInternalStep;
  24434. };
  24435. ;
  24436. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24437. get: function () {
  24438. return this._fogEnabled;
  24439. },
  24440. /**
  24441. * Gets or sets a boolean indicating if fog is enabled on this scene
  24442. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24443. */
  24444. set: function (value) {
  24445. if (this._fogEnabled === value) {
  24446. return;
  24447. }
  24448. this._fogEnabled = value;
  24449. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24450. },
  24451. enumerable: true,
  24452. configurable: true
  24453. });
  24454. Object.defineProperty(Scene.prototype, "fogMode", {
  24455. get: function () {
  24456. return this._fogMode;
  24457. },
  24458. /**
  24459. * Gets or sets the fog mode to use
  24460. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24461. */
  24462. set: function (value) {
  24463. if (this._fogMode === value) {
  24464. return;
  24465. }
  24466. this._fogMode = value;
  24467. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24468. },
  24469. enumerable: true,
  24470. configurable: true
  24471. });
  24472. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24473. get: function () {
  24474. return this._shadowsEnabled;
  24475. },
  24476. /**
  24477. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24478. */
  24479. set: function (value) {
  24480. if (this._shadowsEnabled === value) {
  24481. return;
  24482. }
  24483. this._shadowsEnabled = value;
  24484. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24485. },
  24486. enumerable: true,
  24487. configurable: true
  24488. });
  24489. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24490. get: function () {
  24491. return this._lightsEnabled;
  24492. },
  24493. /**
  24494. * Gets or sets a boolean indicating if lights are enabled on this scene
  24495. */
  24496. set: function (value) {
  24497. if (this._lightsEnabled === value) {
  24498. return;
  24499. }
  24500. this._lightsEnabled = value;
  24501. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24507. /** The default material used on meshes when no material is affected */
  24508. get: function () {
  24509. if (!this._defaultMaterial) {
  24510. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24511. }
  24512. return this._defaultMaterial;
  24513. },
  24514. /** The default material used on meshes when no material is affected */
  24515. set: function (value) {
  24516. this._defaultMaterial = value;
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24522. get: function () {
  24523. return this._texturesEnabled;
  24524. },
  24525. /**
  24526. * Gets or sets a boolean indicating if textures are enabled on this scene
  24527. */
  24528. set: function (value) {
  24529. if (this._texturesEnabled === value) {
  24530. return;
  24531. }
  24532. this._texturesEnabled = value;
  24533. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24539. get: function () {
  24540. return this._skeletonsEnabled;
  24541. },
  24542. /**
  24543. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24544. */
  24545. set: function (value) {
  24546. if (this._skeletonsEnabled === value) {
  24547. return;
  24548. }
  24549. this._skeletonsEnabled = value;
  24550. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24551. },
  24552. enumerable: true,
  24553. configurable: true
  24554. });
  24555. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24556. /**
  24557. * Gets the postprocess render pipeline manager
  24558. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24559. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24560. */
  24561. get: function () {
  24562. if (!this._postProcessRenderPipelineManager) {
  24563. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24564. }
  24565. return this._postProcessRenderPipelineManager;
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24571. /**
  24572. * Gets the main soundtrack associated with the scene
  24573. */
  24574. get: function () {
  24575. if (!this._mainSoundTrack) {
  24576. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24577. }
  24578. return this._mainSoundTrack;
  24579. },
  24580. enumerable: true,
  24581. configurable: true
  24582. });
  24583. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24584. /** @hidden */
  24585. get: function () {
  24586. return this._alternateRendering;
  24587. },
  24588. enumerable: true,
  24589. configurable: true
  24590. });
  24591. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24592. /**
  24593. * Gets the list of frustum planes (built from the active camera)
  24594. */
  24595. get: function () {
  24596. return this._frustumPlanes;
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24602. /**
  24603. * Gets the current geometry buffer associated to the scene.
  24604. */
  24605. get: function () {
  24606. return this._geometryBufferRenderer;
  24607. },
  24608. /**
  24609. * Sets the current geometry buffer for the scene.
  24610. */
  24611. set: function (geometryBufferRenderer) {
  24612. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24613. this._geometryBufferRenderer = geometryBufferRenderer;
  24614. }
  24615. },
  24616. enumerable: true,
  24617. configurable: true
  24618. });
  24619. Object.defineProperty(Scene.prototype, "debugLayer", {
  24620. /**
  24621. * Gets the debug layer associated with the scene
  24622. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24623. */
  24624. get: function () {
  24625. if (!this._debugLayer) {
  24626. this._debugLayer = new BABYLON.DebugLayer(this);
  24627. }
  24628. return this._debugLayer;
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24634. /**
  24635. * Gets a boolean indicating if collisions are processed on a web worker
  24636. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24637. */
  24638. get: function () {
  24639. return this._workerCollisions;
  24640. },
  24641. set: function (enabled) {
  24642. if (!BABYLON.CollisionCoordinatorLegacy) {
  24643. return;
  24644. }
  24645. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24646. this._workerCollisions = enabled;
  24647. if (this.collisionCoordinator) {
  24648. this.collisionCoordinator.destroy();
  24649. }
  24650. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24651. this.collisionCoordinator.init(this);
  24652. },
  24653. enumerable: true,
  24654. configurable: true
  24655. });
  24656. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24657. /**
  24658. * Gets the octree used to boost mesh selection (picking)
  24659. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24660. */
  24661. get: function () {
  24662. return this._selectionOctree;
  24663. },
  24664. enumerable: true,
  24665. configurable: true
  24666. });
  24667. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24668. /**
  24669. * Gets the mesh that is currently under the pointer
  24670. */
  24671. get: function () {
  24672. return this._pointerOverMesh;
  24673. },
  24674. enumerable: true,
  24675. configurable: true
  24676. });
  24677. Object.defineProperty(Scene.prototype, "pointerX", {
  24678. /**
  24679. * Gets the current on-screen X position of the pointer
  24680. */
  24681. get: function () {
  24682. return this._pointerX;
  24683. },
  24684. enumerable: true,
  24685. configurable: true
  24686. });
  24687. Object.defineProperty(Scene.prototype, "pointerY", {
  24688. /**
  24689. * Gets the current on-screen Y position of the pointer
  24690. */
  24691. get: function () {
  24692. return this._pointerY;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. /**
  24698. * Gets the cached material (ie. the latest rendered one)
  24699. * @returns the cached material
  24700. */
  24701. Scene.prototype.getCachedMaterial = function () {
  24702. return this._cachedMaterial;
  24703. };
  24704. /**
  24705. * Gets the cached effect (ie. the latest rendered one)
  24706. * @returns the cached effect
  24707. */
  24708. Scene.prototype.getCachedEffect = function () {
  24709. return this._cachedEffect;
  24710. };
  24711. /**
  24712. * Gets the cached visibility state (ie. the latest rendered one)
  24713. * @returns the cached visibility state
  24714. */
  24715. Scene.prototype.getCachedVisibility = function () {
  24716. return this._cachedVisibility;
  24717. };
  24718. /**
  24719. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24720. * @param material defines the current material
  24721. * @param effect defines the current effect
  24722. * @param visibility defines the current visibility state
  24723. * @returns true if one parameter is not cached
  24724. */
  24725. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24726. if (visibility === void 0) { visibility = 1; }
  24727. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24728. };
  24729. /**
  24730. * Gets the bounding box renderer associated with the scene
  24731. * @returns a BoundingBoxRenderer
  24732. */
  24733. Scene.prototype.getBoundingBoxRenderer = function () {
  24734. if (!this._boundingBoxRenderer) {
  24735. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24736. }
  24737. return this._boundingBoxRenderer;
  24738. };
  24739. /**
  24740. * Gets the outline renderer associated with the scene
  24741. * @returns a OutlineRenderer
  24742. */
  24743. Scene.prototype.getOutlineRenderer = function () {
  24744. return this._outlineRenderer;
  24745. };
  24746. /**
  24747. * Gets the engine associated with the scene
  24748. * @returns an Engine
  24749. */
  24750. Scene.prototype.getEngine = function () {
  24751. return this._engine;
  24752. };
  24753. /**
  24754. * Gets the total number of vertices rendered per frame
  24755. * @returns the total number of vertices rendered per frame
  24756. */
  24757. Scene.prototype.getTotalVertices = function () {
  24758. return this._totalVertices.current;
  24759. };
  24760. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24761. /**
  24762. * Gets the performance counter for total vertices
  24763. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24764. */
  24765. get: function () {
  24766. return this._totalVertices;
  24767. },
  24768. enumerable: true,
  24769. configurable: true
  24770. });
  24771. /**
  24772. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24773. * @returns the total number of active indices rendered per frame
  24774. */
  24775. Scene.prototype.getActiveIndices = function () {
  24776. return this._activeIndices.current;
  24777. };
  24778. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24779. /**
  24780. * Gets the performance counter for active indices
  24781. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24782. */
  24783. get: function () {
  24784. return this._activeIndices;
  24785. },
  24786. enumerable: true,
  24787. configurable: true
  24788. });
  24789. /**
  24790. * Gets the total number of active particles rendered per frame
  24791. * @returns the total number of active particles rendered per frame
  24792. */
  24793. Scene.prototype.getActiveParticles = function () {
  24794. return this._activeParticles.current;
  24795. };
  24796. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24797. /**
  24798. * Gets the performance counter for active particles
  24799. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24800. */
  24801. get: function () {
  24802. return this._activeParticles;
  24803. },
  24804. enumerable: true,
  24805. configurable: true
  24806. });
  24807. /**
  24808. * Gets the total number of active bones rendered per frame
  24809. * @returns the total number of active bones rendered per frame
  24810. */
  24811. Scene.prototype.getActiveBones = function () {
  24812. return this._activeBones.current;
  24813. };
  24814. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24815. /**
  24816. * Gets the performance counter for active bones
  24817. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24818. */
  24819. get: function () {
  24820. return this._activeBones;
  24821. },
  24822. enumerable: true,
  24823. configurable: true
  24824. });
  24825. /** @hidden */
  24826. Scene.prototype.getInterFramePerfCounter = function () {
  24827. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24828. return 0;
  24829. };
  24830. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24831. /** @hidden */
  24832. get: function () {
  24833. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24834. return null;
  24835. },
  24836. enumerable: true,
  24837. configurable: true
  24838. });
  24839. /** @hidden */
  24840. Scene.prototype.getLastFrameDuration = function () {
  24841. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24842. return 0;
  24843. };
  24844. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24845. /** @hidden */
  24846. get: function () {
  24847. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24848. return null;
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. /** @hidden */
  24854. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24855. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24856. return 0;
  24857. };
  24858. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24859. /** @hidden */
  24860. get: function () {
  24861. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24862. return null;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. /**
  24868. * Gets the array of active meshes
  24869. * @returns an array of AbstractMesh
  24870. */
  24871. Scene.prototype.getActiveMeshes = function () {
  24872. return this._activeMeshes;
  24873. };
  24874. /** @hidden */
  24875. Scene.prototype.getRenderTargetsDuration = function () {
  24876. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24877. return 0;
  24878. };
  24879. /** @hidden */
  24880. Scene.prototype.getRenderDuration = function () {
  24881. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24882. return 0;
  24883. };
  24884. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24885. /** @hidden */
  24886. get: function () {
  24887. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24888. return null;
  24889. },
  24890. enumerable: true,
  24891. configurable: true
  24892. });
  24893. /** @hidden */
  24894. Scene.prototype.getParticlesDuration = function () {
  24895. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24896. return 0;
  24897. };
  24898. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24899. /** @hidden */
  24900. get: function () {
  24901. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24902. return null;
  24903. },
  24904. enumerable: true,
  24905. configurable: true
  24906. });
  24907. /** @hidden */
  24908. Scene.prototype.getSpritesDuration = function () {
  24909. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24910. return 0;
  24911. };
  24912. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24913. /** @hidden */
  24914. get: function () {
  24915. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24916. return null;
  24917. },
  24918. enumerable: true,
  24919. configurable: true
  24920. });
  24921. /**
  24922. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24923. * @returns a number
  24924. */
  24925. Scene.prototype.getAnimationRatio = function () {
  24926. return this._animationRatio;
  24927. };
  24928. /**
  24929. * Gets an unique Id for the current frame
  24930. * @returns a number
  24931. */
  24932. Scene.prototype.getRenderId = function () {
  24933. return this._renderId;
  24934. };
  24935. /** Call this function if you want to manually increment the render Id*/
  24936. Scene.prototype.incrementRenderId = function () {
  24937. this._renderId++;
  24938. };
  24939. Scene.prototype._updatePointerPosition = function (evt) {
  24940. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24941. if (!canvasRect) {
  24942. return;
  24943. }
  24944. this._pointerX = evt.clientX - canvasRect.left;
  24945. this._pointerY = evt.clientY - canvasRect.top;
  24946. this._unTranslatedPointerX = this._pointerX;
  24947. this._unTranslatedPointerY = this._pointerY;
  24948. };
  24949. Scene.prototype._createUbo = function () {
  24950. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24951. this._sceneUbo.addUniform("viewProjection", 16);
  24952. this._sceneUbo.addUniform("view", 16);
  24953. };
  24954. Scene.prototype._createAlternateUbo = function () {
  24955. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24956. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24957. this._alternateSceneUbo.addUniform("view", 16);
  24958. };
  24959. // Pointers handling
  24960. /**
  24961. * Use this method to simulate a pointer move on a mesh
  24962. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24963. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24964. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24965. * @returns the current scene
  24966. */
  24967. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24968. var evt = new PointerEvent("pointermove", pointerEventInit);
  24969. return this._processPointerMove(pickResult, evt);
  24970. };
  24971. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24972. var canvas = this._engine.getRenderingCanvas();
  24973. if (!canvas) {
  24974. return this;
  24975. }
  24976. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24977. this.setPointerOverSprite(null);
  24978. this.setPointerOverMesh(pickResult.pickedMesh);
  24979. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24980. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24981. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24982. }
  24983. else {
  24984. canvas.style.cursor = this.hoverCursor;
  24985. }
  24986. }
  24987. else {
  24988. canvas.style.cursor = this.defaultCursor;
  24989. }
  24990. }
  24991. else {
  24992. this.setPointerOverMesh(null);
  24993. // Sprites
  24994. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24995. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24996. this.setPointerOverSprite(pickResult.pickedSprite);
  24997. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24998. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24999. }
  25000. else {
  25001. canvas.style.cursor = this.hoverCursor;
  25002. }
  25003. }
  25004. else {
  25005. this.setPointerOverSprite(null);
  25006. // Restore pointer
  25007. canvas.style.cursor = this.defaultCursor;
  25008. }
  25009. }
  25010. if (pickResult) {
  25011. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25012. if (this.onPointerMove) {
  25013. this.onPointerMove(evt, pickResult, type);
  25014. }
  25015. if (this.onPointerObservable.hasObservers()) {
  25016. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25017. this.onPointerObservable.notifyObservers(pi, type);
  25018. }
  25019. }
  25020. return this;
  25021. };
  25022. /**
  25023. * Use this method to simulate a pointer down on a mesh
  25024. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25025. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25026. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25027. * @returns the current scene
  25028. */
  25029. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25030. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25031. return this._processPointerDown(pickResult, evt);
  25032. };
  25033. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25034. var _this = this;
  25035. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25036. this._pickedDownMesh = pickResult.pickedMesh;
  25037. var actionManager = pickResult.pickedMesh.actionManager;
  25038. if (actionManager) {
  25039. if (actionManager.hasPickTriggers) {
  25040. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25041. switch (evt.button) {
  25042. case 0:
  25043. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25044. break;
  25045. case 1:
  25046. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25047. break;
  25048. case 2:
  25049. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25050. break;
  25051. }
  25052. }
  25053. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25054. window.setTimeout(function () {
  25055. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
  25056. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25057. if (_this._totalPointersPressed !== 0 &&
  25058. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25059. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25060. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25061. _this._startingPointerTime = 0;
  25062. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25063. }
  25064. }
  25065. }, Scene.LongPressDelay);
  25066. }
  25067. }
  25068. }
  25069. if (pickResult) {
  25070. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25071. if (this.onPointerDown) {
  25072. this.onPointerDown(evt, pickResult, type);
  25073. }
  25074. if (this.onPointerObservable.hasObservers()) {
  25075. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25076. this.onPointerObservable.notifyObservers(pi, type);
  25077. }
  25078. }
  25079. return this;
  25080. };
  25081. /**
  25082. * Use this method to simulate a pointer up on a mesh
  25083. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25084. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25085. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25086. * @returns the current scene
  25087. */
  25088. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25089. var evt = new PointerEvent("pointerup", pointerEventInit);
  25090. var clickInfo = new ClickInfo();
  25091. clickInfo.singleClick = true;
  25092. clickInfo.ignore = true;
  25093. return this._processPointerUp(pickResult, evt, clickInfo);
  25094. };
  25095. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25096. if (pickResult && pickResult && pickResult.pickedMesh) {
  25097. this._pickedUpMesh = pickResult.pickedMesh;
  25098. if (this._pickedDownMesh === this._pickedUpMesh) {
  25099. if (this.onPointerPick) {
  25100. this.onPointerPick(evt, pickResult);
  25101. }
  25102. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25103. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25104. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25105. this.onPointerObservable.notifyObservers(pi, type_1);
  25106. }
  25107. }
  25108. if (pickResult.pickedMesh.actionManager) {
  25109. if (clickInfo.ignore) {
  25110. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25111. }
  25112. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25113. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25114. }
  25115. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25116. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25117. }
  25118. }
  25119. }
  25120. if (this._pickedDownMesh &&
  25121. this._pickedDownMesh.actionManager &&
  25122. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25123. this._pickedDownMesh !== this._pickedUpMesh) {
  25124. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25125. }
  25126. var type = BABYLON.PointerEventTypes.POINTERUP;
  25127. if (this.onPointerObservable.hasObservers()) {
  25128. if (!clickInfo.ignore) {
  25129. if (!clickInfo.hasSwiped) {
  25130. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25131. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25132. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25133. this.onPointerObservable.notifyObservers(pi, type_2);
  25134. }
  25135. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25136. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25137. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25138. this.onPointerObservable.notifyObservers(pi, type_3);
  25139. }
  25140. }
  25141. }
  25142. else {
  25143. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25144. this.onPointerObservable.notifyObservers(pi, type);
  25145. }
  25146. }
  25147. if (this.onPointerUp) {
  25148. this.onPointerUp(evt, pickResult, type);
  25149. }
  25150. return this;
  25151. };
  25152. /**
  25153. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25154. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25155. * @returns true if the pointer was captured
  25156. */
  25157. Scene.prototype.isPointerCaptured = function (pointerId) {
  25158. if (pointerId === void 0) { pointerId = 0; }
  25159. return this._pointerCaptures[pointerId];
  25160. };
  25161. /**
  25162. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25163. * @param attachUp defines if you want to attach events to pointerup
  25164. * @param attachDown defines if you want to attach events to pointerdown
  25165. * @param attachMove defines if you want to attach events to pointermove
  25166. */
  25167. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25168. var _this = this;
  25169. if (attachUp === void 0) { attachUp = true; }
  25170. if (attachDown === void 0) { attachDown = true; }
  25171. if (attachMove === void 0) { attachMove = true; }
  25172. this._initActionManager = function (act, clickInfo) {
  25173. if (!_this._meshPickProceed) {
  25174. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25175. _this._currentPickResult = pickResult;
  25176. if (pickResult) {
  25177. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25178. }
  25179. _this._meshPickProceed = true;
  25180. }
  25181. return act;
  25182. };
  25183. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25184. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25185. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25186. btn !== _this._previousButtonPressed) {
  25187. _this._doubleClickOccured = false;
  25188. clickInfo.singleClick = true;
  25189. clickInfo.ignore = false;
  25190. cb(clickInfo, _this._currentPickResult);
  25191. }
  25192. };
  25193. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25194. var clickInfo = new ClickInfo();
  25195. _this._currentPickResult = null;
  25196. var act = null;
  25197. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25198. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25199. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25200. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25201. act = _this._initActionManager(act, clickInfo);
  25202. if (act)
  25203. checkPicking = act.hasPickTriggers;
  25204. }
  25205. if (checkPicking) {
  25206. var btn = evt.button;
  25207. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25208. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25209. if (!clickInfo.hasSwiped) {
  25210. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25211. if (!checkSingleClickImmediately) {
  25212. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25213. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25214. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25215. act = _this._initActionManager(act, clickInfo);
  25216. if (act)
  25217. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25218. }
  25219. }
  25220. if (checkSingleClickImmediately) {
  25221. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25222. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25223. btn !== _this._previousButtonPressed) {
  25224. clickInfo.singleClick = true;
  25225. cb(clickInfo, _this._currentPickResult);
  25226. }
  25227. }
  25228. // at least one double click is required to be check and exclusive double click is enabled
  25229. else {
  25230. // wait that no double click has been raised during the double click delay
  25231. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25232. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25233. }
  25234. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25235. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25236. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25237. act = _this._initActionManager(act, clickInfo);
  25238. if (act)
  25239. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25240. }
  25241. if (checkDoubleClick) {
  25242. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25243. if (btn === _this._previousButtonPressed &&
  25244. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25245. !_this._doubleClickOccured) {
  25246. // pointer has not moved for 2 clicks, it's a double click
  25247. if (!clickInfo.hasSwiped &&
  25248. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25249. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25250. _this._previousStartingPointerTime = 0;
  25251. _this._doubleClickOccured = true;
  25252. clickInfo.doubleClick = true;
  25253. clickInfo.ignore = false;
  25254. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25255. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25256. }
  25257. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25258. cb(clickInfo, _this._currentPickResult);
  25259. }
  25260. // if the two successive clicks are too far, it's just two simple clicks
  25261. else {
  25262. _this._doubleClickOccured = false;
  25263. _this._previousStartingPointerTime = _this._startingPointerTime;
  25264. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25265. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25266. _this._previousButtonPressed = btn;
  25267. if (Scene.ExclusiveDoubleClickMode) {
  25268. if (_this._previousDelayedSimpleClickTimeout) {
  25269. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25270. }
  25271. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25272. cb(clickInfo, _this._previousPickResult);
  25273. }
  25274. else {
  25275. cb(clickInfo, _this._currentPickResult);
  25276. }
  25277. }
  25278. }
  25279. // just the first click of the double has been raised
  25280. else {
  25281. _this._doubleClickOccured = false;
  25282. _this._previousStartingPointerTime = _this._startingPointerTime;
  25283. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25284. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25285. _this._previousButtonPressed = btn;
  25286. }
  25287. }
  25288. }
  25289. }
  25290. clickInfo.ignore = true;
  25291. cb(clickInfo, _this._currentPickResult);
  25292. };
  25293. this._spritePredicate = function (sprite) {
  25294. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25295. };
  25296. this._onPointerMove = function (evt) {
  25297. _this._updatePointerPosition(evt);
  25298. // PreObservable support
  25299. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25300. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25301. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25302. _this.onPrePointerObservable.notifyObservers(pi, type);
  25303. if (pi.skipOnPointerObservable) {
  25304. return;
  25305. }
  25306. }
  25307. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25308. return;
  25309. }
  25310. if (!_this.pointerMovePredicate) {
  25311. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25312. }
  25313. // Meshes
  25314. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25315. _this._processPointerMove(pickResult, evt);
  25316. };
  25317. this._onPointerDown = function (evt) {
  25318. _this._totalPointersPressed++;
  25319. _this._pickedDownMesh = null;
  25320. _this._meshPickProceed = false;
  25321. _this._updatePointerPosition(evt);
  25322. if (_this.preventDefaultOnPointerDown && canvas) {
  25323. evt.preventDefault();
  25324. canvas.focus();
  25325. }
  25326. // PreObservable support
  25327. if (_this.onPrePointerObservable.hasObservers()) {
  25328. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25329. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25330. _this.onPrePointerObservable.notifyObservers(pi, type);
  25331. if (pi.skipOnPointerObservable) {
  25332. return;
  25333. }
  25334. }
  25335. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25336. return;
  25337. }
  25338. _this._pointerCaptures[evt.pointerId] = true;
  25339. _this._startingPointerPosition.x = _this._pointerX;
  25340. _this._startingPointerPosition.y = _this._pointerY;
  25341. _this._startingPointerTime = Date.now();
  25342. if (!_this.pointerDownPredicate) {
  25343. _this.pointerDownPredicate = function (mesh) {
  25344. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25345. };
  25346. }
  25347. // Meshes
  25348. _this._pickedDownMesh = null;
  25349. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25350. _this._processPointerDown(pickResult, evt);
  25351. // Sprites
  25352. _this._pickedDownSprite = null;
  25353. if (_this.spriteManagers.length > 0) {
  25354. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25355. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25356. if (pickResult.pickedSprite.actionManager) {
  25357. _this._pickedDownSprite = pickResult.pickedSprite;
  25358. switch (evt.button) {
  25359. case 0:
  25360. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25361. break;
  25362. case 1:
  25363. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25364. break;
  25365. case 2:
  25366. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25367. break;
  25368. }
  25369. if (pickResult.pickedSprite.actionManager) {
  25370. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25371. }
  25372. }
  25373. }
  25374. }
  25375. };
  25376. this._onPointerUp = function (evt) {
  25377. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25378. return; // So we need to test it the pointer down was pressed before.
  25379. }
  25380. _this._totalPointersPressed--;
  25381. _this._pickedUpMesh = null;
  25382. _this._meshPickProceed = false;
  25383. _this._updatePointerPosition(evt);
  25384. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25385. // PreObservable support
  25386. if (_this.onPrePointerObservable.hasObservers()) {
  25387. if (!clickInfo.ignore) {
  25388. if (!clickInfo.hasSwiped) {
  25389. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25390. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25391. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25392. _this.onPrePointerObservable.notifyObservers(pi, type);
  25393. if (pi.skipOnPointerObservable) {
  25394. return;
  25395. }
  25396. }
  25397. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25398. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25399. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25400. _this.onPrePointerObservable.notifyObservers(pi, type);
  25401. if (pi.skipOnPointerObservable) {
  25402. return;
  25403. }
  25404. }
  25405. }
  25406. }
  25407. else {
  25408. var type = BABYLON.PointerEventTypes.POINTERUP;
  25409. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25410. _this.onPrePointerObservable.notifyObservers(pi, type);
  25411. if (pi.skipOnPointerObservable) {
  25412. return;
  25413. }
  25414. }
  25415. }
  25416. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25417. return;
  25418. }
  25419. _this._pointerCaptures[evt.pointerId] = false;
  25420. if (!_this.pointerUpPredicate) {
  25421. _this.pointerUpPredicate = function (mesh) {
  25422. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25423. };
  25424. }
  25425. // Meshes
  25426. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25427. _this._initActionManager(null, clickInfo);
  25428. }
  25429. if (!pickResult) {
  25430. pickResult = _this._currentPickResult;
  25431. }
  25432. _this._processPointerUp(pickResult, evt, clickInfo);
  25433. // Sprites
  25434. if (!clickInfo.ignore) {
  25435. if (_this.spriteManagers.length > 0) {
  25436. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25437. if (spritePickResult) {
  25438. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25439. if (spritePickResult.pickedSprite.actionManager) {
  25440. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25441. if (spritePickResult.pickedSprite.actionManager) {
  25442. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25443. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25444. }
  25445. }
  25446. }
  25447. }
  25448. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25449. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25450. }
  25451. }
  25452. }
  25453. }
  25454. _this._previousPickResult = _this._currentPickResult;
  25455. });
  25456. };
  25457. this._onKeyDown = function (evt) {
  25458. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25459. if (_this.onPreKeyboardObservable.hasObservers()) {
  25460. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25461. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25462. if (pi.skipOnPointerObservable) {
  25463. return;
  25464. }
  25465. }
  25466. if (_this.onKeyboardObservable.hasObservers()) {
  25467. var pi = new BABYLON.KeyboardInfo(type, evt);
  25468. _this.onKeyboardObservable.notifyObservers(pi, type);
  25469. }
  25470. if (_this.actionManager) {
  25471. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25472. }
  25473. };
  25474. this._onKeyUp = function (evt) {
  25475. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25476. if (_this.onPreKeyboardObservable.hasObservers()) {
  25477. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25478. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25479. if (pi.skipOnPointerObservable) {
  25480. return;
  25481. }
  25482. }
  25483. if (_this.onKeyboardObservable.hasObservers()) {
  25484. var pi = new BABYLON.KeyboardInfo(type, evt);
  25485. _this.onKeyboardObservable.notifyObservers(pi, type);
  25486. }
  25487. if (_this.actionManager) {
  25488. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25489. }
  25490. };
  25491. var engine = this.getEngine();
  25492. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25493. if (!canvas) {
  25494. return;
  25495. }
  25496. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25497. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25498. });
  25499. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25500. if (!canvas) {
  25501. return;
  25502. }
  25503. canvas.removeEventListener("keydown", _this._onKeyDown);
  25504. canvas.removeEventListener("keyup", _this._onKeyUp);
  25505. });
  25506. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25507. var canvas = this._engine.getRenderingCanvas();
  25508. if (!canvas) {
  25509. return;
  25510. }
  25511. if (attachMove) {
  25512. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25513. // Wheel
  25514. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25515. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25516. }
  25517. if (attachDown) {
  25518. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25519. }
  25520. if (attachUp) {
  25521. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25522. }
  25523. canvas.tabIndex = 1;
  25524. };
  25525. /** Detaches all event handlers*/
  25526. Scene.prototype.detachControl = function () {
  25527. var engine = this.getEngine();
  25528. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25529. var canvas = engine.getRenderingCanvas();
  25530. if (!canvas) {
  25531. return;
  25532. }
  25533. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25534. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25535. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25536. if (this._onCanvasBlurObserver) {
  25537. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25538. }
  25539. if (this._onCanvasFocusObserver) {
  25540. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25541. }
  25542. // Wheel
  25543. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25544. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25545. // Keyboard
  25546. canvas.removeEventListener("keydown", this._onKeyDown);
  25547. canvas.removeEventListener("keyup", this._onKeyUp);
  25548. // Observables
  25549. this.onKeyboardObservable.clear();
  25550. this.onPreKeyboardObservable.clear();
  25551. this.onPointerObservable.clear();
  25552. this.onPrePointerObservable.clear();
  25553. };
  25554. /**
  25555. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25556. * Delay loaded resources are not taking in account
  25557. * @return true if all required resources are ready
  25558. */
  25559. Scene.prototype.isReady = function () {
  25560. if (this._isDisposed) {
  25561. return false;
  25562. }
  25563. if (this._pendingData.length > 0) {
  25564. return false;
  25565. }
  25566. var index;
  25567. var engine = this.getEngine();
  25568. // Geometries
  25569. for (index = 0; index < this._geometries.length; index++) {
  25570. var geometry = this._geometries[index];
  25571. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25572. return false;
  25573. }
  25574. }
  25575. // Meshes
  25576. for (index = 0; index < this.meshes.length; index++) {
  25577. var mesh = this.meshes[index];
  25578. if (!mesh.isEnabled()) {
  25579. continue;
  25580. }
  25581. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25582. continue;
  25583. }
  25584. if (!mesh.isReady(true)) {
  25585. return false;
  25586. }
  25587. // Effect layers
  25588. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25589. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25590. var layer = _a[_i];
  25591. if (!layer.hasMesh(mesh)) {
  25592. continue;
  25593. }
  25594. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25595. var subMesh = _c[_b];
  25596. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25597. return false;
  25598. }
  25599. }
  25600. }
  25601. }
  25602. // Post-processes
  25603. if (this.activeCameras && this.activeCameras.length > 0) {
  25604. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25605. var camera = _e[_d];
  25606. if (!camera.isReady(true)) {
  25607. return false;
  25608. }
  25609. }
  25610. }
  25611. else if (this.activeCamera) {
  25612. if (!this.activeCamera.isReady(true)) {
  25613. return false;
  25614. }
  25615. }
  25616. // Particles
  25617. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25618. var particleSystem = _g[_f];
  25619. if (!particleSystem.isReady()) {
  25620. return false;
  25621. }
  25622. }
  25623. return true;
  25624. };
  25625. /** Resets all cached information relative to material (including effect and visibility) */
  25626. Scene.prototype.resetCachedMaterial = function () {
  25627. this._cachedMaterial = null;
  25628. this._cachedEffect = null;
  25629. this._cachedVisibility = null;
  25630. };
  25631. /**
  25632. * Registers a function to be called before every frame render
  25633. * @param func defines the function to register
  25634. */
  25635. Scene.prototype.registerBeforeRender = function (func) {
  25636. this.onBeforeRenderObservable.add(func);
  25637. };
  25638. /**
  25639. * Unregisters a function called before every frame render
  25640. * @param func defines the function to unregister
  25641. */
  25642. Scene.prototype.unregisterBeforeRender = function (func) {
  25643. this.onBeforeRenderObservable.removeCallback(func);
  25644. };
  25645. /**
  25646. * Registers a function to be called after every frame render
  25647. * @param func defines the function to register
  25648. */
  25649. Scene.prototype.registerAfterRender = function (func) {
  25650. this.onAfterRenderObservable.add(func);
  25651. };
  25652. /**
  25653. * Unregisters a function called after every frame render
  25654. * @param func defines the function to unregister
  25655. */
  25656. Scene.prototype.unregisterAfterRender = function (func) {
  25657. this.onAfterRenderObservable.removeCallback(func);
  25658. };
  25659. Scene.prototype._executeOnceBeforeRender = function (func) {
  25660. var _this = this;
  25661. var execFunc = function () {
  25662. func();
  25663. setTimeout(function () {
  25664. _this.unregisterBeforeRender(execFunc);
  25665. });
  25666. };
  25667. this.registerBeforeRender(execFunc);
  25668. };
  25669. /**
  25670. * The provided function will run before render once and will be disposed afterwards.
  25671. * A timeout delay can be provided so that the function will be executed in N ms.
  25672. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25673. * @param func The function to be executed.
  25674. * @param timeout optional delay in ms
  25675. */
  25676. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25677. var _this = this;
  25678. if (timeout !== undefined) {
  25679. setTimeout(function () {
  25680. _this._executeOnceBeforeRender(func);
  25681. }, timeout);
  25682. }
  25683. else {
  25684. this._executeOnceBeforeRender(func);
  25685. }
  25686. };
  25687. /** @hidden */
  25688. Scene.prototype._addPendingData = function (data) {
  25689. this._pendingData.push(data);
  25690. };
  25691. /** @hidden */
  25692. Scene.prototype._removePendingData = function (data) {
  25693. var wasLoading = this.isLoading;
  25694. var index = this._pendingData.indexOf(data);
  25695. if (index !== -1) {
  25696. this._pendingData.splice(index, 1);
  25697. }
  25698. if (wasLoading && !this.isLoading) {
  25699. this.onDataLoadedObservable.notifyObservers(this);
  25700. }
  25701. };
  25702. /**
  25703. * Returns the number of items waiting to be loaded
  25704. * @returns the number of items waiting to be loaded
  25705. */
  25706. Scene.prototype.getWaitingItemsCount = function () {
  25707. return this._pendingData.length;
  25708. };
  25709. Object.defineProperty(Scene.prototype, "isLoading", {
  25710. /**
  25711. * Returns a boolean indicating if the scene is still loading data
  25712. */
  25713. get: function () {
  25714. return this._pendingData.length > 0;
  25715. },
  25716. enumerable: true,
  25717. configurable: true
  25718. });
  25719. /**
  25720. * Registers a function to be executed when the scene is ready
  25721. * @param {Function} func - the function to be executed
  25722. */
  25723. Scene.prototype.executeWhenReady = function (func) {
  25724. var _this = this;
  25725. this.onReadyObservable.add(func);
  25726. if (this._executeWhenReadyTimeoutId !== -1) {
  25727. return;
  25728. }
  25729. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25730. _this._checkIsReady();
  25731. }, 150);
  25732. };
  25733. /**
  25734. * Returns a promise that resolves when the scene is ready
  25735. * @returns A promise that resolves when the scene is ready
  25736. */
  25737. Scene.prototype.whenReadyAsync = function () {
  25738. var _this = this;
  25739. return new Promise(function (resolve) {
  25740. _this.executeWhenReady(function () {
  25741. resolve();
  25742. });
  25743. });
  25744. };
  25745. /** @hidden */
  25746. Scene.prototype._checkIsReady = function () {
  25747. var _this = this;
  25748. if (this.isReady()) {
  25749. this.onReadyObservable.notifyObservers(this);
  25750. this.onReadyObservable.clear();
  25751. this._executeWhenReadyTimeoutId = -1;
  25752. return;
  25753. }
  25754. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25755. _this._checkIsReady();
  25756. }, 150);
  25757. };
  25758. // Animations
  25759. /**
  25760. * Will start the animation sequence of a given target
  25761. * @param target defines the target
  25762. * @param from defines from which frame should animation start
  25763. * @param to defines until which frame should animation run.
  25764. * @param weight defines the weight to apply to the animation (1.0 by default)
  25765. * @param loop defines if the animation loops
  25766. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25767. * @param onAnimationEnd defines the function to be executed when the animation ends
  25768. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25769. * @returns the animatable object created for this animation
  25770. */
  25771. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25772. if (weight === void 0) { weight = 1.0; }
  25773. if (speedRatio === void 0) { speedRatio = 1.0; }
  25774. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25775. returnedAnimatable.weight = weight;
  25776. return returnedAnimatable;
  25777. };
  25778. /**
  25779. * Will start the animation sequence of a given target
  25780. * @param target defines the target
  25781. * @param from defines from which frame should animation start
  25782. * @param to defines until which frame should animation run.
  25783. * @param loop defines if the animation loops
  25784. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25785. * @param onAnimationEnd defines the function to be executed when the animation ends
  25786. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25787. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25788. * @returns the animatable object created for this animation
  25789. */
  25790. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25791. if (speedRatio === void 0) { speedRatio = 1.0; }
  25792. if (stopCurrent === void 0) { stopCurrent = true; }
  25793. if (from > to && speedRatio > 0) {
  25794. speedRatio *= -1;
  25795. }
  25796. if (stopCurrent) {
  25797. this.stopAnimation(target);
  25798. }
  25799. if (!animatable) {
  25800. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25801. }
  25802. // Local animations
  25803. if (target.animations) {
  25804. animatable.appendAnimations(target, target.animations);
  25805. }
  25806. // Children animations
  25807. if (target.getAnimatables) {
  25808. var animatables = target.getAnimatables();
  25809. for (var index = 0; index < animatables.length; index++) {
  25810. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25811. }
  25812. }
  25813. animatable.reset();
  25814. return animatable;
  25815. };
  25816. /**
  25817. * Begin a new animation on a given node
  25818. * @param target defines the target where the animation will take place
  25819. * @param animations defines the list of animations to start
  25820. * @param from defines the initial value
  25821. * @param to defines the final value
  25822. * @param loop defines if you want animation to loop (off by default)
  25823. * @param speedRatio defines the speed ratio to apply to all animations
  25824. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25825. * @returns the list of created animatables
  25826. */
  25827. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25828. if (speedRatio === undefined) {
  25829. speedRatio = 1.0;
  25830. }
  25831. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25832. return animatable;
  25833. };
  25834. /**
  25835. * Begin a new animation on a given node and its hierarchy
  25836. * @param target defines the root node where the animation will take place
  25837. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25838. * @param animations defines the list of animations to start
  25839. * @param from defines the initial value
  25840. * @param to defines the final value
  25841. * @param loop defines if you want animation to loop (off by default)
  25842. * @param speedRatio defines the speed ratio to apply to all animations
  25843. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25844. * @returns the list of animatables created for all nodes
  25845. */
  25846. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25847. var children = target.getDescendants(directDescendantsOnly);
  25848. var result = [];
  25849. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25850. var child = children_1[_i];
  25851. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25852. }
  25853. return result;
  25854. };
  25855. /**
  25856. * Gets the animatable associated with a specific target
  25857. * @param target defines the target of the animatable
  25858. * @returns the required animatable if found
  25859. */
  25860. Scene.prototype.getAnimatableByTarget = function (target) {
  25861. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25862. if (this._activeAnimatables[index].target === target) {
  25863. return this._activeAnimatables[index];
  25864. }
  25865. }
  25866. return null;
  25867. };
  25868. /**
  25869. * Gets all animatables associated with a given target
  25870. * @param target defines the target to look animatables for
  25871. * @returns an array of Animatables
  25872. */
  25873. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25874. var result = [];
  25875. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25876. if (this._activeAnimatables[index].target === target) {
  25877. result.push(this._activeAnimatables[index]);
  25878. }
  25879. }
  25880. return result;
  25881. };
  25882. Object.defineProperty(Scene.prototype, "animatables", {
  25883. /**
  25884. * Gets all animatable attached to the scene
  25885. */
  25886. get: function () {
  25887. return this._activeAnimatables;
  25888. },
  25889. enumerable: true,
  25890. configurable: true
  25891. });
  25892. /**
  25893. * Will stop the animation of the given target
  25894. * @param target - the target
  25895. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25896. */
  25897. Scene.prototype.stopAnimation = function (target, animationName) {
  25898. var animatables = this.getAllAnimatablesByTarget(target);
  25899. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25900. var animatable = animatables_1[_i];
  25901. animatable.stop(animationName);
  25902. }
  25903. };
  25904. /**
  25905. * Stops and removes all animations that have been applied to the scene
  25906. */
  25907. Scene.prototype.stopAllAnimations = function () {
  25908. if (this._activeAnimatables) {
  25909. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25910. this._activeAnimatables[i].stop();
  25911. }
  25912. this._activeAnimatables = [];
  25913. }
  25914. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25915. var group = _a[_i];
  25916. group.stop();
  25917. }
  25918. };
  25919. Scene.prototype._animate = function () {
  25920. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25921. return;
  25922. }
  25923. // Getting time
  25924. var now = BABYLON.Tools.Now;
  25925. if (!this._animationTimeLast) {
  25926. if (this._pendingData.length > 0) {
  25927. return;
  25928. }
  25929. this._animationTimeLast = now;
  25930. }
  25931. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25932. this._animationTime += deltaTime;
  25933. this._animationTimeLast = now;
  25934. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25935. this._activeAnimatables[index]._animate(this._animationTime);
  25936. }
  25937. // Late animation bindings
  25938. this._processLateAnimationBindings();
  25939. };
  25940. /** @hidden */
  25941. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25942. var target = runtimeAnimation.target;
  25943. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25944. if (!target._lateAnimationHolders) {
  25945. target._lateAnimationHolders = {};
  25946. }
  25947. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25948. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25949. totalWeight: 0,
  25950. animations: [],
  25951. originalValue: originalValue
  25952. };
  25953. }
  25954. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25955. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25956. };
  25957. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25958. var normalizer = 1.0;
  25959. var finalPosition = BABYLON.Tmp.Vector3[0];
  25960. var finalScaling = BABYLON.Tmp.Vector3[1];
  25961. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25962. var startIndex = 0;
  25963. var originalAnimation = holder.animations[0];
  25964. var originalValue = holder.originalValue;
  25965. var scale = 1;
  25966. if (holder.totalWeight < 1.0) {
  25967. // We need to mix the original value in
  25968. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25969. scale = 1.0 - holder.totalWeight;
  25970. }
  25971. else {
  25972. startIndex = 1;
  25973. // We need to normalize the weights
  25974. normalizer = holder.totalWeight;
  25975. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25976. scale = originalAnimation.weight / normalizer;
  25977. if (scale == 1) {
  25978. return originalAnimation.currentValue;
  25979. }
  25980. }
  25981. finalScaling.scaleInPlace(scale);
  25982. finalPosition.scaleInPlace(scale);
  25983. finalQuaternion.scaleInPlace(scale);
  25984. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25985. var runtimeAnimation = holder.animations[animIndex];
  25986. var scale = runtimeAnimation.weight / normalizer;
  25987. var currentPosition = BABYLON.Tmp.Vector3[2];
  25988. var currentScaling = BABYLON.Tmp.Vector3[3];
  25989. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25990. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25991. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25992. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25993. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25994. }
  25995. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25996. return originalAnimation._workValue;
  25997. };
  25998. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25999. var originalAnimation = holder.animations[0];
  26000. var originalValue = holder.originalValue;
  26001. if (holder.animations.length === 1) {
  26002. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26003. }
  26004. var normalizer = 1.0;
  26005. var quaternions;
  26006. var weights;
  26007. if (holder.totalWeight < 1.0) {
  26008. var scale = 1.0 - holder.totalWeight;
  26009. quaternions = [];
  26010. weights = [];
  26011. quaternions.push(originalValue);
  26012. weights.push(scale);
  26013. }
  26014. else {
  26015. if (holder.animations.length === 2) { // Slerp as soon as we can
  26016. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26017. }
  26018. quaternions = [];
  26019. weights = [];
  26020. normalizer = holder.totalWeight;
  26021. }
  26022. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26023. var runtimeAnimation = holder.animations[animIndex];
  26024. quaternions.push(runtimeAnimation.currentValue);
  26025. weights.push(runtimeAnimation.weight / normalizer);
  26026. }
  26027. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26028. var cumulativeAmount = 0;
  26029. var cumulativeQuaternion = null;
  26030. for (var index = 0; index < quaternions.length;) {
  26031. if (!cumulativeQuaternion) {
  26032. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26033. cumulativeAmount = weights[index] + weights[index + 1];
  26034. index += 2;
  26035. continue;
  26036. }
  26037. cumulativeAmount += weights[index];
  26038. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26039. index++;
  26040. }
  26041. return cumulativeQuaternion;
  26042. };
  26043. Scene.prototype._processLateAnimationBindings = function () {
  26044. if (!this._registeredForLateAnimationBindings.length) {
  26045. return;
  26046. }
  26047. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26048. var target = this._registeredForLateAnimationBindings.data[index];
  26049. for (var path in target._lateAnimationHolders) {
  26050. var holder = target._lateAnimationHolders[path];
  26051. var originalAnimation = holder.animations[0];
  26052. var originalValue = holder.originalValue;
  26053. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26054. var finalValue = void 0;
  26055. if (matrixDecomposeMode) {
  26056. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26057. }
  26058. else {
  26059. var quaternionMode = originalValue.w !== undefined;
  26060. if (quaternionMode) {
  26061. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26062. }
  26063. else {
  26064. var startIndex = 0;
  26065. var normalizer = 1.0;
  26066. if (holder.totalWeight < 1.0) {
  26067. // We need to mix the original value in
  26068. if (originalValue.scale) {
  26069. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26070. }
  26071. else {
  26072. finalValue = originalValue * (1.0 - holder.totalWeight);
  26073. }
  26074. }
  26075. else {
  26076. // We need to normalize the weights
  26077. normalizer = holder.totalWeight;
  26078. var scale_1 = originalAnimation.weight / normalizer;
  26079. if (scale_1 !== 1) {
  26080. if (originalAnimation.currentValue.scale) {
  26081. finalValue = originalAnimation.currentValue.scale(scale_1);
  26082. }
  26083. else {
  26084. finalValue = originalAnimation.currentValue * scale_1;
  26085. }
  26086. }
  26087. else {
  26088. finalValue = originalAnimation.currentValue;
  26089. }
  26090. startIndex = 1;
  26091. }
  26092. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26093. var runtimeAnimation = holder.animations[animIndex];
  26094. var scale = runtimeAnimation.weight / normalizer;
  26095. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26096. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26097. }
  26098. else {
  26099. finalValue += runtimeAnimation.currentValue * scale;
  26100. }
  26101. }
  26102. }
  26103. }
  26104. target[path] = finalValue;
  26105. }
  26106. target._lateAnimationHolders = {};
  26107. }
  26108. this._registeredForLateAnimationBindings.reset();
  26109. };
  26110. // Matrix
  26111. /** @hidden */
  26112. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26113. this._useAlternateCameraConfiguration = active;
  26114. };
  26115. /**
  26116. * Gets the current view matrix
  26117. * @returns a Matrix
  26118. */
  26119. Scene.prototype.getViewMatrix = function () {
  26120. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26121. };
  26122. /**
  26123. * Gets the current projection matrix
  26124. * @returns a Matrix
  26125. */
  26126. Scene.prototype.getProjectionMatrix = function () {
  26127. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26128. };
  26129. /**
  26130. * Gets the current transform matrix
  26131. * @returns a Matrix made of View * Projection
  26132. */
  26133. Scene.prototype.getTransformMatrix = function () {
  26134. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26135. };
  26136. /**
  26137. * Sets the current transform matrix
  26138. * @param view defines the View matrix to use
  26139. * @param projection defines the Projection matrix to use
  26140. */
  26141. Scene.prototype.setTransformMatrix = function (view, projection) {
  26142. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26143. return;
  26144. }
  26145. this._viewUpdateFlag = view.updateFlag;
  26146. this._projectionUpdateFlag = projection.updateFlag;
  26147. this._viewMatrix = view;
  26148. this._projectionMatrix = projection;
  26149. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26150. // Update frustum
  26151. if (!this._frustumPlanes) {
  26152. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26153. }
  26154. else {
  26155. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26156. }
  26157. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26158. var otherCamera = this.activeCamera._alternateCamera;
  26159. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26160. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26161. }
  26162. if (this._sceneUbo.useUbo) {
  26163. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26164. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26165. this._sceneUbo.update();
  26166. }
  26167. };
  26168. /** @hidden */
  26169. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26170. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26171. return;
  26172. }
  26173. this._alternateViewUpdateFlag = view.updateFlag;
  26174. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26175. this._alternateViewMatrix = view;
  26176. this._alternateProjectionMatrix = projection;
  26177. if (!this._alternateTransformMatrix) {
  26178. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26179. }
  26180. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26181. if (!this._alternateSceneUbo) {
  26182. this._createAlternateUbo();
  26183. }
  26184. if (this._alternateSceneUbo.useUbo) {
  26185. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26186. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26187. this._alternateSceneUbo.update();
  26188. }
  26189. };
  26190. /**
  26191. * Gets the uniform buffer used to store scene data
  26192. * @returns a UniformBuffer
  26193. */
  26194. Scene.prototype.getSceneUniformBuffer = function () {
  26195. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26196. };
  26197. /**
  26198. * Gets an unique (relatively to the current scene) Id
  26199. * @returns an unique number for the scene
  26200. */
  26201. Scene.prototype.getUniqueId = function () {
  26202. var result = Scene._uniqueIdCounter;
  26203. Scene._uniqueIdCounter++;
  26204. return result;
  26205. };
  26206. /**
  26207. * Add a mesh to the list of scene's meshes
  26208. * @param newMesh defines the mesh to add
  26209. */
  26210. Scene.prototype.addMesh = function (newMesh) {
  26211. this.meshes.push(newMesh);
  26212. //notify the collision coordinator
  26213. if (this.collisionCoordinator) {
  26214. this.collisionCoordinator.onMeshAdded(newMesh);
  26215. }
  26216. newMesh._resyncLightSources();
  26217. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26218. };
  26219. /**
  26220. * Remove a mesh for the list of scene's meshes
  26221. * @param toRemove defines the mesh to remove
  26222. * @param recursive if all child meshes should also be removed from the scene
  26223. * @returns the index where the mesh was in the mesh list
  26224. */
  26225. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26226. var _this = this;
  26227. if (recursive === void 0) { recursive = false; }
  26228. var index = this.meshes.indexOf(toRemove);
  26229. if (index !== -1) {
  26230. // Remove from the scene if mesh found
  26231. this.meshes.splice(index, 1);
  26232. }
  26233. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26234. if (recursive) {
  26235. toRemove.getChildMeshes().forEach(function (m) {
  26236. _this.removeMesh(m);
  26237. });
  26238. }
  26239. return index;
  26240. };
  26241. /**
  26242. * Add a transform node to the list of scene's transform nodes
  26243. * @param newTransformNode defines the transform node to add
  26244. */
  26245. Scene.prototype.addTransformNode = function (newTransformNode) {
  26246. this.transformNodes.push(newTransformNode);
  26247. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26248. };
  26249. /**
  26250. * Remove a transform node for the list of scene's transform nodes
  26251. * @param toRemove defines the transform node to remove
  26252. * @returns the index where the transform node was in the transform node list
  26253. */
  26254. Scene.prototype.removeTransformNode = function (toRemove) {
  26255. var index = this.transformNodes.indexOf(toRemove);
  26256. if (index !== -1) {
  26257. // Remove from the scene if found
  26258. this.transformNodes.splice(index, 1);
  26259. }
  26260. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26261. return index;
  26262. };
  26263. /**
  26264. * Remove a skeleton for the list of scene's skeletons
  26265. * @param toRemove defines the skeleton to remove
  26266. * @returns the index where the skeleton was in the skeleton list
  26267. */
  26268. Scene.prototype.removeSkeleton = function (toRemove) {
  26269. var index = this.skeletons.indexOf(toRemove);
  26270. if (index !== -1) {
  26271. // Remove from the scene if found
  26272. this.skeletons.splice(index, 1);
  26273. }
  26274. return index;
  26275. };
  26276. /**
  26277. * Remove a morph target for the list of scene's morph targets
  26278. * @param toRemove defines the morph target to remove
  26279. * @returns the index where the morph target was in the morph target list
  26280. */
  26281. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26282. var index = this.morphTargetManagers.indexOf(toRemove);
  26283. if (index !== -1) {
  26284. // Remove from the scene if found
  26285. this.morphTargetManagers.splice(index, 1);
  26286. }
  26287. return index;
  26288. };
  26289. /**
  26290. * Remove a light for the list of scene's lights
  26291. * @param toRemove defines the light to remove
  26292. * @returns the index where the light was in the light list
  26293. */
  26294. Scene.prototype.removeLight = function (toRemove) {
  26295. var index = this.lights.indexOf(toRemove);
  26296. if (index !== -1) {
  26297. // Remove from meshes
  26298. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26299. var mesh = _a[_i];
  26300. mesh._removeLightSource(toRemove);
  26301. }
  26302. // Remove from the scene if mesh found
  26303. this.lights.splice(index, 1);
  26304. this.sortLightsByPriority();
  26305. }
  26306. this.onLightRemovedObservable.notifyObservers(toRemove);
  26307. return index;
  26308. };
  26309. /**
  26310. * Remove a camera for the list of scene's cameras
  26311. * @param toRemove defines the camera to remove
  26312. * @returns the index where the camera was in the camera list
  26313. */
  26314. Scene.prototype.removeCamera = function (toRemove) {
  26315. var index = this.cameras.indexOf(toRemove);
  26316. if (index !== -1) {
  26317. // Remove from the scene if mesh found
  26318. this.cameras.splice(index, 1);
  26319. }
  26320. // Remove from activeCameras
  26321. var index2 = this.activeCameras.indexOf(toRemove);
  26322. if (index2 !== -1) {
  26323. // Remove from the scene if mesh found
  26324. this.activeCameras.splice(index2, 1);
  26325. }
  26326. // Reset the activeCamera
  26327. if (this.activeCamera === toRemove) {
  26328. if (this.cameras.length > 0) {
  26329. this.activeCamera = this.cameras[0];
  26330. }
  26331. else {
  26332. this.activeCamera = null;
  26333. }
  26334. }
  26335. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26336. return index;
  26337. };
  26338. /**
  26339. * Remove a particle system for the list of scene's particle systems
  26340. * @param toRemove defines the particle system to remove
  26341. * @returns the index where the particle system was in the particle system list
  26342. */
  26343. Scene.prototype.removeParticleSystem = function (toRemove) {
  26344. var index = this.particleSystems.indexOf(toRemove);
  26345. if (index !== -1) {
  26346. this.particleSystems.splice(index, 1);
  26347. }
  26348. return index;
  26349. };
  26350. /**
  26351. * Remove a animation for the list of scene's animations
  26352. * @param toRemove defines the animation to remove
  26353. * @returns the index where the animation was in the animation list
  26354. */
  26355. Scene.prototype.removeAnimation = function (toRemove) {
  26356. var index = this.animations.indexOf(toRemove);
  26357. if (index !== -1) {
  26358. this.animations.splice(index, 1);
  26359. }
  26360. return index;
  26361. };
  26362. /**
  26363. * Removes the given animation group from this scene.
  26364. * @param toRemove The animation group to remove
  26365. * @returns The index of the removed animation group
  26366. */
  26367. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26368. var index = this.animationGroups.indexOf(toRemove);
  26369. if (index !== -1) {
  26370. this.animationGroups.splice(index, 1);
  26371. }
  26372. return index;
  26373. };
  26374. /**
  26375. * Removes the given multi-material from this scene.
  26376. * @param toRemove The multi-material to remove
  26377. * @returns The index of the removed multi-material
  26378. */
  26379. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26380. var index = this.multiMaterials.indexOf(toRemove);
  26381. if (index !== -1) {
  26382. this.multiMaterials.splice(index, 1);
  26383. }
  26384. return index;
  26385. };
  26386. /**
  26387. * Removes the given material from this scene.
  26388. * @param toRemove The material to remove
  26389. * @returns The index of the removed material
  26390. */
  26391. Scene.prototype.removeMaterial = function (toRemove) {
  26392. var index = this.materials.indexOf(toRemove);
  26393. if (index !== -1) {
  26394. this.materials.splice(index, 1);
  26395. }
  26396. return index;
  26397. };
  26398. /**
  26399. * Removes the given lens flare system from this scene.
  26400. * @param toRemove The lens flare system to remove
  26401. * @returns The index of the removed lens flare system
  26402. */
  26403. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26404. var index = this.lensFlareSystems.indexOf(toRemove);
  26405. if (index !== -1) {
  26406. this.lensFlareSystems.splice(index, 1);
  26407. }
  26408. return index;
  26409. };
  26410. /**
  26411. * Removes the given action manager from this scene.
  26412. * @param toRemove The action manager to remove
  26413. * @returns The index of the removed action manager
  26414. */
  26415. Scene.prototype.removeActionManager = function (toRemove) {
  26416. var index = this._actionManagers.indexOf(toRemove);
  26417. if (index !== -1) {
  26418. this._actionManagers.splice(index, 1);
  26419. }
  26420. return index;
  26421. };
  26422. /**
  26423. * Removes the given effect layer from this scene.
  26424. * @param toRemove defines the effect layer to remove
  26425. * @returns the index of the removed effect layer
  26426. */
  26427. Scene.prototype.removeEffectLayer = function (toRemove) {
  26428. var index = this.effectLayers.indexOf(toRemove);
  26429. if (index !== -1) {
  26430. this.effectLayers.splice(index, 1);
  26431. }
  26432. return index;
  26433. };
  26434. /**
  26435. * Removes the given texture from this scene.
  26436. * @param toRemove The texture to remove
  26437. * @returns The index of the removed texture
  26438. */
  26439. Scene.prototype.removeTexture = function (toRemove) {
  26440. var index = this.textures.indexOf(toRemove);
  26441. if (index !== -1) {
  26442. this.textures.splice(index, 1);
  26443. }
  26444. return index;
  26445. };
  26446. /**
  26447. * Adds the given light to this scene
  26448. * @param newLight The light to add
  26449. */
  26450. Scene.prototype.addLight = function (newLight) {
  26451. this.lights.push(newLight);
  26452. this.sortLightsByPriority();
  26453. // Add light to all meshes (To support if the light is removed and then readded)
  26454. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26455. var mesh = _a[_i];
  26456. if (mesh._lightSources.indexOf(newLight) === -1) {
  26457. mesh._lightSources.push(newLight);
  26458. mesh._resyncLightSources();
  26459. }
  26460. }
  26461. this.onNewLightAddedObservable.notifyObservers(newLight);
  26462. };
  26463. /**
  26464. * Sorts the list list based on light priorities
  26465. */
  26466. Scene.prototype.sortLightsByPriority = function () {
  26467. if (this.requireLightSorting) {
  26468. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26469. }
  26470. };
  26471. /**
  26472. * Adds the given camera to this scene
  26473. * @param newCamera The camera to add
  26474. */
  26475. Scene.prototype.addCamera = function (newCamera) {
  26476. this.cameras.push(newCamera);
  26477. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26478. };
  26479. /**
  26480. * Adds the given skeleton to this scene
  26481. * @param newSkeleton The skeleton to add
  26482. */
  26483. Scene.prototype.addSkeleton = function (newSkeleton) {
  26484. this.skeletons.push(newSkeleton);
  26485. };
  26486. /**
  26487. * Adds the given particle system to this scene
  26488. * @param newParticleSystem The particle system to add
  26489. */
  26490. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26491. this.particleSystems.push(newParticleSystem);
  26492. };
  26493. /**
  26494. * Adds the given animation to this scene
  26495. * @param newAnimation The animation to add
  26496. */
  26497. Scene.prototype.addAnimation = function (newAnimation) {
  26498. this.animations.push(newAnimation);
  26499. };
  26500. /**
  26501. * Adds the given animation group to this scene.
  26502. * @param newAnimationGroup The animation group to add
  26503. */
  26504. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26505. this.animationGroups.push(newAnimationGroup);
  26506. };
  26507. /**
  26508. * Adds the given multi-material to this scene
  26509. * @param newMultiMaterial The multi-material to add
  26510. */
  26511. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26512. this.multiMaterials.push(newMultiMaterial);
  26513. };
  26514. /**
  26515. * Adds the given material to this scene
  26516. * @param newMaterial The material to add
  26517. */
  26518. Scene.prototype.addMaterial = function (newMaterial) {
  26519. this.materials.push(newMaterial);
  26520. };
  26521. /**
  26522. * Adds the given morph target to this scene
  26523. * @param newMorphTargetManager The morph target to add
  26524. */
  26525. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26526. this.morphTargetManagers.push(newMorphTargetManager);
  26527. };
  26528. /**
  26529. * Adds the given geometry to this scene
  26530. * @param newGeometry The geometry to add
  26531. */
  26532. Scene.prototype.addGeometry = function (newGeometry) {
  26533. this._geometries.push(newGeometry);
  26534. };
  26535. /**
  26536. * Adds the given lens flare system to this scene
  26537. * @param newLensFlareSystem The lens flare system to add
  26538. */
  26539. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26540. this.lensFlareSystems.push(newLensFlareSystem);
  26541. };
  26542. /**
  26543. * Adds the given effect layer to this scene
  26544. * @param newEffectLayer defines the effect layer to add
  26545. */
  26546. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26547. this.effectLayers.push(newEffectLayer);
  26548. };
  26549. /**
  26550. * Adds the given action manager to this scene
  26551. * @param newActionManager The action manager to add
  26552. */
  26553. Scene.prototype.addActionManager = function (newActionManager) {
  26554. this._actionManagers.push(newActionManager);
  26555. };
  26556. /**
  26557. * Adds the given texture to this scene.
  26558. * @param newTexture The texture to add
  26559. */
  26560. Scene.prototype.addTexture = function (newTexture) {
  26561. this.textures.push(newTexture);
  26562. };
  26563. /**
  26564. * Switch active camera
  26565. * @param newCamera defines the new active camera
  26566. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26567. */
  26568. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26569. if (attachControl === void 0) { attachControl = true; }
  26570. var canvas = this._engine.getRenderingCanvas();
  26571. if (!canvas) {
  26572. return;
  26573. }
  26574. if (this.activeCamera) {
  26575. this.activeCamera.detachControl(canvas);
  26576. }
  26577. this.activeCamera = newCamera;
  26578. if (attachControl) {
  26579. newCamera.attachControl(canvas);
  26580. }
  26581. };
  26582. /**
  26583. * sets the active camera of the scene using its ID
  26584. * @param id defines the camera's ID
  26585. * @return the new active camera or null if none found.
  26586. */
  26587. Scene.prototype.setActiveCameraByID = function (id) {
  26588. var camera = this.getCameraByID(id);
  26589. if (camera) {
  26590. this.activeCamera = camera;
  26591. return camera;
  26592. }
  26593. return null;
  26594. };
  26595. /**
  26596. * sets the active camera of the scene using its name
  26597. * @param name defines the camera's name
  26598. * @returns the new active camera or null if none found.
  26599. */
  26600. Scene.prototype.setActiveCameraByName = function (name) {
  26601. var camera = this.getCameraByName(name);
  26602. if (camera) {
  26603. this.activeCamera = camera;
  26604. return camera;
  26605. }
  26606. return null;
  26607. };
  26608. /**
  26609. * get an animation group using its name
  26610. * @param name defines the material's name
  26611. * @return the animation group or null if none found.
  26612. */
  26613. Scene.prototype.getAnimationGroupByName = function (name) {
  26614. for (var index = 0; index < this.animationGroups.length; index++) {
  26615. if (this.animationGroups[index].name === name) {
  26616. return this.animationGroups[index];
  26617. }
  26618. }
  26619. return null;
  26620. };
  26621. /**
  26622. * get a material using its id
  26623. * @param id defines the material's ID
  26624. * @return the material or null if none found.
  26625. */
  26626. Scene.prototype.getMaterialByID = function (id) {
  26627. for (var index = 0; index < this.materials.length; index++) {
  26628. if (this.materials[index].id === id) {
  26629. return this.materials[index];
  26630. }
  26631. }
  26632. return null;
  26633. };
  26634. /**
  26635. * Gets a material using its name
  26636. * @param name defines the material's name
  26637. * @return the material or null if none found.
  26638. */
  26639. Scene.prototype.getMaterialByName = function (name) {
  26640. for (var index = 0; index < this.materials.length; index++) {
  26641. if (this.materials[index].name === name) {
  26642. return this.materials[index];
  26643. }
  26644. }
  26645. return null;
  26646. };
  26647. /**
  26648. * Gets a lens flare system using its name
  26649. * @param name defines the name to look for
  26650. * @returns the lens flare system or null if not found
  26651. */
  26652. Scene.prototype.getLensFlareSystemByName = function (name) {
  26653. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26654. if (this.lensFlareSystems[index].name === name) {
  26655. return this.lensFlareSystems[index];
  26656. }
  26657. }
  26658. return null;
  26659. };
  26660. /**
  26661. * Gets a lens flare system using its id
  26662. * @param id defines the id to look for
  26663. * @returns the lens flare system or null if not found
  26664. */
  26665. Scene.prototype.getLensFlareSystemByID = function (id) {
  26666. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26667. if (this.lensFlareSystems[index].id === id) {
  26668. return this.lensFlareSystems[index];
  26669. }
  26670. }
  26671. return null;
  26672. };
  26673. /**
  26674. * Gets a camera using its id
  26675. * @param id defines the id to look for
  26676. * @returns the camera or null if not found
  26677. */
  26678. Scene.prototype.getCameraByID = function (id) {
  26679. for (var index = 0; index < this.cameras.length; index++) {
  26680. if (this.cameras[index].id === id) {
  26681. return this.cameras[index];
  26682. }
  26683. }
  26684. return null;
  26685. };
  26686. /**
  26687. * Gets a camera using its unique id
  26688. * @param uniqueId defines the unique id to look for
  26689. * @returns the camera or null if not found
  26690. */
  26691. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26692. for (var index = 0; index < this.cameras.length; index++) {
  26693. if (this.cameras[index].uniqueId === uniqueId) {
  26694. return this.cameras[index];
  26695. }
  26696. }
  26697. return null;
  26698. };
  26699. /**
  26700. * Gets a camera using its name
  26701. * @param name defines the camera's name
  26702. * @return the camera or null if none found.
  26703. */
  26704. Scene.prototype.getCameraByName = function (name) {
  26705. for (var index = 0; index < this.cameras.length; index++) {
  26706. if (this.cameras[index].name === name) {
  26707. return this.cameras[index];
  26708. }
  26709. }
  26710. return null;
  26711. };
  26712. /**
  26713. * Gets a bone using its id
  26714. * @param id defines the bone's id
  26715. * @return the bone or null if not found
  26716. */
  26717. Scene.prototype.getBoneByID = function (id) {
  26718. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26719. var skeleton = this.skeletons[skeletonIndex];
  26720. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26721. if (skeleton.bones[boneIndex].id === id) {
  26722. return skeleton.bones[boneIndex];
  26723. }
  26724. }
  26725. }
  26726. return null;
  26727. };
  26728. /**
  26729. * Gets a bone using its id
  26730. * @param name defines the bone's name
  26731. * @return the bone or null if not found
  26732. */
  26733. Scene.prototype.getBoneByName = function (name) {
  26734. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26735. var skeleton = this.skeletons[skeletonIndex];
  26736. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26737. if (skeleton.bones[boneIndex].name === name) {
  26738. return skeleton.bones[boneIndex];
  26739. }
  26740. }
  26741. }
  26742. return null;
  26743. };
  26744. /**
  26745. * Gets a light node using its name
  26746. * @param name defines the the light's name
  26747. * @return the light or null if none found.
  26748. */
  26749. Scene.prototype.getLightByName = function (name) {
  26750. for (var index = 0; index < this.lights.length; index++) {
  26751. if (this.lights[index].name === name) {
  26752. return this.lights[index];
  26753. }
  26754. }
  26755. return null;
  26756. };
  26757. /**
  26758. * Gets a light node using its id
  26759. * @param id defines the light's id
  26760. * @return the light or null if none found.
  26761. */
  26762. Scene.prototype.getLightByID = function (id) {
  26763. for (var index = 0; index < this.lights.length; index++) {
  26764. if (this.lights[index].id === id) {
  26765. return this.lights[index];
  26766. }
  26767. }
  26768. return null;
  26769. };
  26770. /**
  26771. * Gets a light node using its scene-generated unique ID
  26772. * @param uniqueId defines the light's unique id
  26773. * @return the light or null if none found.
  26774. */
  26775. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26776. for (var index = 0; index < this.lights.length; index++) {
  26777. if (this.lights[index].uniqueId === uniqueId) {
  26778. return this.lights[index];
  26779. }
  26780. }
  26781. return null;
  26782. };
  26783. /**
  26784. * Gets a particle system by id
  26785. * @param id defines the particle system id
  26786. * @return the corresponding system or null if none found
  26787. */
  26788. Scene.prototype.getParticleSystemByID = function (id) {
  26789. for (var index = 0; index < this.particleSystems.length; index++) {
  26790. if (this.particleSystems[index].id === id) {
  26791. return this.particleSystems[index];
  26792. }
  26793. }
  26794. return null;
  26795. };
  26796. /**
  26797. * Gets a geometry using its ID
  26798. * @param id defines the geometry's id
  26799. * @return the geometry or null if none found.
  26800. */
  26801. Scene.prototype.getGeometryByID = function (id) {
  26802. for (var index = 0; index < this._geometries.length; index++) {
  26803. if (this._geometries[index].id === id) {
  26804. return this._geometries[index];
  26805. }
  26806. }
  26807. return null;
  26808. };
  26809. /**
  26810. * Add a new geometry to this scene
  26811. * @param geometry defines the geometry to be added to the scene.
  26812. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26813. * @return a boolean defining if the geometry was added or not
  26814. */
  26815. Scene.prototype.pushGeometry = function (geometry, force) {
  26816. if (!force && this.getGeometryByID(geometry.id)) {
  26817. return false;
  26818. }
  26819. this._geometries.push(geometry);
  26820. //notify the collision coordinator
  26821. if (this.collisionCoordinator) {
  26822. this.collisionCoordinator.onGeometryAdded(geometry);
  26823. }
  26824. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26825. return true;
  26826. };
  26827. /**
  26828. * Removes an existing geometry
  26829. * @param geometry defines the geometry to be removed from the scene
  26830. * @return a boolean defining if the geometry was removed or not
  26831. */
  26832. Scene.prototype.removeGeometry = function (geometry) {
  26833. var index = this._geometries.indexOf(geometry);
  26834. if (index > -1) {
  26835. this._geometries.splice(index, 1);
  26836. //notify the collision coordinator
  26837. if (this.collisionCoordinator) {
  26838. this.collisionCoordinator.onGeometryDeleted(geometry);
  26839. }
  26840. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26841. return true;
  26842. }
  26843. return false;
  26844. };
  26845. /**
  26846. * Gets the list of geometries attached to the scene
  26847. * @returns an array of Geometry
  26848. */
  26849. Scene.prototype.getGeometries = function () {
  26850. return this._geometries;
  26851. };
  26852. /**
  26853. * Gets the first added mesh found of a given ID
  26854. * @param id defines the id to search for
  26855. * @return the mesh found or null if not found at all
  26856. */
  26857. Scene.prototype.getMeshByID = function (id) {
  26858. for (var index = 0; index < this.meshes.length; index++) {
  26859. if (this.meshes[index].id === id) {
  26860. return this.meshes[index];
  26861. }
  26862. }
  26863. return null;
  26864. };
  26865. /**
  26866. * Gets a list of meshes using their id
  26867. * @param id defines the id to search for
  26868. * @returns a list of meshes
  26869. */
  26870. Scene.prototype.getMeshesByID = function (id) {
  26871. return this.meshes.filter(function (m) {
  26872. return m.id === id;
  26873. });
  26874. };
  26875. /**
  26876. * Gets the first added transform node found of a given ID
  26877. * @param id defines the id to search for
  26878. * @return the found transform node or null if not found at all.
  26879. */
  26880. Scene.prototype.getTransformNodeByID = function (id) {
  26881. for (var index = 0; index < this.transformNodes.length; index++) {
  26882. if (this.transformNodes[index].id === id) {
  26883. return this.transformNodes[index];
  26884. }
  26885. }
  26886. return null;
  26887. };
  26888. /**
  26889. * Gets a list of transform nodes using their id
  26890. * @param id defines the id to search for
  26891. * @returns a list of transform nodes
  26892. */
  26893. Scene.prototype.getTransformNodesByID = function (id) {
  26894. return this.transformNodes.filter(function (m) {
  26895. return m.id === id;
  26896. });
  26897. };
  26898. /**
  26899. * Gets a mesh with its auto-generated unique id
  26900. * @param uniqueId defines the unique id to search for
  26901. * @return the found mesh or null if not found at all.
  26902. */
  26903. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26904. for (var index = 0; index < this.meshes.length; index++) {
  26905. if (this.meshes[index].uniqueId === uniqueId) {
  26906. return this.meshes[index];
  26907. }
  26908. }
  26909. return null;
  26910. };
  26911. /**
  26912. * Gets a the last added mesh using a given id
  26913. * @param id defines the id to search for
  26914. * @return the found mesh or null if not found at all.
  26915. */
  26916. Scene.prototype.getLastMeshByID = function (id) {
  26917. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26918. if (this.meshes[index].id === id) {
  26919. return this.meshes[index];
  26920. }
  26921. }
  26922. return null;
  26923. };
  26924. /**
  26925. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26926. * @param id defines the id to search for
  26927. * @return the found node or null if not found at all
  26928. */
  26929. Scene.prototype.getLastEntryByID = function (id) {
  26930. var index;
  26931. for (index = this.meshes.length - 1; index >= 0; index--) {
  26932. if (this.meshes[index].id === id) {
  26933. return this.meshes[index];
  26934. }
  26935. }
  26936. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26937. if (this.transformNodes[index].id === id) {
  26938. return this.transformNodes[index];
  26939. }
  26940. }
  26941. for (index = this.cameras.length - 1; index >= 0; index--) {
  26942. if (this.cameras[index].id === id) {
  26943. return this.cameras[index];
  26944. }
  26945. }
  26946. for (index = this.lights.length - 1; index >= 0; index--) {
  26947. if (this.lights[index].id === id) {
  26948. return this.lights[index];
  26949. }
  26950. }
  26951. return null;
  26952. };
  26953. /**
  26954. * Gets a node (Mesh, Camera, Light) using a given id
  26955. * @param id defines the id to search for
  26956. * @return the found node or null if not found at all
  26957. */
  26958. Scene.prototype.getNodeByID = function (id) {
  26959. var mesh = this.getMeshByID(id);
  26960. if (mesh) {
  26961. return mesh;
  26962. }
  26963. var light = this.getLightByID(id);
  26964. if (light) {
  26965. return light;
  26966. }
  26967. var camera = this.getCameraByID(id);
  26968. if (camera) {
  26969. return camera;
  26970. }
  26971. var bone = this.getBoneByID(id);
  26972. return bone;
  26973. };
  26974. /**
  26975. * Gets a node (Mesh, Camera, Light) using a given name
  26976. * @param name defines the name to search for
  26977. * @return the found node or null if not found at all.
  26978. */
  26979. Scene.prototype.getNodeByName = function (name) {
  26980. var mesh = this.getMeshByName(name);
  26981. if (mesh) {
  26982. return mesh;
  26983. }
  26984. var light = this.getLightByName(name);
  26985. if (light) {
  26986. return light;
  26987. }
  26988. var camera = this.getCameraByName(name);
  26989. if (camera) {
  26990. return camera;
  26991. }
  26992. var bone = this.getBoneByName(name);
  26993. return bone;
  26994. };
  26995. /**
  26996. * Gets a mesh using a given name
  26997. * @param name defines the name to search for
  26998. * @return the found mesh or null if not found at all.
  26999. */
  27000. Scene.prototype.getMeshByName = function (name) {
  27001. for (var index = 0; index < this.meshes.length; index++) {
  27002. if (this.meshes[index].name === name) {
  27003. return this.meshes[index];
  27004. }
  27005. }
  27006. return null;
  27007. };
  27008. /**
  27009. * Gets a transform node using a given name
  27010. * @param name defines the name to search for
  27011. * @return the found transform node or null if not found at all.
  27012. */
  27013. Scene.prototype.getTransformNodeByName = function (name) {
  27014. for (var index = 0; index < this.transformNodes.length; index++) {
  27015. if (this.transformNodes[index].name === name) {
  27016. return this.transformNodes[index];
  27017. }
  27018. }
  27019. return null;
  27020. };
  27021. /**
  27022. * Gets a sound using a given name
  27023. * @param name defines the name to search for
  27024. * @return the found sound or null if not found at all.
  27025. */
  27026. Scene.prototype.getSoundByName = function (name) {
  27027. var index;
  27028. if (BABYLON.AudioEngine) {
  27029. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27030. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27031. return this.mainSoundTrack.soundCollection[index];
  27032. }
  27033. }
  27034. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27035. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27036. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27037. return this.soundTracks[sdIndex].soundCollection[index];
  27038. }
  27039. }
  27040. }
  27041. }
  27042. return null;
  27043. };
  27044. /**
  27045. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27046. * @param id defines the id to search for
  27047. * @return the found skeleton or null if not found at all.
  27048. */
  27049. Scene.prototype.getLastSkeletonByID = function (id) {
  27050. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27051. if (this.skeletons[index].id === id) {
  27052. return this.skeletons[index];
  27053. }
  27054. }
  27055. return null;
  27056. };
  27057. /**
  27058. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27059. * @param id defines the id to search for
  27060. * @return the found skeleton or null if not found at all.
  27061. */
  27062. Scene.prototype.getSkeletonById = function (id) {
  27063. for (var index = 0; index < this.skeletons.length; index++) {
  27064. if (this.skeletons[index].id === id) {
  27065. return this.skeletons[index];
  27066. }
  27067. }
  27068. return null;
  27069. };
  27070. /**
  27071. * Gets a skeleton using a given name
  27072. * @param name defines the name to search for
  27073. * @return the found skeleton or null if not found at all.
  27074. */
  27075. Scene.prototype.getSkeletonByName = function (name) {
  27076. for (var index = 0; index < this.skeletons.length; index++) {
  27077. if (this.skeletons[index].name === name) {
  27078. return this.skeletons[index];
  27079. }
  27080. }
  27081. return null;
  27082. };
  27083. /**
  27084. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27085. * @param id defines the id to search for
  27086. * @return the found morph target manager or null if not found at all.
  27087. */
  27088. Scene.prototype.getMorphTargetManagerById = function (id) {
  27089. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27090. if (this.morphTargetManagers[index].uniqueId === id) {
  27091. return this.morphTargetManagers[index];
  27092. }
  27093. }
  27094. return null;
  27095. };
  27096. /**
  27097. * Gets a boolean indicating if the given mesh is active
  27098. * @param mesh defines the mesh to look for
  27099. * @returns true if the mesh is in the active list
  27100. */
  27101. Scene.prototype.isActiveMesh = function (mesh) {
  27102. return (this._activeMeshes.indexOf(mesh) !== -1);
  27103. };
  27104. /**
  27105. * Return a the first highlight layer of the scene with a given name.
  27106. * @param name The name of the highlight layer to look for.
  27107. * @return The highlight layer if found otherwise null.
  27108. */
  27109. Scene.prototype.getHighlightLayerByName = function (name) {
  27110. for (var index = 0; index < this.effectLayers.length; index++) {
  27111. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27112. return this.effectLayers[index];
  27113. }
  27114. }
  27115. return null;
  27116. };
  27117. /**
  27118. * Return a the first highlight layer of the scene with a given name.
  27119. * @param name The name of the highlight layer to look for.
  27120. * @return The highlight layer if found otherwise null.
  27121. */
  27122. Scene.prototype.getGlowLayerByName = function (name) {
  27123. for (var index = 0; index < this.effectLayers.length; index++) {
  27124. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27125. return this.effectLayers[index];
  27126. }
  27127. }
  27128. return null;
  27129. };
  27130. Object.defineProperty(Scene.prototype, "uid", {
  27131. /**
  27132. * Return a unique id as a string which can serve as an identifier for the scene
  27133. */
  27134. get: function () {
  27135. if (!this._uid) {
  27136. this._uid = BABYLON.Tools.RandomId();
  27137. }
  27138. return this._uid;
  27139. },
  27140. enumerable: true,
  27141. configurable: true
  27142. });
  27143. /**
  27144. * Add an externaly attached data from its key.
  27145. * This method call will fail and return false, if such key already exists.
  27146. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27147. * @param key the unique key that identifies the data
  27148. * @param data the data object to associate to the key for this Engine instance
  27149. * @return true if no such key were already present and the data was added successfully, false otherwise
  27150. */
  27151. Scene.prototype.addExternalData = function (key, data) {
  27152. if (!this._externalData) {
  27153. this._externalData = new BABYLON.StringDictionary();
  27154. }
  27155. return this._externalData.add(key, data);
  27156. };
  27157. /**
  27158. * Get an externaly attached data from its key
  27159. * @param key the unique key that identifies the data
  27160. * @return the associated data, if present (can be null), or undefined if not present
  27161. */
  27162. Scene.prototype.getExternalData = function (key) {
  27163. if (!this._externalData) {
  27164. return null;
  27165. }
  27166. return this._externalData.get(key);
  27167. };
  27168. /**
  27169. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27170. * @param key the unique key that identifies the data
  27171. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27172. * @return the associated data, can be null if the factory returned null.
  27173. */
  27174. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27175. if (!this._externalData) {
  27176. this._externalData = new BABYLON.StringDictionary();
  27177. }
  27178. return this._externalData.getOrAddWithFactory(key, factory);
  27179. };
  27180. /**
  27181. * Remove an externaly attached data from the Engine instance
  27182. * @param key the unique key that identifies the data
  27183. * @return true if the data was successfully removed, false if it doesn't exist
  27184. */
  27185. Scene.prototype.removeExternalData = function (key) {
  27186. return this._externalData.remove(key);
  27187. };
  27188. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27189. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27190. if (mesh.showSubMeshesBoundingBox) {
  27191. var boundingInfo = subMesh.getBoundingInfo();
  27192. if (boundingInfo !== null && boundingInfo !== undefined) {
  27193. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27194. }
  27195. }
  27196. var material = subMesh.getMaterial();
  27197. if (material !== null && material !== undefined) {
  27198. // Render targets
  27199. if (material.getRenderTargetTextures !== undefined) {
  27200. if (this._processedMaterials.indexOf(material) === -1) {
  27201. this._processedMaterials.push(material);
  27202. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27203. }
  27204. }
  27205. // Dispatch
  27206. this._activeIndices.addCount(subMesh.indexCount, false);
  27207. this._renderingManager.dispatch(subMesh, mesh, material);
  27208. }
  27209. }
  27210. };
  27211. /**
  27212. * Clear the processed materials smart array preventing retention point in material dispose.
  27213. */
  27214. Scene.prototype.freeProcessedMaterials = function () {
  27215. this._processedMaterials.dispose();
  27216. };
  27217. /**
  27218. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27219. */
  27220. Scene.prototype.freeActiveMeshes = function () {
  27221. this._activeMeshes.dispose();
  27222. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27223. this.activeCamera._activeMeshes.dispose();
  27224. }
  27225. if (this.activeCameras) {
  27226. for (var i = 0; i < this.activeCameras.length; i++) {
  27227. var activeCamera = this.activeCameras[i];
  27228. if (activeCamera && activeCamera._activeMeshes) {
  27229. activeCamera._activeMeshes.dispose();
  27230. }
  27231. }
  27232. }
  27233. };
  27234. /**
  27235. * Clear the info related to rendering groups preventing retention points during dispose.
  27236. */
  27237. Scene.prototype.freeRenderingGroups = function () {
  27238. if (this._renderingManager) {
  27239. this._renderingManager.freeRenderingGroups();
  27240. }
  27241. if (this.textures) {
  27242. for (var i = 0; i < this.textures.length; i++) {
  27243. var texture = this.textures[i];
  27244. if (texture && texture.renderList) {
  27245. texture.freeRenderingGroups();
  27246. }
  27247. }
  27248. }
  27249. };
  27250. /** @hidden */
  27251. Scene.prototype._isInIntermediateRendering = function () {
  27252. return this._intermediateRendering;
  27253. };
  27254. /**
  27255. * Defines the current active mesh candidate provider
  27256. * @param provider defines the provider to use
  27257. */
  27258. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27259. this._activeMeshCandidateProvider = provider;
  27260. };
  27261. /**
  27262. * Gets the current active mesh candidate provider
  27263. * @returns the current active mesh candidate provider
  27264. */
  27265. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27266. return this._activeMeshCandidateProvider;
  27267. };
  27268. /**
  27269. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27270. * @returns the current scene
  27271. */
  27272. Scene.prototype.freezeActiveMeshes = function () {
  27273. if (!this.activeCamera) {
  27274. return this;
  27275. }
  27276. if (!this._frustumPlanes) {
  27277. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27278. }
  27279. this._evaluateActiveMeshes();
  27280. this._activeMeshesFrozen = true;
  27281. return this;
  27282. };
  27283. /**
  27284. * Use this function to restart evaluating active meshes on every frame
  27285. * @returns the current scene
  27286. */
  27287. Scene.prototype.unfreezeActiveMeshes = function () {
  27288. this._activeMeshesFrozen = false;
  27289. return this;
  27290. };
  27291. Scene.prototype._evaluateActiveMeshes = function () {
  27292. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27293. return;
  27294. }
  27295. if (!this.activeCamera) {
  27296. return;
  27297. }
  27298. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27299. this.activeCamera._activeMeshes.reset();
  27300. this._activeMeshes.reset();
  27301. this._renderingManager.reset();
  27302. this._processedMaterials.reset();
  27303. this._activeParticleSystems.reset();
  27304. this._activeSkeletons.reset();
  27305. this._softwareSkinnedMeshes.reset();
  27306. if (this._boundingBoxRenderer) {
  27307. this._boundingBoxRenderer.reset();
  27308. }
  27309. // Meshes
  27310. var meshes;
  27311. var len;
  27312. var checkIsEnabled = true;
  27313. // Determine mesh candidates
  27314. if (this._activeMeshCandidateProvider !== undefined) {
  27315. // Use _activeMeshCandidateProvider
  27316. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27317. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27318. if (meshes !== undefined) {
  27319. len = meshes.length;
  27320. }
  27321. else {
  27322. len = 0;
  27323. }
  27324. }
  27325. else if (this._selectionOctree !== undefined) {
  27326. // Octree
  27327. var selection = this._selectionOctree.select(this._frustumPlanes);
  27328. meshes = selection.data;
  27329. len = selection.length;
  27330. }
  27331. else {
  27332. // Full scene traversal
  27333. len = this.meshes.length;
  27334. meshes = this.meshes;
  27335. }
  27336. // Check each mesh
  27337. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27338. mesh = meshes[meshIndex];
  27339. if (mesh.isBlocked) {
  27340. continue;
  27341. }
  27342. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27343. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27344. continue;
  27345. }
  27346. mesh.computeWorldMatrix();
  27347. // Intersections
  27348. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27349. this._meshesForIntersections.pushNoDuplicate(mesh);
  27350. }
  27351. // Switch to current LOD
  27352. meshLOD = mesh.getLOD(this.activeCamera);
  27353. if (meshLOD === undefined || meshLOD === null) {
  27354. continue;
  27355. }
  27356. mesh._preActivate();
  27357. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27358. this._activeMeshes.push(mesh);
  27359. this.activeCamera._activeMeshes.push(mesh);
  27360. mesh._activate(this._renderId);
  27361. if (meshLOD !== mesh) {
  27362. meshLOD._activate(this._renderId);
  27363. }
  27364. this._activeMesh(mesh, meshLOD);
  27365. }
  27366. }
  27367. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27368. // Particle systems
  27369. if (this.particlesEnabled) {
  27370. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27371. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27372. var particleSystem = this.particleSystems[particleIndex];
  27373. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27374. continue;
  27375. }
  27376. var emitter = particleSystem.emitter;
  27377. if (!emitter.position || emitter.isEnabled()) {
  27378. this._activeParticleSystems.push(particleSystem);
  27379. particleSystem.animate();
  27380. this._renderingManager.dispatchParticles(particleSystem);
  27381. }
  27382. }
  27383. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27384. }
  27385. };
  27386. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27387. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27388. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27389. mesh.skeleton.prepare();
  27390. }
  27391. if (!mesh.computeBonesUsingShaders) {
  27392. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27393. }
  27394. }
  27395. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27396. var boundingInfo = sourceMesh.getBoundingInfo();
  27397. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27398. }
  27399. if (mesh !== undefined && mesh !== null
  27400. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27401. // Submeshes Octrees
  27402. var len;
  27403. var subMeshes;
  27404. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27405. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27406. len = intersections.length;
  27407. subMeshes = intersections.data;
  27408. }
  27409. else {
  27410. subMeshes = mesh.subMeshes;
  27411. len = subMeshes.length;
  27412. }
  27413. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27414. subMesh = subMeshes[subIndex];
  27415. this._evaluateSubMesh(subMesh, mesh);
  27416. }
  27417. }
  27418. };
  27419. /**
  27420. * Update the transform matrix to update from the current active camera
  27421. * @param force defines a boolean used to force the update even if cache is up to date
  27422. */
  27423. Scene.prototype.updateTransformMatrix = function (force) {
  27424. if (!this.activeCamera) {
  27425. return;
  27426. }
  27427. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27428. };
  27429. /**
  27430. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27431. * @param alternateCamera defines the camera to use
  27432. */
  27433. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27434. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27435. };
  27436. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27437. if (camera && camera._skipRendering) {
  27438. return;
  27439. }
  27440. var engine = this._engine;
  27441. this.activeCamera = camera;
  27442. if (!this.activeCamera)
  27443. throw new Error("Active camera not set");
  27444. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27445. // Viewport
  27446. engine.setViewport(this.activeCamera.viewport);
  27447. // Camera
  27448. this.resetCachedMaterial();
  27449. this._renderId++;
  27450. this.updateTransformMatrix();
  27451. if (camera._alternateCamera) {
  27452. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27453. this._alternateRendering = true;
  27454. }
  27455. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27456. // Meshes
  27457. this._evaluateActiveMeshes();
  27458. // Software skinning
  27459. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27460. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27461. mesh.applySkeleton(mesh.skeleton);
  27462. }
  27463. // Render targets
  27464. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27465. var needsRestoreFrameBuffer = false;
  27466. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27467. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27468. }
  27469. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27470. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27471. }
  27472. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27473. this._intermediateRendering = true;
  27474. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27475. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27476. var renderTarget = this._renderTargets.data[renderIndex];
  27477. if (renderTarget._shouldRender()) {
  27478. this._renderId++;
  27479. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27480. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27481. }
  27482. }
  27483. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27484. this._intermediateRendering = false;
  27485. this._renderId++;
  27486. needsRestoreFrameBuffer = true; // Restore back buffer
  27487. }
  27488. // Render EffecttLayer Texture
  27489. var stencilState = this._engine.getStencilBuffer();
  27490. var renderEffects = false;
  27491. var needStencil = false;
  27492. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27493. this._intermediateRendering = true;
  27494. for (var i = 0; i < this.effectLayers.length; i++) {
  27495. var effectLayer = this.effectLayers[i];
  27496. if (effectLayer.shouldRender() &&
  27497. (!effectLayer.camera ||
  27498. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27499. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27500. renderEffects = true;
  27501. needStencil = needStencil || effectLayer.needStencil();
  27502. var renderTarget = effectLayer._mainTexture;
  27503. if (renderTarget._shouldRender()) {
  27504. this._renderId++;
  27505. renderTarget.render(false, false);
  27506. needsRestoreFrameBuffer = true;
  27507. }
  27508. }
  27509. }
  27510. this._intermediateRendering = false;
  27511. this._renderId++;
  27512. }
  27513. if (needsRestoreFrameBuffer) {
  27514. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27515. }
  27516. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27517. // Prepare Frame
  27518. this.postProcessManager._prepareFrame();
  27519. // Backgrounds
  27520. var layerIndex;
  27521. var layer;
  27522. if (this.layers.length) {
  27523. engine.setDepthBuffer(false);
  27524. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27525. layer = this.layers[layerIndex];
  27526. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27527. layer.render();
  27528. }
  27529. }
  27530. engine.setDepthBuffer(true);
  27531. }
  27532. // Activate effect Layer stencil
  27533. if (needStencil) {
  27534. this._engine.setStencilBuffer(true);
  27535. }
  27536. // Render
  27537. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27538. this._renderingManager.render(null, null, true, true);
  27539. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27540. // Restore effect Layer stencil
  27541. if (needStencil) {
  27542. this._engine.setStencilBuffer(stencilState);
  27543. }
  27544. // Bounding boxes
  27545. if (this._boundingBoxRenderer) {
  27546. this._boundingBoxRenderer.render();
  27547. }
  27548. // Lens flares
  27549. if (this.lensFlaresEnabled) {
  27550. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27551. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27552. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27553. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27554. lensFlareSystem.render();
  27555. }
  27556. }
  27557. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27558. }
  27559. // Effect Layer
  27560. if (renderEffects) {
  27561. engine.setDepthBuffer(false);
  27562. for (var i = 0; i < this.effectLayers.length; i++) {
  27563. if (this.effectLayers[i].shouldRender()) {
  27564. this.effectLayers[i].render();
  27565. }
  27566. }
  27567. engine.setDepthBuffer(true);
  27568. }
  27569. // Foregrounds
  27570. if (this.layers.length) {
  27571. engine.setDepthBuffer(false);
  27572. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27573. layer = this.layers[layerIndex];
  27574. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27575. layer.render();
  27576. }
  27577. }
  27578. engine.setDepthBuffer(true);
  27579. }
  27580. // Finalize frame
  27581. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27582. // Reset some special arrays
  27583. this._renderTargets.reset();
  27584. this._alternateRendering = false;
  27585. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27586. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27587. };
  27588. Scene.prototype._processSubCameras = function (camera) {
  27589. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27590. this._renderForCamera(camera);
  27591. return;
  27592. }
  27593. // rig cameras
  27594. for (var index = 0; index < camera._rigCameras.length; index++) {
  27595. this._renderForCamera(camera._rigCameras[index], camera);
  27596. }
  27597. this.activeCamera = camera;
  27598. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27599. };
  27600. Scene.prototype._checkIntersections = function () {
  27601. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27602. var sourceMesh = this._meshesForIntersections.data[index];
  27603. if (!sourceMesh.actionManager) {
  27604. continue;
  27605. }
  27606. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27607. var action = sourceMesh.actionManager.actions[actionIndex];
  27608. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27609. var parameters = action.getTriggerParameter();
  27610. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27611. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27612. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27613. if (areIntersecting && currentIntersectionInProgress === -1) {
  27614. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27615. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27616. sourceMesh._intersectionsInProgress.push(otherMesh);
  27617. }
  27618. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27619. sourceMesh._intersectionsInProgress.push(otherMesh);
  27620. }
  27621. }
  27622. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27623. //They intersected, and now they don't.
  27624. //is this trigger an exit trigger? execute an event.
  27625. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27626. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27627. }
  27628. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27629. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27630. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27631. return otherMesh === parameterMesh;
  27632. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27633. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27634. }
  27635. }
  27636. }
  27637. }
  27638. }
  27639. };
  27640. /**
  27641. * Render the scene
  27642. */
  27643. Scene.prototype.render = function () {
  27644. if (this.isDisposed) {
  27645. return;
  27646. }
  27647. this._activeParticles.fetchNewFrame();
  27648. this._totalVertices.fetchNewFrame();
  27649. this._activeIndices.fetchNewFrame();
  27650. this._activeBones.fetchNewFrame();
  27651. this._meshesForIntersections.reset();
  27652. this.resetCachedMaterial();
  27653. this.onBeforeAnimationsObservable.notifyObservers(this);
  27654. // Actions
  27655. if (this.actionManager) {
  27656. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27657. }
  27658. //Simplification Queue
  27659. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27660. this.simplificationQueue.executeNext();
  27661. }
  27662. if (this._engine.isDeterministicLockStep()) {
  27663. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27664. var defaultFPS = (60.0 / 1000.0);
  27665. var defaultFrameTime = 1000 / 60; // frame time in MS
  27666. if (this._physicsEngine) {
  27667. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27668. }
  27669. var stepsTaken = 0;
  27670. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27671. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27672. internalSteps = Math.min(internalSteps, maxSubSteps);
  27673. do {
  27674. this.onBeforeStepObservable.notifyObservers(this);
  27675. // Animations
  27676. this._animationRatio = defaultFrameTime * defaultFPS;
  27677. this._animate();
  27678. this.onAfterAnimationsObservable.notifyObservers(this);
  27679. // Physics
  27680. if (this._physicsEngine) {
  27681. this.onBeforePhysicsObservable.notifyObservers(this);
  27682. this._physicsEngine._step(defaultFrameTime / 1000);
  27683. this.onAfterPhysicsObservable.notifyObservers(this);
  27684. }
  27685. this.onAfterStepObservable.notifyObservers(this);
  27686. this._currentStepId++;
  27687. stepsTaken++;
  27688. deltaTime -= defaultFrameTime;
  27689. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27690. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27691. }
  27692. else {
  27693. // Animations
  27694. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27695. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27696. this._animate();
  27697. this.onAfterAnimationsObservable.notifyObservers(this);
  27698. // Physics
  27699. if (this._physicsEngine) {
  27700. this.onBeforePhysicsObservable.notifyObservers(this);
  27701. this._physicsEngine._step(deltaTime / 1000.0);
  27702. this.onAfterPhysicsObservable.notifyObservers(this);
  27703. }
  27704. }
  27705. // update gamepad manager
  27706. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27707. this._gamepadManager._checkGamepadsStatus();
  27708. }
  27709. // Update Cameras
  27710. if (this.activeCameras.length > 0) {
  27711. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27712. var camera = this.activeCameras[cameraIndex];
  27713. camera.update();
  27714. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27715. // rig cameras
  27716. for (var index = 0; index < camera._rigCameras.length; index++) {
  27717. camera._rigCameras[index].update();
  27718. }
  27719. }
  27720. }
  27721. }
  27722. else if (this.activeCamera) {
  27723. this.activeCamera.update();
  27724. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27725. // rig cameras
  27726. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27727. this.activeCamera._rigCameras[index].update();
  27728. }
  27729. }
  27730. }
  27731. // Before render
  27732. this.onBeforeRenderObservable.notifyObservers(this);
  27733. // Customs render targets
  27734. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27735. var engine = this.getEngine();
  27736. var currentActiveCamera = this.activeCamera;
  27737. if (this.renderTargetsEnabled) {
  27738. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27739. this._intermediateRendering = true;
  27740. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27741. var renderTarget = this.customRenderTargets[customIndex];
  27742. if (renderTarget._shouldRender()) {
  27743. this._renderId++;
  27744. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27745. if (!this.activeCamera)
  27746. throw new Error("Active camera not set");
  27747. // Viewport
  27748. engine.setViewport(this.activeCamera.viewport);
  27749. // Camera
  27750. this.updateTransformMatrix();
  27751. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27752. }
  27753. }
  27754. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27755. this._intermediateRendering = false;
  27756. this._renderId++;
  27757. }
  27758. // Restore back buffer
  27759. if (this.customRenderTargets.length > 0) {
  27760. engine.restoreDefaultFramebuffer();
  27761. }
  27762. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27763. this.activeCamera = currentActiveCamera;
  27764. // Procedural textures
  27765. if (this.proceduralTexturesEnabled) {
  27766. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27767. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27768. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27769. if (proceduralTexture._shouldRender()) {
  27770. proceduralTexture.render();
  27771. }
  27772. }
  27773. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27774. }
  27775. // Clear
  27776. if (this.autoClearDepthAndStencil || this.autoClear) {
  27777. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27778. }
  27779. // Shadows
  27780. if (this.shadowsEnabled) {
  27781. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27782. var light = this.lights[lightIndex];
  27783. var shadowGenerator = light.getShadowGenerator();
  27784. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27785. var shadowMap = (shadowGenerator.getShadowMap());
  27786. if (this.textures.indexOf(shadowMap) !== -1) {
  27787. this._renderTargets.push(shadowMap);
  27788. }
  27789. }
  27790. }
  27791. }
  27792. // Depth renderer
  27793. for (var key in this._depthRenderer) {
  27794. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27795. }
  27796. // Geometry renderer
  27797. if (this._geometryBufferRenderer) {
  27798. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27799. }
  27800. // RenderPipeline
  27801. if (this._postProcessRenderPipelineManager) {
  27802. this._postProcessRenderPipelineManager.update();
  27803. }
  27804. // Multi-cameras?
  27805. if (this.activeCameras.length > 0) {
  27806. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27807. if (cameraIndex > 0) {
  27808. this._engine.clear(null, false, true, true);
  27809. }
  27810. this._processSubCameras(this.activeCameras[cameraIndex]);
  27811. }
  27812. }
  27813. else {
  27814. if (!this.activeCamera) {
  27815. throw new Error("No camera defined");
  27816. }
  27817. this._processSubCameras(this.activeCamera);
  27818. }
  27819. // Intersection checks
  27820. this._checkIntersections();
  27821. // Update the audio listener attached to the camera
  27822. if (BABYLON.AudioEngine) {
  27823. this._updateAudioParameters();
  27824. }
  27825. // After render
  27826. if (this.afterRender) {
  27827. this.afterRender();
  27828. }
  27829. this.onAfterRenderObservable.notifyObservers(this);
  27830. // Cleaning
  27831. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27832. var data = this._toBeDisposed.data[index];
  27833. if (data) {
  27834. data.dispose();
  27835. }
  27836. this._toBeDisposed[index] = null;
  27837. }
  27838. this._toBeDisposed.reset();
  27839. if (this.dumpNextRenderTargets) {
  27840. this.dumpNextRenderTargets = false;
  27841. }
  27842. this._activeBones.addCount(0, true);
  27843. this._activeIndices.addCount(0, true);
  27844. this._activeParticles.addCount(0, true);
  27845. };
  27846. Scene.prototype._updateAudioParameters = function () {
  27847. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27848. return;
  27849. }
  27850. var listeningCamera;
  27851. var audioEngine = BABYLON.Engine.audioEngine;
  27852. if (this.activeCameras.length > 0) {
  27853. listeningCamera = this.activeCameras[0];
  27854. }
  27855. else {
  27856. listeningCamera = this.activeCamera;
  27857. }
  27858. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27859. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27860. // for VR cameras
  27861. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27862. listeningCamera = listeningCamera.rigCameras[0];
  27863. }
  27864. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27865. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27866. cameraDirection.normalize();
  27867. // To avoid some errors on GearVR
  27868. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27869. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27870. }
  27871. var i;
  27872. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27873. var sound = this.mainSoundTrack.soundCollection[i];
  27874. if (sound.useCustomAttenuation) {
  27875. sound.updateDistanceFromListener();
  27876. }
  27877. }
  27878. for (i = 0; i < this.soundTracks.length; i++) {
  27879. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27880. sound = this.soundTracks[i].soundCollection[j];
  27881. if (sound.useCustomAttenuation) {
  27882. sound.updateDistanceFromListener();
  27883. }
  27884. }
  27885. }
  27886. }
  27887. };
  27888. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27889. // Audio
  27890. /**
  27891. * Gets or sets if audio support is enabled
  27892. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27893. */
  27894. get: function () {
  27895. return this._audioEnabled;
  27896. },
  27897. set: function (value) {
  27898. this._audioEnabled = value;
  27899. if (BABYLON.AudioEngine) {
  27900. if (this._audioEnabled) {
  27901. this._enableAudio();
  27902. }
  27903. else {
  27904. this._disableAudio();
  27905. }
  27906. }
  27907. },
  27908. enumerable: true,
  27909. configurable: true
  27910. });
  27911. Scene.prototype._disableAudio = function () {
  27912. var i;
  27913. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27914. this.mainSoundTrack.soundCollection[i].pause();
  27915. }
  27916. for (i = 0; i < this.soundTracks.length; i++) {
  27917. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27918. this.soundTracks[i].soundCollection[j].pause();
  27919. }
  27920. }
  27921. };
  27922. Scene.prototype._enableAudio = function () {
  27923. var i;
  27924. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27925. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27926. this.mainSoundTrack.soundCollection[i].play();
  27927. }
  27928. }
  27929. for (i = 0; i < this.soundTracks.length; i++) {
  27930. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27931. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27932. this.soundTracks[i].soundCollection[j].play();
  27933. }
  27934. }
  27935. }
  27936. };
  27937. Object.defineProperty(Scene.prototype, "headphone", {
  27938. /**
  27939. * Gets or sets if audio will be output to headphones
  27940. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27941. */
  27942. get: function () {
  27943. return this._headphone;
  27944. },
  27945. set: function (value) {
  27946. this._headphone = value;
  27947. if (BABYLON.AudioEngine) {
  27948. if (this._headphone) {
  27949. this._switchAudioModeForHeadphones();
  27950. }
  27951. else {
  27952. this._switchAudioModeForNormalSpeakers();
  27953. }
  27954. }
  27955. },
  27956. enumerable: true,
  27957. configurable: true
  27958. });
  27959. Scene.prototype._switchAudioModeForHeadphones = function () {
  27960. this.mainSoundTrack.switchPanningModelToHRTF();
  27961. for (var i = 0; i < this.soundTracks.length; i++) {
  27962. this.soundTracks[i].switchPanningModelToHRTF();
  27963. }
  27964. };
  27965. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27966. this.mainSoundTrack.switchPanningModelToEqualPower();
  27967. for (var i = 0; i < this.soundTracks.length; i++) {
  27968. this.soundTracks[i].switchPanningModelToEqualPower();
  27969. }
  27970. };
  27971. /**
  27972. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27973. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27974. * @returns the created depth renderer
  27975. */
  27976. Scene.prototype.enableDepthRenderer = function (camera) {
  27977. camera = camera || this.activeCamera;
  27978. if (!camera) {
  27979. throw "No camera available to enable depth renderer";
  27980. }
  27981. if (!this._depthRenderer[camera.id]) {
  27982. var textureType = 0;
  27983. if (this._engine.getCaps().textureHalfFloatRender) {
  27984. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27985. }
  27986. else if (this._engine.getCaps().textureFloatRender) {
  27987. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27988. }
  27989. else {
  27990. throw "Depth renderer does not support int texture type";
  27991. }
  27992. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27993. }
  27994. return this._depthRenderer[camera.id];
  27995. };
  27996. /**
  27997. * Disables a depth renderer for a given camera
  27998. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27999. */
  28000. Scene.prototype.disableDepthRenderer = function (camera) {
  28001. camera = camera || this.activeCamera;
  28002. if (!camera || !this._depthRenderer[camera.id]) {
  28003. return;
  28004. }
  28005. this._depthRenderer[camera.id].dispose();
  28006. delete this._depthRenderer[camera.id];
  28007. };
  28008. /**
  28009. * Enables a GeometryBufferRender and associates it with the scene
  28010. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28011. * @returns the GeometryBufferRenderer
  28012. */
  28013. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28014. if (ratio === void 0) { ratio = 1; }
  28015. if (this._geometryBufferRenderer) {
  28016. return this._geometryBufferRenderer;
  28017. }
  28018. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28019. if (!this._geometryBufferRenderer.isSupported) {
  28020. this._geometryBufferRenderer = null;
  28021. }
  28022. return this._geometryBufferRenderer;
  28023. };
  28024. /**
  28025. * Disables the GeometryBufferRender associated with the scene
  28026. */
  28027. Scene.prototype.disableGeometryBufferRenderer = function () {
  28028. if (!this._geometryBufferRenderer) {
  28029. return;
  28030. }
  28031. this._geometryBufferRenderer.dispose();
  28032. this._geometryBufferRenderer = null;
  28033. };
  28034. /**
  28035. * Freeze all materials
  28036. * A frozen material will not be updatable but should be faster to render
  28037. */
  28038. Scene.prototype.freezeMaterials = function () {
  28039. for (var i = 0; i < this.materials.length; i++) {
  28040. this.materials[i].freeze();
  28041. }
  28042. };
  28043. /**
  28044. * Unfreeze all materials
  28045. * A frozen material will not be updatable but should be faster to render
  28046. */
  28047. Scene.prototype.unfreezeMaterials = function () {
  28048. for (var i = 0; i < this.materials.length; i++) {
  28049. this.materials[i].unfreeze();
  28050. }
  28051. };
  28052. /**
  28053. * Releases all held ressources
  28054. */
  28055. Scene.prototype.dispose = function () {
  28056. this.beforeRender = null;
  28057. this.afterRender = null;
  28058. this.skeletons = [];
  28059. this.morphTargetManagers = [];
  28060. this.importedMeshesFiles = new Array();
  28061. this.stopAllAnimations();
  28062. this.resetCachedMaterial();
  28063. for (var key in this._depthRenderer) {
  28064. this._depthRenderer[key].dispose();
  28065. }
  28066. if (this._gamepadManager) {
  28067. this._gamepadManager.dispose();
  28068. this._gamepadManager = null;
  28069. }
  28070. // Smart arrays
  28071. if (this.activeCamera) {
  28072. this.activeCamera._activeMeshes.dispose();
  28073. this.activeCamera = null;
  28074. }
  28075. this._activeMeshes.dispose();
  28076. this._renderingManager.dispose();
  28077. this._processedMaterials.dispose();
  28078. this._activeParticleSystems.dispose();
  28079. this._activeSkeletons.dispose();
  28080. this._softwareSkinnedMeshes.dispose();
  28081. this._renderTargets.dispose();
  28082. this._registeredForLateAnimationBindings.dispose();
  28083. if (this._boundingBoxRenderer) {
  28084. this._boundingBoxRenderer.dispose();
  28085. }
  28086. this._meshesForIntersections.dispose();
  28087. this._toBeDisposed.dispose();
  28088. // Abort active requests
  28089. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28090. var request = _a[_i];
  28091. request.abort();
  28092. }
  28093. // Debug layer
  28094. if (this._debugLayer) {
  28095. this._debugLayer.hide();
  28096. }
  28097. // Events
  28098. this.onDisposeObservable.notifyObservers(this);
  28099. this.onDisposeObservable.clear();
  28100. this.onBeforeRenderObservable.clear();
  28101. this.onAfterRenderObservable.clear();
  28102. this.onBeforeRenderTargetsRenderObservable.clear();
  28103. this.onAfterRenderTargetsRenderObservable.clear();
  28104. this.onAfterStepObservable.clear();
  28105. this.onBeforeStepObservable.clear();
  28106. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28107. this.onAfterActiveMeshesEvaluationObservable.clear();
  28108. this.onBeforeParticlesRenderingObservable.clear();
  28109. this.onAfterParticlesRenderingObservable.clear();
  28110. this.onBeforeSpritesRenderingObservable.clear();
  28111. this.onAfterSpritesRenderingObservable.clear();
  28112. this.onBeforeDrawPhaseObservable.clear();
  28113. this.onAfterDrawPhaseObservable.clear();
  28114. this.onBeforePhysicsObservable.clear();
  28115. this.onAfterPhysicsObservable.clear();
  28116. this.onBeforeAnimationsObservable.clear();
  28117. this.onAfterAnimationsObservable.clear();
  28118. this.onDataLoadedObservable.clear();
  28119. this.detachControl();
  28120. // Release sounds & sounds tracks
  28121. if (BABYLON.AudioEngine) {
  28122. this.disposeSounds();
  28123. }
  28124. // VR Helper
  28125. if (this.VRHelper) {
  28126. this.VRHelper.dispose();
  28127. }
  28128. // Detach cameras
  28129. var canvas = this._engine.getRenderingCanvas();
  28130. if (canvas) {
  28131. var index;
  28132. for (index = 0; index < this.cameras.length; index++) {
  28133. this.cameras[index].detachControl(canvas);
  28134. }
  28135. }
  28136. // Release animation groups
  28137. while (this.animationGroups.length) {
  28138. this.animationGroups[0].dispose();
  28139. }
  28140. // Release lights
  28141. while (this.lights.length) {
  28142. this.lights[0].dispose();
  28143. }
  28144. // Release meshes
  28145. while (this.meshes.length) {
  28146. this.meshes[0].dispose(true);
  28147. }
  28148. while (this.transformNodes.length) {
  28149. this.removeTransformNode(this.transformNodes[0]);
  28150. }
  28151. // Release cameras
  28152. while (this.cameras.length) {
  28153. this.cameras[0].dispose();
  28154. }
  28155. // Release materials
  28156. if (this.defaultMaterial) {
  28157. this.defaultMaterial.dispose();
  28158. }
  28159. while (this.multiMaterials.length) {
  28160. this.multiMaterials[0].dispose();
  28161. }
  28162. while (this.materials.length) {
  28163. this.materials[0].dispose();
  28164. }
  28165. // Release particles
  28166. while (this.particleSystems.length) {
  28167. this.particleSystems[0].dispose();
  28168. }
  28169. // Release sprites
  28170. while (this.spriteManagers.length) {
  28171. this.spriteManagers[0].dispose();
  28172. }
  28173. // Release postProcesses
  28174. while (this.postProcesses.length) {
  28175. this.postProcesses[0].dispose();
  28176. }
  28177. // Release layers
  28178. while (this.layers.length) {
  28179. this.layers[0].dispose();
  28180. }
  28181. while (this.effectLayers.length) {
  28182. this.effectLayers[0].dispose();
  28183. }
  28184. // Release textures
  28185. while (this.textures.length) {
  28186. this.textures[0].dispose();
  28187. }
  28188. // Release UBO
  28189. this._sceneUbo.dispose();
  28190. if (this._alternateSceneUbo) {
  28191. this._alternateSceneUbo.dispose();
  28192. }
  28193. // Post-processes
  28194. this.postProcessManager.dispose();
  28195. if (this._postProcessRenderPipelineManager) {
  28196. this._postProcessRenderPipelineManager.dispose();
  28197. }
  28198. // Physics
  28199. if (this._physicsEngine) {
  28200. this.disablePhysicsEngine();
  28201. }
  28202. // Remove from engine
  28203. index = this._engine.scenes.indexOf(this);
  28204. if (index > -1) {
  28205. this._engine.scenes.splice(index, 1);
  28206. }
  28207. this._engine.wipeCaches(true);
  28208. this._isDisposed = true;
  28209. };
  28210. Object.defineProperty(Scene.prototype, "isDisposed", {
  28211. /**
  28212. * Gets if the scene is already disposed
  28213. */
  28214. get: function () {
  28215. return this._isDisposed;
  28216. },
  28217. enumerable: true,
  28218. configurable: true
  28219. });
  28220. /**
  28221. * Releases sounds & soundtracks
  28222. */
  28223. Scene.prototype.disposeSounds = function () {
  28224. if (!this._mainSoundTrack) {
  28225. return;
  28226. }
  28227. this.mainSoundTrack.dispose();
  28228. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28229. this.soundTracks[scIndex].dispose();
  28230. }
  28231. };
  28232. // Octrees
  28233. /**
  28234. * Get the world extend vectors with an optional filter
  28235. *
  28236. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28237. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28238. */
  28239. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28240. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28241. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28242. filterPredicate = filterPredicate || (function () { return true; });
  28243. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28244. mesh.computeWorldMatrix(true);
  28245. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28246. return;
  28247. }
  28248. var boundingInfo = mesh.getBoundingInfo();
  28249. var minBox = boundingInfo.boundingBox.minimumWorld;
  28250. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28251. BABYLON.Tools.CheckExtends(minBox, min, max);
  28252. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28253. });
  28254. return {
  28255. min: min,
  28256. max: max
  28257. };
  28258. };
  28259. /**
  28260. * Creates or updates the octree used to boost selection (picking)
  28261. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28262. * @param maxCapacity defines the maximum capacity per leaf
  28263. * @param maxDepth defines the maximum depth of the octree
  28264. * @returns an octree of AbstractMesh
  28265. */
  28266. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28267. if (maxCapacity === void 0) { maxCapacity = 64; }
  28268. if (maxDepth === void 0) { maxDepth = 2; }
  28269. if (!this._selectionOctree) {
  28270. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28271. }
  28272. var worldExtends = this.getWorldExtends();
  28273. // Update octree
  28274. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28275. return this._selectionOctree;
  28276. };
  28277. // Picking
  28278. /**
  28279. * Creates a ray that can be used to pick in the scene
  28280. * @param x defines the x coordinate of the origin (on-screen)
  28281. * @param y defines the y coordinate of the origin (on-screen)
  28282. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28283. * @param camera defines the camera to use for the picking
  28284. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28285. * @returns a Ray
  28286. */
  28287. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28288. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28289. var result = BABYLON.Ray.Zero();
  28290. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28291. return result;
  28292. };
  28293. /**
  28294. * Creates a ray that can be used to pick in the scene
  28295. * @param x defines the x coordinate of the origin (on-screen)
  28296. * @param y defines the y coordinate of the origin (on-screen)
  28297. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28298. * @param result defines the ray where to store the picking ray
  28299. * @param camera defines the camera to use for the picking
  28300. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28301. * @returns the current scene
  28302. */
  28303. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28304. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28305. var engine = this._engine;
  28306. if (!camera) {
  28307. if (!this.activeCamera)
  28308. throw new Error("Active camera not set");
  28309. camera = this.activeCamera;
  28310. }
  28311. var cameraViewport = camera.viewport;
  28312. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28313. // Moving coordinates to local viewport world
  28314. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28315. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28316. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28317. return this;
  28318. };
  28319. /**
  28320. * Creates a ray that can be used to pick in the scene
  28321. * @param x defines the x coordinate of the origin (on-screen)
  28322. * @param y defines the y coordinate of the origin (on-screen)
  28323. * @param camera defines the camera to use for the picking
  28324. * @returns a Ray
  28325. */
  28326. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28327. var result = BABYLON.Ray.Zero();
  28328. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28329. return result;
  28330. };
  28331. /**
  28332. * Creates a ray that can be used to pick in the scene
  28333. * @param x defines the x coordinate of the origin (on-screen)
  28334. * @param y defines the y coordinate of the origin (on-screen)
  28335. * @param result defines the ray where to store the picking ray
  28336. * @param camera defines the camera to use for the picking
  28337. * @returns the current scene
  28338. */
  28339. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28340. if (!BABYLON.PickingInfo) {
  28341. return this;
  28342. }
  28343. var engine = this._engine;
  28344. if (!camera) {
  28345. if (!this.activeCamera)
  28346. throw new Error("Active camera not set");
  28347. camera = this.activeCamera;
  28348. }
  28349. var cameraViewport = camera.viewport;
  28350. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28351. var identity = BABYLON.Matrix.Identity();
  28352. // Moving coordinates to local viewport world
  28353. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28354. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28355. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28356. return this;
  28357. };
  28358. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28359. if (!BABYLON.PickingInfo) {
  28360. return null;
  28361. }
  28362. var pickingInfo = null;
  28363. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28364. var mesh = this.meshes[meshIndex];
  28365. if (predicate) {
  28366. if (!predicate(mesh)) {
  28367. continue;
  28368. }
  28369. }
  28370. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28371. continue;
  28372. }
  28373. var world = mesh.getWorldMatrix();
  28374. var ray = rayFunction(world);
  28375. var result = mesh.intersects(ray, fastCheck);
  28376. if (!result || !result.hit)
  28377. continue;
  28378. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28379. continue;
  28380. pickingInfo = result;
  28381. if (fastCheck) {
  28382. break;
  28383. }
  28384. }
  28385. return pickingInfo || new BABYLON.PickingInfo();
  28386. };
  28387. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28388. if (!BABYLON.PickingInfo) {
  28389. return null;
  28390. }
  28391. var pickingInfos = new Array();
  28392. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28393. var mesh = this.meshes[meshIndex];
  28394. if (predicate) {
  28395. if (!predicate(mesh)) {
  28396. continue;
  28397. }
  28398. }
  28399. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28400. continue;
  28401. }
  28402. var world = mesh.getWorldMatrix();
  28403. var ray = rayFunction(world);
  28404. var result = mesh.intersects(ray, false);
  28405. if (!result || !result.hit)
  28406. continue;
  28407. pickingInfos.push(result);
  28408. }
  28409. return pickingInfos;
  28410. };
  28411. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28412. if (!BABYLON.PickingInfo) {
  28413. return null;
  28414. }
  28415. var pickingInfo = null;
  28416. if (!camera) {
  28417. if (!this.activeCamera) {
  28418. return null;
  28419. }
  28420. camera = this.activeCamera;
  28421. }
  28422. if (this.spriteManagers.length > 0) {
  28423. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28424. var spriteManager = this.spriteManagers[spriteIndex];
  28425. if (!spriteManager.isPickable) {
  28426. continue;
  28427. }
  28428. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28429. if (!result || !result.hit)
  28430. continue;
  28431. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28432. continue;
  28433. pickingInfo = result;
  28434. if (fastCheck) {
  28435. break;
  28436. }
  28437. }
  28438. }
  28439. return pickingInfo || new BABYLON.PickingInfo();
  28440. };
  28441. /** Launch a ray to try to pick a mesh in the scene
  28442. * @param x position on screen
  28443. * @param y position on screen
  28444. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  28445. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28446. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28447. * @returns a PickingInfo
  28448. */
  28449. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28450. var _this = this;
  28451. if (!BABYLON.PickingInfo) {
  28452. return null;
  28453. }
  28454. return this._internalPick(function (world) {
  28455. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28456. return _this._tempPickingRay;
  28457. }, predicate, fastCheck);
  28458. };
  28459. /** Launch a ray to try to pick a sprite in the scene
  28460. * @param x position on screen
  28461. * @param y position on screen
  28462. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28463. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28464. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28465. * @returns a PickingInfo
  28466. */
  28467. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28468. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28469. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28470. };
  28471. /** Use the given ray to pick a mesh in the scene
  28472. * @param ray The ray to use to pick meshes
  28473. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28474. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28475. * @returns a PickingInfo
  28476. */
  28477. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28478. var _this = this;
  28479. return this._internalPick(function (world) {
  28480. if (!_this._pickWithRayInverseMatrix) {
  28481. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28482. }
  28483. world.invertToRef(_this._pickWithRayInverseMatrix);
  28484. if (!_this._cachedRayForTransform) {
  28485. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28486. }
  28487. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28488. return _this._cachedRayForTransform;
  28489. }, predicate, fastCheck);
  28490. };
  28491. /**
  28492. * Launch a ray to try to pick a mesh in the scene
  28493. * @param x X position on screen
  28494. * @param y Y position on screen
  28495. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  28496. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28497. * @returns an array of PickingInfo
  28498. */
  28499. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28500. var _this = this;
  28501. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28502. };
  28503. /**
  28504. * Launch a ray to try to pick a mesh in the scene
  28505. * @param ray Ray to use
  28506. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  28507. * @returns an array of PickingInfo
  28508. */
  28509. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28510. var _this = this;
  28511. return this._internalMultiPick(function (world) {
  28512. if (!_this._pickWithRayInverseMatrix) {
  28513. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28514. }
  28515. world.invertToRef(_this._pickWithRayInverseMatrix);
  28516. if (!_this._cachedRayForTransform) {
  28517. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28518. }
  28519. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28520. return _this._cachedRayForTransform;
  28521. }, predicate);
  28522. };
  28523. /**
  28524. * Force the value of meshUnderPointer
  28525. * @param mesh defines the mesh to use
  28526. */
  28527. Scene.prototype.setPointerOverMesh = function (mesh) {
  28528. if (this._pointerOverMesh === mesh) {
  28529. return;
  28530. }
  28531. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28532. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28533. }
  28534. this._pointerOverMesh = mesh;
  28535. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28536. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28537. }
  28538. };
  28539. /**
  28540. * Gets the mesh under the pointer
  28541. * @returns a Mesh or null if no mesh is under the pointer
  28542. */
  28543. Scene.prototype.getPointerOverMesh = function () {
  28544. return this._pointerOverMesh;
  28545. };
  28546. /**
  28547. * Force the sprite under the pointer
  28548. * @param sprite defines the sprite to use
  28549. */
  28550. Scene.prototype.setPointerOverSprite = function (sprite) {
  28551. if (this._pointerOverSprite === sprite) {
  28552. return;
  28553. }
  28554. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28555. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28556. }
  28557. this._pointerOverSprite = sprite;
  28558. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28559. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28560. }
  28561. };
  28562. /**
  28563. * Gets the sprite under the pointer
  28564. * @returns a Sprite or null if no sprite is under the pointer
  28565. */
  28566. Scene.prototype.getPointerOverSprite = function () {
  28567. return this._pointerOverSprite;
  28568. };
  28569. // Physics
  28570. /**
  28571. * Gets the current physics engine
  28572. * @returns a PhysicsEngine or null if none attached
  28573. */
  28574. Scene.prototype.getPhysicsEngine = function () {
  28575. return this._physicsEngine;
  28576. };
  28577. /**
  28578. * Enables physics to the current scene
  28579. * @param gravity defines the scene's gravity for the physics engine
  28580. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28581. * @return a boolean indicating if the physics engine was initialized
  28582. */
  28583. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28584. if (gravity === void 0) { gravity = null; }
  28585. if (this._physicsEngine) {
  28586. return true;
  28587. }
  28588. try {
  28589. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28590. return true;
  28591. }
  28592. catch (e) {
  28593. BABYLON.Tools.Error(e.message);
  28594. return false;
  28595. }
  28596. };
  28597. /**
  28598. * Disables and disposes the physics engine associated with the scene
  28599. */
  28600. Scene.prototype.disablePhysicsEngine = function () {
  28601. if (!this._physicsEngine) {
  28602. return;
  28603. }
  28604. this._physicsEngine.dispose();
  28605. this._physicsEngine = null;
  28606. };
  28607. /**
  28608. * Gets a boolean indicating if there is an active physics engine
  28609. * @returns a boolean indicating if there is an active physics engine
  28610. */
  28611. Scene.prototype.isPhysicsEnabled = function () {
  28612. return this._physicsEngine !== undefined;
  28613. };
  28614. /**
  28615. * Deletes a physics compound impostor
  28616. * @param compound defines the compound to delete
  28617. */
  28618. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28619. var mesh = compound.parts[0].mesh;
  28620. if (mesh.physicsImpostor) {
  28621. mesh.physicsImpostor.dispose( /*true*/);
  28622. mesh.physicsImpostor = null;
  28623. }
  28624. };
  28625. // Misc.
  28626. /** @hidden */
  28627. Scene.prototype._rebuildGeometries = function () {
  28628. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28629. var geometry = _a[_i];
  28630. geometry._rebuild();
  28631. }
  28632. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28633. var mesh = _c[_b];
  28634. mesh._rebuild();
  28635. }
  28636. if (this.postProcessManager) {
  28637. this.postProcessManager._rebuild();
  28638. }
  28639. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28640. var layer = _e[_d];
  28641. layer._rebuild();
  28642. }
  28643. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28644. var effectLayer = _g[_f];
  28645. effectLayer._rebuild();
  28646. }
  28647. if (this._boundingBoxRenderer) {
  28648. this._boundingBoxRenderer._rebuild();
  28649. }
  28650. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28651. var system = _j[_h];
  28652. system.rebuild();
  28653. }
  28654. if (this._postProcessRenderPipelineManager) {
  28655. this._postProcessRenderPipelineManager._rebuild();
  28656. }
  28657. };
  28658. /** @hidden */
  28659. Scene.prototype._rebuildTextures = function () {
  28660. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28661. var texture = _a[_i];
  28662. texture._rebuild();
  28663. }
  28664. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28665. };
  28666. /**
  28667. * Creates a default light for the scene.
  28668. * @param replace Whether to replace the existing lights in the scene.
  28669. */
  28670. Scene.prototype.createDefaultLight = function (replace) {
  28671. if (replace === void 0) { replace = false; }
  28672. // Dispose existing light in replace mode.
  28673. if (replace) {
  28674. if (this.lights) {
  28675. for (var i = 0; i < this.lights.length; i++) {
  28676. this.lights[i].dispose();
  28677. }
  28678. }
  28679. }
  28680. // Light
  28681. if (this.lights.length === 0) {
  28682. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28683. }
  28684. };
  28685. /**
  28686. * Creates a default camera for the scene.
  28687. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28688. * @param replace Whether to replace the existing active camera in the scene.
  28689. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28690. */
  28691. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28692. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28693. if (replace === void 0) { replace = false; }
  28694. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28695. // Dispose existing camera in replace mode.
  28696. if (replace) {
  28697. if (this.activeCamera) {
  28698. this.activeCamera.dispose();
  28699. this.activeCamera = null;
  28700. }
  28701. }
  28702. // Camera
  28703. if (!this.activeCamera) {
  28704. var worldExtends = this.getWorldExtends();
  28705. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28706. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28707. var camera;
  28708. var radius = worldSize.length() * 1.5;
  28709. // empty scene scenario!
  28710. if (!isFinite(radius)) {
  28711. radius = 1;
  28712. worldCenter.copyFromFloats(0, 0, 0);
  28713. }
  28714. if (createArcRotateCamera) {
  28715. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28716. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28717. arcRotateCamera.wheelPrecision = 100 / radius;
  28718. camera = arcRotateCamera;
  28719. }
  28720. else {
  28721. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28722. freeCamera.setTarget(worldCenter);
  28723. camera = freeCamera;
  28724. }
  28725. camera.minZ = radius * 0.01;
  28726. camera.maxZ = radius * 1000;
  28727. camera.speed = radius * 0.2;
  28728. this.activeCamera = camera;
  28729. var canvas = this.getEngine().getRenderingCanvas();
  28730. if (attachCameraControls && canvas) {
  28731. camera.attachControl(canvas);
  28732. }
  28733. }
  28734. };
  28735. /**
  28736. * Creates a default camera and a default light
  28737. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28738. * @param replace defines if the camera and/or light will replace the existing ones
  28739. * @param attachCameraControls defines if attachControl will be called on the new camera
  28740. */
  28741. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28742. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28743. if (replace === void 0) { replace = false; }
  28744. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28745. this.createDefaultLight(replace);
  28746. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28747. };
  28748. /**
  28749. * Creates a new sky box
  28750. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28751. * @param environmentTexture defines the texture to use as environment texture
  28752. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28753. * @param scale defines the overall scale of the skybox
  28754. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28755. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28756. * @returns a new mesh holding the sky box
  28757. */
  28758. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28759. if (pbr === void 0) { pbr = false; }
  28760. if (scale === void 0) { scale = 1000; }
  28761. if (blur === void 0) { blur = 0; }
  28762. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28763. if (!environmentTexture) {
  28764. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28765. return null;
  28766. }
  28767. if (setGlobalEnvTexture) {
  28768. if (environmentTexture) {
  28769. this.environmentTexture = environmentTexture;
  28770. }
  28771. }
  28772. // Skybox
  28773. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28774. if (pbr) {
  28775. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28776. hdrSkyboxMaterial.backFaceCulling = false;
  28777. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28778. if (hdrSkyboxMaterial.reflectionTexture) {
  28779. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28780. }
  28781. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28782. hdrSkyboxMaterial.disableLighting = true;
  28783. hdrSkyboxMaterial.twoSidedLighting = true;
  28784. hdrSkybox.infiniteDistance = true;
  28785. hdrSkybox.material = hdrSkyboxMaterial;
  28786. }
  28787. else {
  28788. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28789. skyboxMaterial.backFaceCulling = false;
  28790. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28791. if (skyboxMaterial.reflectionTexture) {
  28792. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28793. }
  28794. skyboxMaterial.disableLighting = true;
  28795. hdrSkybox.infiniteDistance = true;
  28796. hdrSkybox.material = skyboxMaterial;
  28797. }
  28798. return hdrSkybox;
  28799. };
  28800. /**
  28801. * Creates a new environment
  28802. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28803. * @param options defines the options you can use to configure the environment
  28804. * @returns the new EnvironmentHelper
  28805. */
  28806. Scene.prototype.createDefaultEnvironment = function (options) {
  28807. if (BABYLON.EnvironmentHelper) {
  28808. return new BABYLON.EnvironmentHelper(options, this);
  28809. }
  28810. return null;
  28811. };
  28812. /**
  28813. * Creates a new VREXperienceHelper
  28814. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28815. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28816. * @returns a new VREXperienceHelper
  28817. */
  28818. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28819. if (webVROptions === void 0) { webVROptions = {}; }
  28820. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28821. };
  28822. // Tags
  28823. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28824. if (tagsQuery === undefined) {
  28825. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28826. return list;
  28827. }
  28828. var listByTags = [];
  28829. forEach = forEach || (function (item) { return; });
  28830. for (var i in list) {
  28831. var item = list[i];
  28832. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28833. listByTags.push(item);
  28834. forEach(item);
  28835. }
  28836. }
  28837. return listByTags;
  28838. };
  28839. /**
  28840. * Get a list of meshes by tags
  28841. * @param tagsQuery defines the tags query to use
  28842. * @param forEach defines a predicate used to filter results
  28843. * @returns an array of Mesh
  28844. */
  28845. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28846. return this._getByTags(this.meshes, tagsQuery, forEach);
  28847. };
  28848. /**
  28849. * Get a list of cameras by tags
  28850. * @param tagsQuery defines the tags query to use
  28851. * @param forEach defines a predicate used to filter results
  28852. * @returns an array of Camera
  28853. */
  28854. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28855. return this._getByTags(this.cameras, tagsQuery, forEach);
  28856. };
  28857. /**
  28858. * Get a list of lights by tags
  28859. * @param tagsQuery defines the tags query to use
  28860. * @param forEach defines a predicate used to filter results
  28861. * @returns an array of Light
  28862. */
  28863. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28864. return this._getByTags(this.lights, tagsQuery, forEach);
  28865. };
  28866. /**
  28867. * Get a list of materials by tags
  28868. * @param tagsQuery defines the tags query to use
  28869. * @param forEach defines a predicate used to filter results
  28870. * @returns an array of Material
  28871. */
  28872. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28873. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28874. };
  28875. /**
  28876. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28877. * This allowed control for front to back rendering or reversly depending of the special needs.
  28878. *
  28879. * @param renderingGroupId The rendering group id corresponding to its index
  28880. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28881. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28882. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28883. */
  28884. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28885. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28886. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28887. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28888. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28889. };
  28890. /**
  28891. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28892. *
  28893. * @param renderingGroupId The rendering group id corresponding to its index
  28894. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28895. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28896. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28897. */
  28898. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28899. if (depth === void 0) { depth = true; }
  28900. if (stencil === void 0) { stencil = true; }
  28901. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28902. };
  28903. /**
  28904. * Will flag all materials as dirty to trigger new shader compilation
  28905. * @param flag defines the flag used to specify which material part must be marked as dirty
  28906. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28907. */
  28908. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28909. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28910. var material = _a[_i];
  28911. if (predicate && !predicate(material)) {
  28912. continue;
  28913. }
  28914. material.markAsDirty(flag);
  28915. }
  28916. };
  28917. /** @hidden */
  28918. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28919. var _this = this;
  28920. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28921. this._activeRequests.push(request);
  28922. request.onCompleteObservable.add(function (request) {
  28923. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28924. });
  28925. return request;
  28926. };
  28927. /** @hidden */
  28928. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28929. var _this = this;
  28930. return new Promise(function (resolve, reject) {
  28931. _this._loadFile(url, function (data) {
  28932. resolve(data);
  28933. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28934. reject(exception);
  28935. });
  28936. });
  28937. };
  28938. // Statics
  28939. Scene._FOGMODE_NONE = 0;
  28940. Scene._FOGMODE_EXP = 1;
  28941. Scene._FOGMODE_EXP2 = 2;
  28942. Scene._FOGMODE_LINEAR = 3;
  28943. Scene._uniqueIdCounter = 0;
  28944. /**
  28945. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28946. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28947. */
  28948. Scene.MinDeltaTime = 1.0;
  28949. /**
  28950. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28951. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28952. */
  28953. Scene.MaxDeltaTime = 1000.0;
  28954. /** The distance in pixel that you have to move to prevent some events */
  28955. Scene.DragMovementThreshold = 10; // in pixels
  28956. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28957. Scene.LongPressDelay = 500; // in milliseconds
  28958. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28959. Scene.DoubleClickDelay = 300; // in milliseconds
  28960. /** If you need to check double click without raising a single click at first click, enable this flag */
  28961. Scene.ExclusiveDoubleClickMode = false;
  28962. return Scene;
  28963. }());
  28964. BABYLON.Scene = Scene;
  28965. })(BABYLON || (BABYLON = {}));
  28966. //# sourceMappingURL=babylon.scene.js.map
  28967. var BABYLON;
  28968. (function (BABYLON) {
  28969. /**
  28970. * Set of assets to keep when moving a scene into an asset container.
  28971. */
  28972. var KeepAssets = /** @class */ (function () {
  28973. function KeepAssets() {
  28974. /**
  28975. * Cameras to keep.
  28976. */
  28977. this.cameras = new Array();
  28978. /**
  28979. * Lights to keep.
  28980. */
  28981. this.lights = new Array();
  28982. /**
  28983. * Meshes to keep.
  28984. */
  28985. this.meshes = new Array();
  28986. /**
  28987. * Skeletons to keep.
  28988. */
  28989. this.skeletons = new Array();
  28990. /**
  28991. * ParticleSystems to keep.
  28992. */
  28993. this.particleSystems = new Array();
  28994. /**
  28995. * Animations to keep.
  28996. */
  28997. this.animations = new Array();
  28998. /**
  28999. * AnimationGroups to keep.
  29000. */
  29001. this.animationGroups = new Array();
  29002. /**
  29003. * MultiMaterials to keep.
  29004. */
  29005. this.multiMaterials = new Array();
  29006. /**
  29007. * Materials to keep.
  29008. */
  29009. this.materials = new Array();
  29010. /**
  29011. * MorphTargetManagers to keep.
  29012. */
  29013. this.morphTargetManagers = new Array();
  29014. /**
  29015. * Geometries to keep.
  29016. */
  29017. this.geometries = new Array();
  29018. /**
  29019. * TransformNodes to keep.
  29020. */
  29021. this.transformNodes = new Array();
  29022. /**
  29023. * LensFlareSystems to keep.
  29024. */
  29025. this.lensFlareSystems = new Array();
  29026. /**
  29027. * ShadowGenerators to keep.
  29028. */
  29029. this.shadowGenerators = new Array();
  29030. /**
  29031. * ActionManagers to keep.
  29032. */
  29033. this.actionManagers = new Array();
  29034. /**
  29035. * Sounds to keep.
  29036. */
  29037. this.sounds = new Array();
  29038. /**
  29039. * Textures to keep.
  29040. */
  29041. this.textures = new Array();
  29042. /**
  29043. * Effect layers to keep.
  29044. */
  29045. this.effectLayers = new Array();
  29046. }
  29047. return KeepAssets;
  29048. }());
  29049. BABYLON.KeepAssets = KeepAssets;
  29050. /**
  29051. * Container with a set of assets that can be added or removed from a scene.
  29052. */
  29053. var AssetContainer = /** @class */ (function () {
  29054. /**
  29055. * Instantiates an AssetContainer.
  29056. * @param scene The scene the AssetContainer belongs to.
  29057. */
  29058. function AssetContainer(scene) {
  29059. // Objects
  29060. /**
  29061. * Cameras populated in the container.
  29062. */
  29063. this.cameras = new Array();
  29064. /**
  29065. * Lights populated in the container.
  29066. */
  29067. this.lights = new Array();
  29068. /**
  29069. * Meshes populated in the container.
  29070. */
  29071. this.meshes = new Array();
  29072. /**
  29073. * Skeletons populated in the container.
  29074. */
  29075. this.skeletons = new Array();
  29076. /**
  29077. * ParticleSystems populated in the container.
  29078. */
  29079. this.particleSystems = new Array();
  29080. /**
  29081. * Animations populated in the container.
  29082. */
  29083. this.animations = new Array();
  29084. /**
  29085. * AnimationGroups populated in the container.
  29086. */
  29087. this.animationGroups = new Array();
  29088. /**
  29089. * MultiMaterials populated in the container.
  29090. */
  29091. this.multiMaterials = new Array();
  29092. /**
  29093. * Materials populated in the container.
  29094. */
  29095. this.materials = new Array();
  29096. /**
  29097. * MorphTargetManagers populated in the container.
  29098. */
  29099. this.morphTargetManagers = new Array();
  29100. /**
  29101. * Geometries populated in the container.
  29102. */
  29103. this.geometries = new Array();
  29104. /**
  29105. * TransformNodes populated in the container.
  29106. */
  29107. this.transformNodes = new Array();
  29108. /**
  29109. * LensFlareSystems populated in the container.
  29110. */
  29111. this.lensFlareSystems = new Array();
  29112. /**
  29113. * ShadowGenerators populated in the container.
  29114. */
  29115. this.shadowGenerators = new Array();
  29116. /**
  29117. * ActionManagers populated in the container.
  29118. */
  29119. this.actionManagers = new Array();
  29120. /**
  29121. * Sounds populated in the container.
  29122. */
  29123. this.sounds = new Array();
  29124. /**
  29125. * Textures populated in the container.
  29126. */
  29127. this.textures = new Array();
  29128. /**
  29129. * Effect layers populated in the container.
  29130. */
  29131. this.effectLayers = new Array();
  29132. this.scene = scene;
  29133. }
  29134. /**
  29135. * Adds all the assets from the container to the scene.
  29136. */
  29137. AssetContainer.prototype.addAllToScene = function () {
  29138. var _this = this;
  29139. this.cameras.forEach(function (o) {
  29140. _this.scene.addCamera(o);
  29141. });
  29142. this.lights.forEach(function (o) {
  29143. _this.scene.addLight(o);
  29144. });
  29145. this.meshes.forEach(function (o) {
  29146. _this.scene.addMesh(o);
  29147. });
  29148. this.skeletons.forEach(function (o) {
  29149. _this.scene.addSkeleton(o);
  29150. });
  29151. this.particleSystems.forEach(function (o) {
  29152. _this.scene.addParticleSystem(o);
  29153. });
  29154. this.animations.forEach(function (o) {
  29155. _this.scene.addAnimation(o);
  29156. });
  29157. this.animationGroups.forEach(function (o) {
  29158. _this.scene.addAnimationGroup(o);
  29159. });
  29160. this.multiMaterials.forEach(function (o) {
  29161. _this.scene.addMultiMaterial(o);
  29162. });
  29163. this.materials.forEach(function (o) {
  29164. _this.scene.addMaterial(o);
  29165. });
  29166. this.morphTargetManagers.forEach(function (o) {
  29167. _this.scene.addMorphTargetManager(o);
  29168. });
  29169. this.geometries.forEach(function (o) {
  29170. _this.scene.addGeometry(o);
  29171. });
  29172. this.transformNodes.forEach(function (o) {
  29173. _this.scene.addTransformNode(o);
  29174. });
  29175. this.lensFlareSystems.forEach(function (o) {
  29176. _this.scene.addLensFlareSystem(o);
  29177. });
  29178. this.actionManagers.forEach(function (o) {
  29179. _this.scene.addActionManager(o);
  29180. });
  29181. this.sounds.forEach(function (o) {
  29182. o.play();
  29183. o.autoplay = true;
  29184. _this.scene.mainSoundTrack.AddSound(o);
  29185. });
  29186. this.textures.forEach(function (o) {
  29187. _this.scene.addTexture(o);
  29188. });
  29189. this.effectLayers.forEach(function (o) {
  29190. _this.scene.addEffectLayer(o);
  29191. });
  29192. };
  29193. /**
  29194. * Removes all the assets in the container from the scene
  29195. */
  29196. AssetContainer.prototype.removeAllFromScene = function () {
  29197. var _this = this;
  29198. this.cameras.forEach(function (o) {
  29199. _this.scene.removeCamera(o);
  29200. });
  29201. this.lights.forEach(function (o) {
  29202. _this.scene.removeLight(o);
  29203. });
  29204. this.meshes.forEach(function (o) {
  29205. _this.scene.removeMesh(o);
  29206. });
  29207. this.skeletons.forEach(function (o) {
  29208. _this.scene.removeSkeleton(o);
  29209. });
  29210. this.particleSystems.forEach(function (o) {
  29211. _this.scene.removeParticleSystem(o);
  29212. });
  29213. this.animations.forEach(function (o) {
  29214. _this.scene.removeAnimation(o);
  29215. });
  29216. this.animationGroups.forEach(function (o) {
  29217. _this.scene.removeAnimationGroup(o);
  29218. });
  29219. this.multiMaterials.forEach(function (o) {
  29220. _this.scene.removeMultiMaterial(o);
  29221. });
  29222. this.materials.forEach(function (o) {
  29223. _this.scene.removeMaterial(o);
  29224. });
  29225. this.morphTargetManagers.forEach(function (o) {
  29226. _this.scene.removeMorphTargetManager(o);
  29227. });
  29228. this.geometries.forEach(function (o) {
  29229. _this.scene.removeGeometry(o);
  29230. });
  29231. this.transformNodes.forEach(function (o) {
  29232. _this.scene.removeTransformNode(o);
  29233. });
  29234. this.lensFlareSystems.forEach(function (o) {
  29235. _this.scene.removeLensFlareSystem(o);
  29236. });
  29237. this.actionManagers.forEach(function (o) {
  29238. _this.scene.removeActionManager(o);
  29239. });
  29240. this.sounds.forEach(function (o) {
  29241. o.stop();
  29242. o.autoplay = false;
  29243. _this.scene.mainSoundTrack.RemoveSound(o);
  29244. });
  29245. this.textures.forEach(function (o) {
  29246. _this.scene.removeTexture(o);
  29247. });
  29248. this.effectLayers.forEach(function (o) {
  29249. _this.scene.removeEffectLayer(o);
  29250. });
  29251. };
  29252. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29253. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29254. var asset = sourceAssets_1[_i];
  29255. var move = true;
  29256. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29257. var keepAsset = keepAssets_1[_a];
  29258. if (asset === keepAsset) {
  29259. move = false;
  29260. break;
  29261. }
  29262. }
  29263. if (move) {
  29264. targetAssets.push(asset);
  29265. }
  29266. }
  29267. };
  29268. /**
  29269. * Removes all the assets contained in the scene and adds them to the container.
  29270. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29271. */
  29272. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29273. if (keepAssets === undefined) {
  29274. keepAssets = new KeepAssets();
  29275. }
  29276. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29277. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29278. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29279. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29280. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29281. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29282. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29283. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29284. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29285. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29286. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29287. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29288. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29289. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29290. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29291. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29292. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29293. this.removeAllFromScene();
  29294. };
  29295. return AssetContainer;
  29296. }());
  29297. BABYLON.AssetContainer = AssetContainer;
  29298. })(BABYLON || (BABYLON = {}));
  29299. //# sourceMappingURL=babylon.assetContainer.js.map
  29300. var BABYLON;
  29301. (function (BABYLON) {
  29302. var Buffer = /** @class */ (function () {
  29303. /**
  29304. * Constructor
  29305. * @param engine the engine
  29306. * @param data the data to use for this buffer
  29307. * @param updatable whether the data is updatable
  29308. * @param stride the stride (optional)
  29309. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29310. * @param instanced whether the buffer is instanced (optional)
  29311. * @param useBytes set to true if the stride in in bytes (optional)
  29312. */
  29313. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29314. if (stride === void 0) { stride = 0; }
  29315. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29316. if (instanced === void 0) { instanced = false; }
  29317. if (useBytes === void 0) { useBytes = false; }
  29318. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29319. this._engine = engine.getScene().getEngine();
  29320. }
  29321. else {
  29322. this._engine = engine;
  29323. }
  29324. this._updatable = updatable;
  29325. this._instanced = instanced;
  29326. this._data = data;
  29327. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29328. if (!postponeInternalCreation) { // by default
  29329. this.create();
  29330. }
  29331. }
  29332. /**
  29333. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29334. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29335. * @param offset defines offset in the buffer (0 by default)
  29336. * @param size defines the size in floats of attributes (position is 3 for instance)
  29337. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29338. * @param instanced defines if the vertex buffer contains indexed data
  29339. * @param useBytes defines if the offset and stride are in bytes
  29340. * @returns the new vertex buffer
  29341. */
  29342. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29343. if (useBytes === void 0) { useBytes = false; }
  29344. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29345. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29346. // a lot of these parameters are ignored as they are overriden by the buffer
  29347. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29348. };
  29349. // Properties
  29350. Buffer.prototype.isUpdatable = function () {
  29351. return this._updatable;
  29352. };
  29353. Buffer.prototype.getData = function () {
  29354. return this._data;
  29355. };
  29356. Buffer.prototype.getBuffer = function () {
  29357. return this._buffer;
  29358. };
  29359. /**
  29360. * Gets the stride in float32 units (i.e. byte stride / 4).
  29361. * May not be an integer if the byte stride is not divisible by 4.
  29362. * DEPRECATED. Use byteStride instead.
  29363. * @returns the stride in float32 units
  29364. */
  29365. Buffer.prototype.getStrideSize = function () {
  29366. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29367. };
  29368. // Methods
  29369. Buffer.prototype.create = function (data) {
  29370. if (data === void 0) { data = null; }
  29371. if (!data && this._buffer) {
  29372. return; // nothing to do
  29373. }
  29374. data = data || this._data;
  29375. if (!data) {
  29376. return;
  29377. }
  29378. if (!this._buffer) { // create buffer
  29379. if (this._updatable) {
  29380. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29381. this._data = data;
  29382. }
  29383. else {
  29384. this._buffer = this._engine.createVertexBuffer(data);
  29385. }
  29386. }
  29387. else if (this._updatable) { // update buffer
  29388. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29389. this._data = data;
  29390. }
  29391. };
  29392. Buffer.prototype._rebuild = function () {
  29393. this._buffer = null;
  29394. this.create(this._data);
  29395. };
  29396. Buffer.prototype.update = function (data) {
  29397. this.create(data);
  29398. };
  29399. /**
  29400. * Updates the data directly.
  29401. * @param data the new data
  29402. * @param offset the new offset
  29403. * @param vertexCount the vertex count (optional)
  29404. * @param useBytes set to true if the offset is in bytes
  29405. */
  29406. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29407. if (useBytes === void 0) { useBytes = false; }
  29408. if (!this._buffer) {
  29409. return;
  29410. }
  29411. if (this._updatable) { // update buffer
  29412. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29413. this._data = null;
  29414. }
  29415. };
  29416. Buffer.prototype.dispose = function () {
  29417. if (!this._buffer) {
  29418. return;
  29419. }
  29420. if (this._engine._releaseBuffer(this._buffer)) {
  29421. this._buffer = null;
  29422. }
  29423. };
  29424. return Buffer;
  29425. }());
  29426. BABYLON.Buffer = Buffer;
  29427. })(BABYLON || (BABYLON = {}));
  29428. //# sourceMappingURL=babylon.buffer.js.map
  29429. var BABYLON;
  29430. (function (BABYLON) {
  29431. var VertexBuffer = /** @class */ (function () {
  29432. /**
  29433. * Constructor
  29434. * @param engine the engine
  29435. * @param data the data to use for this vertex buffer
  29436. * @param kind the vertex buffer kind
  29437. * @param updatable whether the data is updatable
  29438. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29439. * @param stride the stride (optional)
  29440. * @param instanced whether the buffer is instanced (optional)
  29441. * @param offset the offset of the data (optional)
  29442. * @param size the number of components (optional)
  29443. * @param type the type of the component (optional)
  29444. * @param normalized whether the data contains normalized data (optional)
  29445. * @param useBytes set to true if stride and offset are in bytes (optional)
  29446. */
  29447. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29448. if (normalized === void 0) { normalized = false; }
  29449. if (useBytes === void 0) { useBytes = false; }
  29450. if (data instanceof BABYLON.Buffer) {
  29451. this._buffer = data;
  29452. this._ownsBuffer = false;
  29453. }
  29454. else {
  29455. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29456. this._ownsBuffer = true;
  29457. }
  29458. this._kind = kind;
  29459. if (type == undefined) {
  29460. var data_1 = this.getData();
  29461. this.type = VertexBuffer.FLOAT;
  29462. if (data_1 instanceof Int8Array)
  29463. this.type = VertexBuffer.BYTE;
  29464. else if (data_1 instanceof Uint8Array)
  29465. this.type = VertexBuffer.UNSIGNED_BYTE;
  29466. else if (data_1 instanceof Int16Array)
  29467. this.type = VertexBuffer.SHORT;
  29468. else if (data_1 instanceof Uint16Array)
  29469. this.type = VertexBuffer.UNSIGNED_SHORT;
  29470. else if (data_1 instanceof Int32Array)
  29471. this.type = VertexBuffer.INT;
  29472. else if (data_1 instanceof Uint32Array)
  29473. this.type = VertexBuffer.UNSIGNED_INT;
  29474. }
  29475. else {
  29476. this.type = type;
  29477. }
  29478. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29479. if (useBytes) {
  29480. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29481. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29482. this.byteOffset = offset || 0;
  29483. }
  29484. else {
  29485. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29486. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29487. this.byteOffset = (offset || 0) * typeByteLength;
  29488. }
  29489. this.normalized = normalized;
  29490. this._instanced = instanced !== undefined ? instanced : false;
  29491. this._instanceDivisor = instanced ? 1 : 0;
  29492. }
  29493. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29494. /**
  29495. * Gets or sets the instance divisor when in instanced mode
  29496. */
  29497. get: function () {
  29498. return this._instanceDivisor;
  29499. },
  29500. set: function (value) {
  29501. this._instanceDivisor = value;
  29502. if (value == 0) {
  29503. this._instanced = false;
  29504. }
  29505. else {
  29506. this._instanced = true;
  29507. }
  29508. },
  29509. enumerable: true,
  29510. configurable: true
  29511. });
  29512. VertexBuffer.prototype._rebuild = function () {
  29513. if (!this._buffer) {
  29514. return;
  29515. }
  29516. this._buffer._rebuild();
  29517. };
  29518. /**
  29519. * Returns the kind of the VertexBuffer (string).
  29520. */
  29521. VertexBuffer.prototype.getKind = function () {
  29522. return this._kind;
  29523. };
  29524. // Properties
  29525. /**
  29526. * Boolean : is the VertexBuffer updatable ?
  29527. */
  29528. VertexBuffer.prototype.isUpdatable = function () {
  29529. return this._buffer.isUpdatable();
  29530. };
  29531. /**
  29532. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29533. */
  29534. VertexBuffer.prototype.getData = function () {
  29535. return this._buffer.getData();
  29536. };
  29537. /**
  29538. * Returns the WebGLBuffer associated to the VertexBuffer.
  29539. */
  29540. VertexBuffer.prototype.getBuffer = function () {
  29541. return this._buffer.getBuffer();
  29542. };
  29543. /**
  29544. * Returns the stride as a multiple of the type byte length.
  29545. * DEPRECATED. Use byteStride instead.
  29546. */
  29547. VertexBuffer.prototype.getStrideSize = function () {
  29548. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29549. };
  29550. /**
  29551. * Returns the offset as a multiple of the type byte length.
  29552. * DEPRECATED. Use byteOffset instead.
  29553. */
  29554. VertexBuffer.prototype.getOffset = function () {
  29555. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29556. };
  29557. /**
  29558. * Returns the number of components per vertex attribute (integer).
  29559. */
  29560. VertexBuffer.prototype.getSize = function () {
  29561. return this._size;
  29562. };
  29563. /**
  29564. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29565. */
  29566. VertexBuffer.prototype.getIsInstanced = function () {
  29567. return this._instanced;
  29568. };
  29569. /**
  29570. * Returns the instancing divisor, zero for non-instanced (integer).
  29571. */
  29572. VertexBuffer.prototype.getInstanceDivisor = function () {
  29573. return this._instanceDivisor;
  29574. };
  29575. // Methods
  29576. /**
  29577. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29578. * Returns the created WebGLBuffer.
  29579. */
  29580. VertexBuffer.prototype.create = function (data) {
  29581. return this._buffer.create(data);
  29582. };
  29583. /**
  29584. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29585. * This function will create a new buffer if the current one is not updatable
  29586. * Returns the updated WebGLBuffer.
  29587. */
  29588. VertexBuffer.prototype.update = function (data) {
  29589. return this._buffer.update(data);
  29590. };
  29591. /**
  29592. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29593. * Returns the directly updated WebGLBuffer.
  29594. * @param data the new data
  29595. * @param offset the new offset
  29596. * @param useBytes set to true if the offset is in bytes
  29597. */
  29598. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29599. if (useBytes === void 0) { useBytes = false; }
  29600. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29601. };
  29602. /**
  29603. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29604. */
  29605. VertexBuffer.prototype.dispose = function () {
  29606. if (this._ownsBuffer) {
  29607. this._buffer.dispose();
  29608. }
  29609. };
  29610. /**
  29611. * Enumerates each value of this vertex buffer as numbers.
  29612. * @param count the number of values to enumerate
  29613. * @param callback the callback function called for each value
  29614. */
  29615. VertexBuffer.prototype.forEach = function (count, callback) {
  29616. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29617. };
  29618. Object.defineProperty(VertexBuffer, "PositionKind", {
  29619. get: function () {
  29620. return VertexBuffer._PositionKind;
  29621. },
  29622. enumerable: true,
  29623. configurable: true
  29624. });
  29625. Object.defineProperty(VertexBuffer, "NormalKind", {
  29626. get: function () {
  29627. return VertexBuffer._NormalKind;
  29628. },
  29629. enumerable: true,
  29630. configurable: true
  29631. });
  29632. Object.defineProperty(VertexBuffer, "TangentKind", {
  29633. get: function () {
  29634. return VertexBuffer._TangentKind;
  29635. },
  29636. enumerable: true,
  29637. configurable: true
  29638. });
  29639. Object.defineProperty(VertexBuffer, "UVKind", {
  29640. get: function () {
  29641. return VertexBuffer._UVKind;
  29642. },
  29643. enumerable: true,
  29644. configurable: true
  29645. });
  29646. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29647. get: function () {
  29648. return VertexBuffer._UV2Kind;
  29649. },
  29650. enumerable: true,
  29651. configurable: true
  29652. });
  29653. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29654. get: function () {
  29655. return VertexBuffer._UV3Kind;
  29656. },
  29657. enumerable: true,
  29658. configurable: true
  29659. });
  29660. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29661. get: function () {
  29662. return VertexBuffer._UV4Kind;
  29663. },
  29664. enumerable: true,
  29665. configurable: true
  29666. });
  29667. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29668. get: function () {
  29669. return VertexBuffer._UV5Kind;
  29670. },
  29671. enumerable: true,
  29672. configurable: true
  29673. });
  29674. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29675. get: function () {
  29676. return VertexBuffer._UV6Kind;
  29677. },
  29678. enumerable: true,
  29679. configurable: true
  29680. });
  29681. Object.defineProperty(VertexBuffer, "ColorKind", {
  29682. get: function () {
  29683. return VertexBuffer._ColorKind;
  29684. },
  29685. enumerable: true,
  29686. configurable: true
  29687. });
  29688. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29689. get: function () {
  29690. return VertexBuffer._MatricesIndicesKind;
  29691. },
  29692. enumerable: true,
  29693. configurable: true
  29694. });
  29695. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29696. get: function () {
  29697. return VertexBuffer._MatricesWeightsKind;
  29698. },
  29699. enumerable: true,
  29700. configurable: true
  29701. });
  29702. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29703. get: function () {
  29704. return VertexBuffer._MatricesIndicesExtraKind;
  29705. },
  29706. enumerable: true,
  29707. configurable: true
  29708. });
  29709. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29710. get: function () {
  29711. return VertexBuffer._MatricesWeightsExtraKind;
  29712. },
  29713. enumerable: true,
  29714. configurable: true
  29715. });
  29716. /**
  29717. * Deduces the stride given a kind.
  29718. * @param kind The kind string to deduce
  29719. * @returns The deduced stride
  29720. */
  29721. VertexBuffer.DeduceStride = function (kind) {
  29722. switch (kind) {
  29723. case VertexBuffer.UVKind:
  29724. case VertexBuffer.UV2Kind:
  29725. case VertexBuffer.UV3Kind:
  29726. case VertexBuffer.UV4Kind:
  29727. case VertexBuffer.UV5Kind:
  29728. case VertexBuffer.UV6Kind:
  29729. return 2;
  29730. case VertexBuffer.NormalKind:
  29731. case VertexBuffer.PositionKind:
  29732. return 3;
  29733. case VertexBuffer.ColorKind:
  29734. case VertexBuffer.MatricesIndicesKind:
  29735. case VertexBuffer.MatricesIndicesExtraKind:
  29736. case VertexBuffer.MatricesWeightsKind:
  29737. case VertexBuffer.MatricesWeightsExtraKind:
  29738. case VertexBuffer.TangentKind:
  29739. return 4;
  29740. default:
  29741. throw new Error("Invalid kind '" + kind + "'");
  29742. }
  29743. };
  29744. /**
  29745. * Gets the byte length of the given type.
  29746. * @param type the type
  29747. * @returns the number of bytes
  29748. */
  29749. VertexBuffer.GetTypeByteLength = function (type) {
  29750. switch (type) {
  29751. case VertexBuffer.BYTE:
  29752. case VertexBuffer.UNSIGNED_BYTE:
  29753. return 1;
  29754. case VertexBuffer.SHORT:
  29755. case VertexBuffer.UNSIGNED_SHORT:
  29756. return 2;
  29757. case VertexBuffer.INT:
  29758. case VertexBuffer.FLOAT:
  29759. return 4;
  29760. default:
  29761. throw new Error("Invalid type '" + type + "'");
  29762. }
  29763. };
  29764. /**
  29765. * Enumerates each value of the given parameters as numbers.
  29766. * @param data the data to enumerate
  29767. * @param byteOffset the byte offset of the data
  29768. * @param byteStride the byte stride of the data
  29769. * @param componentCount the number of components per element
  29770. * @param componentType the type of the component
  29771. * @param count the total number of components
  29772. * @param normalized whether the data is normalized
  29773. * @param callback the callback function called for each value
  29774. */
  29775. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29776. if (data instanceof Array) {
  29777. var offset = byteOffset / 4;
  29778. var stride = byteStride / 4;
  29779. for (var index = 0; index < count; index += componentCount) {
  29780. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29781. callback(data[offset + componentIndex], index + componentIndex);
  29782. }
  29783. offset += stride;
  29784. }
  29785. }
  29786. else {
  29787. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29788. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29789. for (var index = 0; index < count; index += componentCount) {
  29790. var componentByteOffset = byteOffset;
  29791. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29792. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29793. callback(value, index + componentIndex);
  29794. componentByteOffset += componentByteLength;
  29795. }
  29796. byteOffset += byteStride;
  29797. }
  29798. }
  29799. };
  29800. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29801. switch (type) {
  29802. case VertexBuffer.BYTE: {
  29803. var value = dataView.getInt8(byteOffset);
  29804. if (normalized) {
  29805. value = Math.max(value / 127, -1);
  29806. }
  29807. return value;
  29808. }
  29809. case VertexBuffer.UNSIGNED_BYTE: {
  29810. var value = dataView.getUint8(byteOffset);
  29811. if (normalized) {
  29812. value = value / 255;
  29813. }
  29814. return value;
  29815. }
  29816. case VertexBuffer.SHORT: {
  29817. var value = dataView.getInt16(byteOffset, true);
  29818. if (normalized) {
  29819. value = Math.max(value / 16383, -1);
  29820. }
  29821. return value;
  29822. }
  29823. case VertexBuffer.UNSIGNED_SHORT: {
  29824. var value = dataView.getUint16(byteOffset, true);
  29825. if (normalized) {
  29826. value = value / 65535;
  29827. }
  29828. return value;
  29829. }
  29830. case VertexBuffer.FLOAT: {
  29831. return dataView.getFloat32(byteOffset, true);
  29832. }
  29833. default: {
  29834. throw new Error("Invalid component type " + type);
  29835. }
  29836. }
  29837. };
  29838. /**
  29839. * The byte type.
  29840. */
  29841. VertexBuffer.BYTE = 5120;
  29842. /**
  29843. * The unsigned byte type.
  29844. */
  29845. VertexBuffer.UNSIGNED_BYTE = 5121;
  29846. /**
  29847. * The short type.
  29848. */
  29849. VertexBuffer.SHORT = 5122;
  29850. /**
  29851. * The unsigned short type.
  29852. */
  29853. VertexBuffer.UNSIGNED_SHORT = 5123;
  29854. /**
  29855. * The integer type.
  29856. */
  29857. VertexBuffer.INT = 5124;
  29858. /**
  29859. * The unsigned integer type.
  29860. */
  29861. VertexBuffer.UNSIGNED_INT = 5125;
  29862. /**
  29863. * The float type.
  29864. */
  29865. VertexBuffer.FLOAT = 5126;
  29866. // Enums
  29867. VertexBuffer._PositionKind = "position";
  29868. VertexBuffer._NormalKind = "normal";
  29869. VertexBuffer._TangentKind = "tangent";
  29870. VertexBuffer._UVKind = "uv";
  29871. VertexBuffer._UV2Kind = "uv2";
  29872. VertexBuffer._UV3Kind = "uv3";
  29873. VertexBuffer._UV4Kind = "uv4";
  29874. VertexBuffer._UV5Kind = "uv5";
  29875. VertexBuffer._UV6Kind = "uv6";
  29876. VertexBuffer._ColorKind = "color";
  29877. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29878. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29879. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29880. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29881. return VertexBuffer;
  29882. }());
  29883. BABYLON.VertexBuffer = VertexBuffer;
  29884. })(BABYLON || (BABYLON = {}));
  29885. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29886. var BABYLON;
  29887. (function (BABYLON) {
  29888. /**
  29889. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29890. */
  29891. var DummyInternalTextureTracker = /** @class */ (function () {
  29892. function DummyInternalTextureTracker() {
  29893. /**
  29894. * Gets or set the previous tracker in the list
  29895. */
  29896. this.previous = null;
  29897. /**
  29898. * Gets or set the next tracker in the list
  29899. */
  29900. this.next = null;
  29901. }
  29902. return DummyInternalTextureTracker;
  29903. }());
  29904. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29905. })(BABYLON || (BABYLON = {}));
  29906. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29907. var BABYLON;
  29908. (function (BABYLON) {
  29909. /**
  29910. * Class used to store data associated with WebGL texture data for the engine
  29911. * This class should not be used directly
  29912. */
  29913. var InternalTexture = /** @class */ (function () {
  29914. /**
  29915. * Creates a new InternalTexture
  29916. * @param engine defines the engine to use
  29917. * @param dataSource defines the type of data that will be used
  29918. */
  29919. function InternalTexture(engine, dataSource) {
  29920. /**
  29921. * Observable called when the texture is loaded
  29922. */
  29923. this.onLoadedObservable = new BABYLON.Observable();
  29924. /**
  29925. * Gets or set the previous tracker in the list
  29926. */
  29927. this.previous = null;
  29928. /**
  29929. * Gets or set the next tracker in the list
  29930. */
  29931. this.next = null;
  29932. // Private
  29933. /** @hidden */
  29934. this._initialSlot = -1;
  29935. /** @hidden */
  29936. this._designatedSlot = -1;
  29937. /** @hidden */
  29938. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29939. /** @hidden */
  29940. this._comparisonFunction = 0;
  29941. /** @hidden */
  29942. this._references = 1;
  29943. this._engine = engine;
  29944. this._dataSource = dataSource;
  29945. this._webGLTexture = engine._createTexture();
  29946. }
  29947. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29948. /**
  29949. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29950. */
  29951. get: function () {
  29952. return this._dataSource;
  29953. },
  29954. enumerable: true,
  29955. configurable: true
  29956. });
  29957. /**
  29958. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29959. */
  29960. InternalTexture.prototype.incrementReferences = function () {
  29961. this._references++;
  29962. };
  29963. /**
  29964. * Change the size of the texture (not the size of the content)
  29965. * @param width defines the new width
  29966. * @param height defines the new height
  29967. * @param depth defines the new depth (1 by default)
  29968. */
  29969. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29970. if (depth === void 0) { depth = 1; }
  29971. this.width = width;
  29972. this.height = height;
  29973. this.depth = depth;
  29974. this.baseWidth = width;
  29975. this.baseHeight = height;
  29976. this.baseDepth = depth;
  29977. this._size = width * height * depth;
  29978. };
  29979. /** @hidden */
  29980. InternalTexture.prototype._rebuild = function () {
  29981. var _this = this;
  29982. var proxy;
  29983. this.isReady = false;
  29984. this._cachedCoordinatesMode = null;
  29985. this._cachedWrapU = null;
  29986. this._cachedWrapV = null;
  29987. this._cachedAnisotropicFilteringLevel = null;
  29988. switch (this._dataSource) {
  29989. case InternalTexture.DATASOURCE_TEMP:
  29990. return;
  29991. case InternalTexture.DATASOURCE_URL:
  29992. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29993. _this.isReady = true;
  29994. }, null, this._buffer, undefined, this.format);
  29995. proxy._swapAndDie(this);
  29996. return;
  29997. case InternalTexture.DATASOURCE_RAW:
  29998. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29999. proxy._swapAndDie(this);
  30000. this.isReady = true;
  30001. return;
  30002. case InternalTexture.DATASOURCE_RAW3D:
  30003. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30004. proxy._swapAndDie(this);
  30005. this.isReady = true;
  30006. return;
  30007. case InternalTexture.DATASOURCE_DYNAMIC:
  30008. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30009. proxy._swapAndDie(this);
  30010. // The engine will make sure to update content so no need to flag it as isReady = true
  30011. return;
  30012. case InternalTexture.DATASOURCE_RENDERTARGET:
  30013. var options = new BABYLON.RenderTargetCreationOptions();
  30014. options.generateDepthBuffer = this._generateDepthBuffer;
  30015. options.generateMipMaps = this.generateMipMaps;
  30016. options.generateStencilBuffer = this._generateStencilBuffer;
  30017. options.samplingMode = this.samplingMode;
  30018. options.type = this.type;
  30019. if (this.isCube) {
  30020. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30021. }
  30022. else {
  30023. var size = {
  30024. width: this.width,
  30025. height: this.height
  30026. };
  30027. proxy = this._engine.createRenderTargetTexture(size, options);
  30028. }
  30029. proxy._swapAndDie(this);
  30030. this.isReady = true;
  30031. return;
  30032. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30033. var depthTextureOptions = {
  30034. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30035. comparisonFunction: this._comparisonFunction,
  30036. generateStencil: this._generateStencilBuffer,
  30037. isCube: this.isCube
  30038. };
  30039. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30040. proxy._swapAndDie(this);
  30041. this.isReady = true;
  30042. return;
  30043. case InternalTexture.DATASOURCE_CUBE:
  30044. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30045. _this.isReady = true;
  30046. }, null, this.format, this._extension);
  30047. proxy._swapAndDie(this);
  30048. return;
  30049. case InternalTexture.DATASOURCE_CUBERAW:
  30050. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30051. proxy._swapAndDie(this);
  30052. this.isReady = true;
  30053. return;
  30054. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30055. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30056. if (proxy) {
  30057. proxy._swapAndDie(_this);
  30058. }
  30059. _this.isReady = true;
  30060. }, null, this.format, this._extension);
  30061. return;
  30062. }
  30063. };
  30064. InternalTexture.prototype._swapAndDie = function (target) {
  30065. target._webGLTexture = this._webGLTexture;
  30066. if (this._framebuffer) {
  30067. target._framebuffer = this._framebuffer;
  30068. }
  30069. if (this._depthStencilBuffer) {
  30070. target._depthStencilBuffer = this._depthStencilBuffer;
  30071. }
  30072. if (this._lodTextureHigh) {
  30073. if (target._lodTextureHigh) {
  30074. target._lodTextureHigh.dispose();
  30075. }
  30076. target._lodTextureHigh = this._lodTextureHigh;
  30077. }
  30078. if (this._lodTextureMid) {
  30079. if (target._lodTextureMid) {
  30080. target._lodTextureMid.dispose();
  30081. }
  30082. target._lodTextureMid = this._lodTextureMid;
  30083. }
  30084. if (this._lodTextureLow) {
  30085. if (target._lodTextureLow) {
  30086. target._lodTextureLow.dispose();
  30087. }
  30088. target._lodTextureLow = this._lodTextureLow;
  30089. }
  30090. var cache = this._engine.getLoadedTexturesCache();
  30091. var index = cache.indexOf(this);
  30092. if (index !== -1) {
  30093. cache.splice(index, 1);
  30094. }
  30095. };
  30096. /**
  30097. * Dispose the current allocated resources
  30098. */
  30099. InternalTexture.prototype.dispose = function () {
  30100. if (!this._webGLTexture) {
  30101. return;
  30102. }
  30103. this._references--;
  30104. if (this._references === 0) {
  30105. this._engine._releaseTexture(this);
  30106. this._webGLTexture = null;
  30107. this.previous = null;
  30108. this.next = null;
  30109. }
  30110. };
  30111. /**
  30112. * The source of the texture data is unknown
  30113. */
  30114. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30115. /**
  30116. * Texture data comes from an URL
  30117. */
  30118. InternalTexture.DATASOURCE_URL = 1;
  30119. /**
  30120. * Texture data is only used for temporary storage
  30121. */
  30122. InternalTexture.DATASOURCE_TEMP = 2;
  30123. /**
  30124. * Texture data comes from raw data (ArrayBuffer)
  30125. */
  30126. InternalTexture.DATASOURCE_RAW = 3;
  30127. /**
  30128. * Texture content is dynamic (video or dynamic texture)
  30129. */
  30130. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30131. /**
  30132. * Texture content is generated by rendering to it
  30133. */
  30134. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30135. /**
  30136. * Texture content is part of a multi render target process
  30137. */
  30138. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30139. /**
  30140. * Texture data comes from a cube data file
  30141. */
  30142. InternalTexture.DATASOURCE_CUBE = 7;
  30143. /**
  30144. * Texture data comes from a raw cube data
  30145. */
  30146. InternalTexture.DATASOURCE_CUBERAW = 8;
  30147. /**
  30148. * Texture data come from a prefiltered cube data file
  30149. */
  30150. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30151. /**
  30152. * Texture content is raw 3D data
  30153. */
  30154. InternalTexture.DATASOURCE_RAW3D = 10;
  30155. /**
  30156. * Texture content is a depth texture
  30157. */
  30158. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30159. return InternalTexture;
  30160. }());
  30161. BABYLON.InternalTexture = InternalTexture;
  30162. })(BABYLON || (BABYLON = {}));
  30163. //# sourceMappingURL=babylon.internalTexture.js.map
  30164. var BABYLON;
  30165. (function (BABYLON) {
  30166. var BaseTexture = /** @class */ (function () {
  30167. function BaseTexture(scene) {
  30168. this._hasAlpha = false;
  30169. this.getAlphaFromRGB = false;
  30170. this.level = 1;
  30171. this.coordinatesIndex = 0;
  30172. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30173. /**
  30174. * | Value | Type | Description |
  30175. * | ----- | ------------------ | ----------- |
  30176. * | 0 | CLAMP_ADDRESSMODE | |
  30177. * | 1 | WRAP_ADDRESSMODE | |
  30178. * | 2 | MIRROR_ADDRESSMODE | |
  30179. */
  30180. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30181. /**
  30182. * | Value | Type | Description |
  30183. * | ----- | ------------------ | ----------- |
  30184. * | 0 | CLAMP_ADDRESSMODE | |
  30185. * | 1 | WRAP_ADDRESSMODE | |
  30186. * | 2 | MIRROR_ADDRESSMODE | |
  30187. */
  30188. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30189. /**
  30190. * | Value | Type | Description |
  30191. * | ----- | ------------------ | ----------- |
  30192. * | 0 | CLAMP_ADDRESSMODE | |
  30193. * | 1 | WRAP_ADDRESSMODE | |
  30194. * | 2 | MIRROR_ADDRESSMODE | |
  30195. */
  30196. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30197. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30198. this.isCube = false;
  30199. this.is3D = false;
  30200. this.gammaSpace = true;
  30201. this.invertZ = false;
  30202. this.lodLevelInAlpha = false;
  30203. this.lodGenerationOffset = 0.0;
  30204. this.lodGenerationScale = 0.8;
  30205. this.isRenderTarget = false;
  30206. this.animations = new Array();
  30207. /**
  30208. * An event triggered when the texture is disposed.
  30209. */
  30210. this.onDisposeObservable = new BABYLON.Observable();
  30211. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30212. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30213. if (this._scene) {
  30214. this._scene.textures.push(this);
  30215. }
  30216. this._uid = null;
  30217. }
  30218. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30219. get: function () {
  30220. return this._hasAlpha;
  30221. },
  30222. set: function (value) {
  30223. if (this._hasAlpha === value) {
  30224. return;
  30225. }
  30226. this._hasAlpha = value;
  30227. if (this._scene) {
  30228. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30229. }
  30230. },
  30231. enumerable: true,
  30232. configurable: true
  30233. });
  30234. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30235. get: function () {
  30236. return this._coordinatesMode;
  30237. },
  30238. /**
  30239. * How a texture is mapped.
  30240. *
  30241. * | Value | Type | Description |
  30242. * | ----- | ----------------------------------- | ----------- |
  30243. * | 0 | EXPLICIT_MODE | |
  30244. * | 1 | SPHERICAL_MODE | |
  30245. * | 2 | PLANAR_MODE | |
  30246. * | 3 | CUBIC_MODE | |
  30247. * | 4 | PROJECTION_MODE | |
  30248. * | 5 | SKYBOX_MODE | |
  30249. * | 6 | INVCUBIC_MODE | |
  30250. * | 7 | EQUIRECTANGULAR_MODE | |
  30251. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30252. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30253. */
  30254. set: function (value) {
  30255. if (this._coordinatesMode === value) {
  30256. return;
  30257. }
  30258. this._coordinatesMode = value;
  30259. if (this._scene) {
  30260. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30261. }
  30262. },
  30263. enumerable: true,
  30264. configurable: true
  30265. });
  30266. Object.defineProperty(BaseTexture.prototype, "uid", {
  30267. get: function () {
  30268. if (!this._uid) {
  30269. this._uid = BABYLON.Tools.RandomId();
  30270. }
  30271. return this._uid;
  30272. },
  30273. enumerable: true,
  30274. configurable: true
  30275. });
  30276. BaseTexture.prototype.toString = function () {
  30277. return this.name;
  30278. };
  30279. BaseTexture.prototype.getClassName = function () {
  30280. return "BaseTexture";
  30281. };
  30282. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30283. set: function (callback) {
  30284. if (this._onDisposeObserver) {
  30285. this.onDisposeObservable.remove(this._onDisposeObserver);
  30286. }
  30287. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30288. },
  30289. enumerable: true,
  30290. configurable: true
  30291. });
  30292. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30293. get: function () {
  30294. return true;
  30295. },
  30296. enumerable: true,
  30297. configurable: true
  30298. });
  30299. BaseTexture.prototype.getScene = function () {
  30300. return this._scene;
  30301. };
  30302. BaseTexture.prototype.getTextureMatrix = function () {
  30303. return BABYLON.Matrix.IdentityReadOnly;
  30304. };
  30305. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30306. return BABYLON.Matrix.IdentityReadOnly;
  30307. };
  30308. BaseTexture.prototype.getInternalTexture = function () {
  30309. return this._texture;
  30310. };
  30311. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30312. return !this.isBlocking || this.isReady();
  30313. };
  30314. BaseTexture.prototype.isReady = function () {
  30315. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30316. this.delayLoad();
  30317. return false;
  30318. }
  30319. if (this._texture) {
  30320. return this._texture.isReady;
  30321. }
  30322. return false;
  30323. };
  30324. BaseTexture.prototype.getSize = function () {
  30325. if (this._texture && this._texture.width) {
  30326. return new BABYLON.Size(this._texture.width, this._texture.height);
  30327. }
  30328. if (this._texture && this._texture._size) {
  30329. return new BABYLON.Size(this._texture._size, this._texture._size);
  30330. }
  30331. return BABYLON.Size.Zero();
  30332. };
  30333. BaseTexture.prototype.getBaseSize = function () {
  30334. if (!this.isReady() || !this._texture)
  30335. return BABYLON.Size.Zero();
  30336. if (this._texture._size) {
  30337. return new BABYLON.Size(this._texture._size, this._texture._size);
  30338. }
  30339. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30340. };
  30341. BaseTexture.prototype.scale = function (ratio) {
  30342. };
  30343. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30344. get: function () {
  30345. return false;
  30346. },
  30347. enumerable: true,
  30348. configurable: true
  30349. });
  30350. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30351. if (!this._scene) {
  30352. return null;
  30353. }
  30354. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30355. for (var index = 0; index < texturesCache.length; index++) {
  30356. var texturesCacheEntry = texturesCache[index];
  30357. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30358. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30359. texturesCacheEntry.incrementReferences();
  30360. return texturesCacheEntry;
  30361. }
  30362. }
  30363. }
  30364. return null;
  30365. };
  30366. BaseTexture.prototype._rebuild = function () {
  30367. };
  30368. BaseTexture.prototype.delayLoad = function () {
  30369. };
  30370. BaseTexture.prototype.clone = function () {
  30371. return null;
  30372. };
  30373. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30374. get: function () {
  30375. if (!this._texture) {
  30376. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30377. }
  30378. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30379. },
  30380. enumerable: true,
  30381. configurable: true
  30382. });
  30383. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30384. get: function () {
  30385. if (!this._texture) {
  30386. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30387. }
  30388. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30389. },
  30390. enumerable: true,
  30391. configurable: true
  30392. });
  30393. BaseTexture.prototype.readPixels = function (faceIndex) {
  30394. if (faceIndex === void 0) { faceIndex = 0; }
  30395. if (!this._texture) {
  30396. return null;
  30397. }
  30398. var size = this.getSize();
  30399. var scene = this.getScene();
  30400. if (!scene) {
  30401. return null;
  30402. }
  30403. var engine = scene.getEngine();
  30404. if (this._texture.isCube) {
  30405. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30406. }
  30407. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30408. };
  30409. BaseTexture.prototype.releaseInternalTexture = function () {
  30410. if (this._texture) {
  30411. this._texture.dispose();
  30412. this._texture = null;
  30413. }
  30414. };
  30415. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30416. get: function () {
  30417. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30418. return null;
  30419. }
  30420. if (!this._texture._sphericalPolynomial) {
  30421. this._texture._sphericalPolynomial =
  30422. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30423. }
  30424. return this._texture._sphericalPolynomial;
  30425. },
  30426. set: function (value) {
  30427. if (this._texture) {
  30428. this._texture._sphericalPolynomial = value;
  30429. }
  30430. },
  30431. enumerable: true,
  30432. configurable: true
  30433. });
  30434. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30435. get: function () {
  30436. if (this._texture) {
  30437. return this._texture._lodTextureHigh;
  30438. }
  30439. return null;
  30440. },
  30441. enumerable: true,
  30442. configurable: true
  30443. });
  30444. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30445. get: function () {
  30446. if (this._texture) {
  30447. return this._texture._lodTextureMid;
  30448. }
  30449. return null;
  30450. },
  30451. enumerable: true,
  30452. configurable: true
  30453. });
  30454. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30455. get: function () {
  30456. if (this._texture) {
  30457. return this._texture._lodTextureLow;
  30458. }
  30459. return null;
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. BaseTexture.prototype.dispose = function () {
  30465. if (!this._scene) {
  30466. return;
  30467. }
  30468. // Animations
  30469. this._scene.stopAnimation(this);
  30470. // Remove from scene
  30471. this._scene._removePendingData(this);
  30472. var index = this._scene.textures.indexOf(this);
  30473. if (index >= 0) {
  30474. this._scene.textures.splice(index, 1);
  30475. }
  30476. if (this._texture === undefined) {
  30477. return;
  30478. }
  30479. // Release
  30480. this.releaseInternalTexture();
  30481. // Callback
  30482. this.onDisposeObservable.notifyObservers(this);
  30483. this.onDisposeObservable.clear();
  30484. };
  30485. BaseTexture.prototype.serialize = function () {
  30486. if (!this.name) {
  30487. return null;
  30488. }
  30489. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30490. // Animations
  30491. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30492. return serializationObject;
  30493. };
  30494. BaseTexture.WhenAllReady = function (textures, callback) {
  30495. var numRemaining = textures.length;
  30496. if (numRemaining === 0) {
  30497. callback();
  30498. return;
  30499. }
  30500. var _loop_1 = function () {
  30501. texture = textures[i];
  30502. if (texture.isReady()) {
  30503. if (--numRemaining === 0) {
  30504. callback();
  30505. }
  30506. }
  30507. else {
  30508. onLoadObservable = texture.onLoadObservable;
  30509. var onLoadCallback_1 = function () {
  30510. onLoadObservable.removeCallback(onLoadCallback_1);
  30511. if (--numRemaining === 0) {
  30512. callback();
  30513. }
  30514. };
  30515. onLoadObservable.add(onLoadCallback_1);
  30516. }
  30517. };
  30518. var texture, onLoadObservable;
  30519. for (var i = 0; i < textures.length; i++) {
  30520. _loop_1();
  30521. }
  30522. };
  30523. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30524. __decorate([
  30525. BABYLON.serialize()
  30526. ], BaseTexture.prototype, "name", void 0);
  30527. __decorate([
  30528. BABYLON.serialize("hasAlpha")
  30529. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30530. __decorate([
  30531. BABYLON.serialize()
  30532. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30533. __decorate([
  30534. BABYLON.serialize()
  30535. ], BaseTexture.prototype, "level", void 0);
  30536. __decorate([
  30537. BABYLON.serialize()
  30538. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30539. __decorate([
  30540. BABYLON.serialize("coordinatesMode")
  30541. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30542. __decorate([
  30543. BABYLON.serialize()
  30544. ], BaseTexture.prototype, "wrapU", void 0);
  30545. __decorate([
  30546. BABYLON.serialize()
  30547. ], BaseTexture.prototype, "wrapV", void 0);
  30548. __decorate([
  30549. BABYLON.serialize()
  30550. ], BaseTexture.prototype, "wrapR", void 0);
  30551. __decorate([
  30552. BABYLON.serialize()
  30553. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30554. __decorate([
  30555. BABYLON.serialize()
  30556. ], BaseTexture.prototype, "isCube", void 0);
  30557. __decorate([
  30558. BABYLON.serialize()
  30559. ], BaseTexture.prototype, "is3D", void 0);
  30560. __decorate([
  30561. BABYLON.serialize()
  30562. ], BaseTexture.prototype, "gammaSpace", void 0);
  30563. __decorate([
  30564. BABYLON.serialize()
  30565. ], BaseTexture.prototype, "invertZ", void 0);
  30566. __decorate([
  30567. BABYLON.serialize()
  30568. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30569. __decorate([
  30570. BABYLON.serialize()
  30571. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30572. __decorate([
  30573. BABYLON.serialize()
  30574. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30575. __decorate([
  30576. BABYLON.serialize()
  30577. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30578. return BaseTexture;
  30579. }());
  30580. BABYLON.BaseTexture = BaseTexture;
  30581. })(BABYLON || (BABYLON = {}));
  30582. //# sourceMappingURL=babylon.baseTexture.js.map
  30583. var BABYLON;
  30584. (function (BABYLON) {
  30585. var Texture = /** @class */ (function (_super) {
  30586. __extends(Texture, _super);
  30587. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30588. if (noMipmap === void 0) { noMipmap = false; }
  30589. if (invertY === void 0) { invertY = true; }
  30590. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30591. if (onLoad === void 0) { onLoad = null; }
  30592. if (onError === void 0) { onError = null; }
  30593. if (buffer === void 0) { buffer = null; }
  30594. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30595. var _this = _super.call(this, scene) || this;
  30596. _this.uOffset = 0;
  30597. _this.vOffset = 0;
  30598. _this.uScale = 1.0;
  30599. _this.vScale = 1.0;
  30600. _this.uAng = 0;
  30601. _this.vAng = 0;
  30602. _this.wAng = 0;
  30603. /**
  30604. * Defines the center of rotation (U)
  30605. */
  30606. _this.uRotationCenter = 0.5;
  30607. /**
  30608. * Defines the center of rotation (V)
  30609. */
  30610. _this.vRotationCenter = 0.5;
  30611. /**
  30612. * Defines the center of rotation (W)
  30613. */
  30614. _this.wRotationCenter = 0.5;
  30615. _this._isBlocking = true;
  30616. _this.name = url || "";
  30617. _this.url = url;
  30618. _this._noMipmap = noMipmap;
  30619. _this._invertY = invertY;
  30620. _this._samplingMode = samplingMode;
  30621. _this._buffer = buffer;
  30622. _this._deleteBuffer = deleteBuffer;
  30623. if (format) {
  30624. _this._format = format;
  30625. }
  30626. scene = _this.getScene();
  30627. if (!scene) {
  30628. return _this;
  30629. }
  30630. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30631. var load = function () {
  30632. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30633. _this.onLoadObservable.notifyObservers(_this);
  30634. }
  30635. if (onLoad) {
  30636. onLoad();
  30637. }
  30638. if (!_this.isBlocking && scene) {
  30639. scene.resetCachedMaterial();
  30640. }
  30641. };
  30642. if (!_this.url) {
  30643. _this._delayedOnLoad = load;
  30644. _this._delayedOnError = onError;
  30645. return _this;
  30646. }
  30647. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30648. if (!_this._texture) {
  30649. if (!scene.useDelayedTextureLoading) {
  30650. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30651. if (deleteBuffer) {
  30652. delete _this._buffer;
  30653. }
  30654. }
  30655. else {
  30656. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30657. _this._delayedOnLoad = load;
  30658. _this._delayedOnError = onError;
  30659. }
  30660. }
  30661. else {
  30662. if (_this._texture.isReady) {
  30663. BABYLON.Tools.SetImmediate(function () { return load(); });
  30664. }
  30665. else {
  30666. _this._texture.onLoadedObservable.add(load);
  30667. }
  30668. }
  30669. return _this;
  30670. }
  30671. Object.defineProperty(Texture.prototype, "noMipmap", {
  30672. get: function () {
  30673. return this._noMipmap;
  30674. },
  30675. enumerable: true,
  30676. configurable: true
  30677. });
  30678. Object.defineProperty(Texture.prototype, "isBlocking", {
  30679. get: function () {
  30680. return this._isBlocking;
  30681. },
  30682. set: function (value) {
  30683. this._isBlocking = value;
  30684. },
  30685. enumerable: true,
  30686. configurable: true
  30687. });
  30688. Object.defineProperty(Texture.prototype, "samplingMode", {
  30689. get: function () {
  30690. return this._samplingMode;
  30691. },
  30692. enumerable: true,
  30693. configurable: true
  30694. });
  30695. Texture.prototype.updateURL = function (url) {
  30696. this.url = url;
  30697. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30698. this.delayLoad();
  30699. };
  30700. Texture.prototype.delayLoad = function () {
  30701. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30702. return;
  30703. }
  30704. var scene = this.getScene();
  30705. if (!scene) {
  30706. return;
  30707. }
  30708. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30709. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30710. if (!this._texture) {
  30711. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30712. if (this._deleteBuffer) {
  30713. delete this._buffer;
  30714. }
  30715. }
  30716. else {
  30717. if (this._delayedOnLoad) {
  30718. if (this._texture.isReady) {
  30719. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30720. }
  30721. else {
  30722. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30723. }
  30724. }
  30725. }
  30726. this._delayedOnLoad = null;
  30727. this._delayedOnError = null;
  30728. };
  30729. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30730. if (!this._texture) {
  30731. return;
  30732. }
  30733. var scene = this.getScene();
  30734. if (!scene) {
  30735. return;
  30736. }
  30737. this._samplingMode = samplingMode;
  30738. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30739. };
  30740. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30741. x *= this.uScale;
  30742. y *= this.vScale;
  30743. x -= this.uRotationCenter * this.uScale;
  30744. y -= this.vRotationCenter * this.vScale;
  30745. z -= this.wRotationCenter;
  30746. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30747. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30748. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30749. t.z += this.wRotationCenter;
  30750. };
  30751. Texture.prototype.getTextureMatrix = function () {
  30752. var _this = this;
  30753. if (this.uOffset === this._cachedUOffset &&
  30754. this.vOffset === this._cachedVOffset &&
  30755. this.uScale === this._cachedUScale &&
  30756. this.vScale === this._cachedVScale &&
  30757. this.uAng === this._cachedUAng &&
  30758. this.vAng === this._cachedVAng &&
  30759. this.wAng === this._cachedWAng) {
  30760. return this._cachedTextureMatrix;
  30761. }
  30762. this._cachedUOffset = this.uOffset;
  30763. this._cachedVOffset = this.vOffset;
  30764. this._cachedUScale = this.uScale;
  30765. this._cachedVScale = this.vScale;
  30766. this._cachedUAng = this.uAng;
  30767. this._cachedVAng = this.vAng;
  30768. this._cachedWAng = this.wAng;
  30769. if (!this._cachedTextureMatrix) {
  30770. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30771. this._rowGenerationMatrix = new BABYLON.Matrix();
  30772. this._t0 = BABYLON.Vector3.Zero();
  30773. this._t1 = BABYLON.Vector3.Zero();
  30774. this._t2 = BABYLON.Vector3.Zero();
  30775. }
  30776. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30777. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30778. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30779. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30780. this._t1.subtractInPlace(this._t0);
  30781. this._t2.subtractInPlace(this._t0);
  30782. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30783. this._cachedTextureMatrix.m[0] = this._t1.x;
  30784. this._cachedTextureMatrix.m[1] = this._t1.y;
  30785. this._cachedTextureMatrix.m[2] = this._t1.z;
  30786. this._cachedTextureMatrix.m[4] = this._t2.x;
  30787. this._cachedTextureMatrix.m[5] = this._t2.y;
  30788. this._cachedTextureMatrix.m[6] = this._t2.z;
  30789. this._cachedTextureMatrix.m[8] = this._t0.x;
  30790. this._cachedTextureMatrix.m[9] = this._t0.y;
  30791. this._cachedTextureMatrix.m[10] = this._t0.z;
  30792. var scene = this.getScene();
  30793. if (!scene) {
  30794. return this._cachedTextureMatrix;
  30795. }
  30796. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30797. return mat.hasTexture(_this);
  30798. });
  30799. return this._cachedTextureMatrix;
  30800. };
  30801. Texture.prototype.getReflectionTextureMatrix = function () {
  30802. var _this = this;
  30803. var scene = this.getScene();
  30804. if (!scene) {
  30805. return this._cachedTextureMatrix;
  30806. }
  30807. if (this.uOffset === this._cachedUOffset &&
  30808. this.vOffset === this._cachedVOffset &&
  30809. this.uScale === this._cachedUScale &&
  30810. this.vScale === this._cachedVScale &&
  30811. this.coordinatesMode === this._cachedCoordinatesMode) {
  30812. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30813. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30814. return this._cachedTextureMatrix;
  30815. }
  30816. }
  30817. else {
  30818. return this._cachedTextureMatrix;
  30819. }
  30820. }
  30821. if (!this._cachedTextureMatrix) {
  30822. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30823. }
  30824. if (!this._projectionModeMatrix) {
  30825. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30826. }
  30827. this._cachedUOffset = this.uOffset;
  30828. this._cachedVOffset = this.vOffset;
  30829. this._cachedUScale = this.uScale;
  30830. this._cachedVScale = this.vScale;
  30831. this._cachedCoordinatesMode = this.coordinatesMode;
  30832. switch (this.coordinatesMode) {
  30833. case Texture.PLANAR_MODE:
  30834. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30835. this._cachedTextureMatrix[0] = this.uScale;
  30836. this._cachedTextureMatrix[5] = this.vScale;
  30837. this._cachedTextureMatrix[12] = this.uOffset;
  30838. this._cachedTextureMatrix[13] = this.vOffset;
  30839. break;
  30840. case Texture.PROJECTION_MODE:
  30841. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30842. this._projectionModeMatrix.m[0] = 0.5;
  30843. this._projectionModeMatrix.m[5] = -0.5;
  30844. this._projectionModeMatrix.m[10] = 0.0;
  30845. this._projectionModeMatrix.m[12] = 0.5;
  30846. this._projectionModeMatrix.m[13] = 0.5;
  30847. this._projectionModeMatrix.m[14] = 1.0;
  30848. this._projectionModeMatrix.m[15] = 1.0;
  30849. var projectionMatrix = scene.getProjectionMatrix();
  30850. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30851. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30852. break;
  30853. default:
  30854. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30855. break;
  30856. }
  30857. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30858. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30859. });
  30860. return this._cachedTextureMatrix;
  30861. };
  30862. Texture.prototype.clone = function () {
  30863. var _this = this;
  30864. return BABYLON.SerializationHelper.Clone(function () {
  30865. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30866. }, this);
  30867. };
  30868. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30869. get: function () {
  30870. if (!this._onLoadObservable) {
  30871. this._onLoadObservable = new BABYLON.Observable();
  30872. }
  30873. return this._onLoadObservable;
  30874. },
  30875. enumerable: true,
  30876. configurable: true
  30877. });
  30878. Texture.prototype.serialize = function () {
  30879. var serializationObject = _super.prototype.serialize.call(this);
  30880. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30881. serializationObject.base64String = this._buffer;
  30882. serializationObject.name = serializationObject.name.replace("data:", "");
  30883. }
  30884. serializationObject.invertY = this._invertY;
  30885. serializationObject.samplingMode = this.samplingMode;
  30886. return serializationObject;
  30887. };
  30888. Texture.prototype.getClassName = function () {
  30889. return "Texture";
  30890. };
  30891. Texture.prototype.dispose = function () {
  30892. _super.prototype.dispose.call(this);
  30893. if (this.onLoadObservable) {
  30894. this.onLoadObservable.clear();
  30895. this._onLoadObservable = null;
  30896. }
  30897. this._delayedOnLoad = null;
  30898. this._delayedOnError = null;
  30899. };
  30900. // Statics
  30901. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30902. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30903. if (onLoad === void 0) { onLoad = null; }
  30904. if (onError === void 0) { onError = null; }
  30905. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30906. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30907. };
  30908. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30909. if (parsedTexture.customType) {
  30910. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30911. // Update Sampling Mode
  30912. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30913. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30914. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30915. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30916. }
  30917. }
  30918. return parsedCustomTexture;
  30919. }
  30920. if (parsedTexture.isCube) {
  30921. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30922. }
  30923. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30924. return null;
  30925. }
  30926. var texture = BABYLON.SerializationHelper.Parse(function () {
  30927. var generateMipMaps = true;
  30928. if (parsedTexture.noMipmap) {
  30929. generateMipMaps = false;
  30930. }
  30931. if (parsedTexture.mirrorPlane) {
  30932. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30933. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30934. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30935. return mirrorTexture;
  30936. }
  30937. else if (parsedTexture.isRenderTarget) {
  30938. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30939. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30940. return renderTargetTexture;
  30941. }
  30942. else {
  30943. var texture;
  30944. if (parsedTexture.base64String) {
  30945. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30946. }
  30947. else {
  30948. var url = rootUrl + parsedTexture.name;
  30949. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30950. url = parsedTexture.url;
  30951. }
  30952. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30953. }
  30954. return texture;
  30955. }
  30956. }, parsedTexture, scene);
  30957. // Update Sampling Mode
  30958. if (parsedTexture.samplingMode) {
  30959. var sampling = parsedTexture.samplingMode;
  30960. if (texture._samplingMode !== sampling) {
  30961. texture.updateSamplingMode(sampling);
  30962. }
  30963. }
  30964. // Animations
  30965. if (parsedTexture.animations) {
  30966. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30967. var parsedAnimation = parsedTexture.animations[animationIndex];
  30968. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30969. }
  30970. }
  30971. return texture;
  30972. };
  30973. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30974. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30975. if (noMipmap === void 0) { noMipmap = false; }
  30976. if (invertY === void 0) { invertY = true; }
  30977. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30978. if (onLoad === void 0) { onLoad = null; }
  30979. if (onError === void 0) { onError = null; }
  30980. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30981. if (name.substr(0, 5) !== "data:") {
  30982. name = "data:" + name;
  30983. }
  30984. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30985. };
  30986. // Constants
  30987. Texture.NEAREST_SAMPLINGMODE = 1;
  30988. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30989. Texture.BILINEAR_SAMPLINGMODE = 2;
  30990. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30991. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30992. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30993. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30994. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30995. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30996. Texture.NEAREST_LINEAR = 7;
  30997. Texture.NEAREST_NEAREST = 8;
  30998. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30999. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31000. Texture.LINEAR_LINEAR = 11;
  31001. Texture.LINEAR_NEAREST = 12;
  31002. Texture.EXPLICIT_MODE = 0;
  31003. Texture.SPHERICAL_MODE = 1;
  31004. Texture.PLANAR_MODE = 2;
  31005. Texture.CUBIC_MODE = 3;
  31006. Texture.PROJECTION_MODE = 4;
  31007. Texture.SKYBOX_MODE = 5;
  31008. Texture.INVCUBIC_MODE = 6;
  31009. Texture.EQUIRECTANGULAR_MODE = 7;
  31010. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31011. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31012. Texture.CLAMP_ADDRESSMODE = 0;
  31013. Texture.WRAP_ADDRESSMODE = 1;
  31014. Texture.MIRROR_ADDRESSMODE = 2;
  31015. /**
  31016. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  31017. */
  31018. Texture.UseSerializedUrlIfAny = false;
  31019. __decorate([
  31020. BABYLON.serialize()
  31021. ], Texture.prototype, "url", void 0);
  31022. __decorate([
  31023. BABYLON.serialize()
  31024. ], Texture.prototype, "uOffset", void 0);
  31025. __decorate([
  31026. BABYLON.serialize()
  31027. ], Texture.prototype, "vOffset", void 0);
  31028. __decorate([
  31029. BABYLON.serialize()
  31030. ], Texture.prototype, "uScale", void 0);
  31031. __decorate([
  31032. BABYLON.serialize()
  31033. ], Texture.prototype, "vScale", void 0);
  31034. __decorate([
  31035. BABYLON.serialize()
  31036. ], Texture.prototype, "uAng", void 0);
  31037. __decorate([
  31038. BABYLON.serialize()
  31039. ], Texture.prototype, "vAng", void 0);
  31040. __decorate([
  31041. BABYLON.serialize()
  31042. ], Texture.prototype, "wAng", void 0);
  31043. __decorate([
  31044. BABYLON.serialize()
  31045. ], Texture.prototype, "uRotationCenter", void 0);
  31046. __decorate([
  31047. BABYLON.serialize()
  31048. ], Texture.prototype, "vRotationCenter", void 0);
  31049. __decorate([
  31050. BABYLON.serialize()
  31051. ], Texture.prototype, "wRotationCenter", void 0);
  31052. __decorate([
  31053. BABYLON.serialize()
  31054. ], Texture.prototype, "isBlocking", null);
  31055. return Texture;
  31056. }(BABYLON.BaseTexture));
  31057. BABYLON.Texture = Texture;
  31058. })(BABYLON || (BABYLON = {}));
  31059. //# sourceMappingURL=babylon.texture.js.map
  31060. var BABYLON;
  31061. (function (BABYLON) {
  31062. /**
  31063. * @hidden
  31064. **/
  31065. var _InstancesBatch = /** @class */ (function () {
  31066. function _InstancesBatch() {
  31067. this.mustReturn = false;
  31068. this.visibleInstances = new Array();
  31069. this.renderSelf = new Array();
  31070. }
  31071. return _InstancesBatch;
  31072. }());
  31073. BABYLON._InstancesBatch = _InstancesBatch;
  31074. var Mesh = /** @class */ (function (_super) {
  31075. __extends(Mesh, _super);
  31076. /**
  31077. * @constructor
  31078. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31079. * @param {Scene} scene The scene to add this mesh to.
  31080. * @param {Node} parent The parent of this mesh, if it has one
  31081. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31082. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31083. * When false, achieved by calling a clone(), also passing False.
  31084. * This will make creation of children, recursive.
  31085. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31086. */
  31087. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31088. if (scene === void 0) { scene = null; }
  31089. if (parent === void 0) { parent = null; }
  31090. if (source === void 0) { source = null; }
  31091. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31092. var _this = _super.call(this, name, scene) || this;
  31093. // Events
  31094. /**
  31095. * An event triggered before rendering the mesh
  31096. */
  31097. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31098. /**
  31099. * An event triggered after rendering the mesh
  31100. */
  31101. _this.onAfterRenderObservable = new BABYLON.Observable();
  31102. /**
  31103. * An event triggered before drawing the mesh
  31104. */
  31105. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31106. // Members
  31107. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31108. _this.instances = new Array();
  31109. _this._LODLevels = new Array();
  31110. _this._visibleInstances = {};
  31111. _this._renderIdForInstances = new Array();
  31112. _this._batchCache = new _InstancesBatch();
  31113. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31114. // Use by builder only to know what orientation were the mesh build in.
  31115. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31116. _this.overrideMaterialSideOrientation = null;
  31117. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31118. // Will be used to save a source mesh reference, If any
  31119. _this._source = null;
  31120. scene = _this.getScene();
  31121. if (source) {
  31122. // Source mesh
  31123. _this._source = source;
  31124. // Geometry
  31125. if (source._geometry) {
  31126. source._geometry.applyToMesh(_this);
  31127. }
  31128. // Deep copy
  31129. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31130. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  31131. // Metadata
  31132. if (source.metadata && source.metadata.clone) {
  31133. _this.metadata = source.metadata.clone();
  31134. }
  31135. else {
  31136. _this.metadata = source.metadata;
  31137. }
  31138. // Tags
  31139. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31140. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31141. }
  31142. // Parent
  31143. _this.parent = source.parent;
  31144. // Pivot
  31145. _this.setPivotMatrix(source.getPivotMatrix());
  31146. _this.id = name + "." + source.id;
  31147. // Material
  31148. _this.material = source.material;
  31149. var index;
  31150. if (!doNotCloneChildren) {
  31151. // Children
  31152. var directDescendants = source.getDescendants(true);
  31153. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31154. var child = directDescendants[index_1];
  31155. if (child.clone) {
  31156. child.clone(name + "." + child.name, _this);
  31157. }
  31158. }
  31159. }
  31160. // Physics clone
  31161. var physicsEngine = _this.getScene().getPhysicsEngine();
  31162. if (clonePhysicsImpostor && physicsEngine) {
  31163. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31164. if (impostor) {
  31165. _this.physicsImpostor = impostor.clone(_this);
  31166. }
  31167. }
  31168. // Particles
  31169. for (index = 0; index < scene.particleSystems.length; index++) {
  31170. var system = scene.particleSystems[index];
  31171. if (system.emitter === source) {
  31172. system.clone(system.name, _this);
  31173. }
  31174. }
  31175. _this.computeWorldMatrix(true);
  31176. }
  31177. // Parent
  31178. if (parent !== null) {
  31179. _this.parent = parent;
  31180. }
  31181. return _this;
  31182. }
  31183. Object.defineProperty(Mesh, "FRONTSIDE", {
  31184. /**
  31185. * Mesh side orientation : usually the external or front surface
  31186. */
  31187. get: function () {
  31188. return Mesh._FRONTSIDE;
  31189. },
  31190. enumerable: true,
  31191. configurable: true
  31192. });
  31193. Object.defineProperty(Mesh, "BACKSIDE", {
  31194. /**
  31195. * Mesh side orientation : usually the internal or back surface
  31196. */
  31197. get: function () {
  31198. return Mesh._BACKSIDE;
  31199. },
  31200. enumerable: true,
  31201. configurable: true
  31202. });
  31203. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31204. /**
  31205. * Mesh side orientation : both internal and external or front and back surfaces
  31206. */
  31207. get: function () {
  31208. return Mesh._DOUBLESIDE;
  31209. },
  31210. enumerable: true,
  31211. configurable: true
  31212. });
  31213. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31214. /**
  31215. * Mesh side orientation : by default, `FRONTSIDE`
  31216. */
  31217. get: function () {
  31218. return Mesh._DEFAULTSIDE;
  31219. },
  31220. enumerable: true,
  31221. configurable: true
  31222. });
  31223. Object.defineProperty(Mesh, "NO_CAP", {
  31224. /**
  31225. * Mesh cap setting : no cap
  31226. */
  31227. get: function () {
  31228. return Mesh._NO_CAP;
  31229. },
  31230. enumerable: true,
  31231. configurable: true
  31232. });
  31233. Object.defineProperty(Mesh, "CAP_START", {
  31234. /**
  31235. * Mesh cap setting : one cap at the beginning of the mesh
  31236. */
  31237. get: function () {
  31238. return Mesh._CAP_START;
  31239. },
  31240. enumerable: true,
  31241. configurable: true
  31242. });
  31243. Object.defineProperty(Mesh, "CAP_END", {
  31244. /**
  31245. * Mesh cap setting : one cap at the end of the mesh
  31246. */
  31247. get: function () {
  31248. return Mesh._CAP_END;
  31249. },
  31250. enumerable: true,
  31251. configurable: true
  31252. });
  31253. Object.defineProperty(Mesh, "CAP_ALL", {
  31254. /**
  31255. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31256. */
  31257. get: function () {
  31258. return Mesh._CAP_ALL;
  31259. },
  31260. enumerable: true,
  31261. configurable: true
  31262. });
  31263. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31264. set: function (callback) {
  31265. if (this._onBeforeDrawObserver) {
  31266. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31267. }
  31268. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31269. },
  31270. enumerable: true,
  31271. configurable: true
  31272. });
  31273. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31274. get: function () {
  31275. return this._morphTargetManager;
  31276. },
  31277. set: function (value) {
  31278. if (this._morphTargetManager === value) {
  31279. return;
  31280. }
  31281. this._morphTargetManager = value;
  31282. this._syncGeometryWithMorphTargetManager();
  31283. },
  31284. enumerable: true,
  31285. configurable: true
  31286. });
  31287. Object.defineProperty(Mesh.prototype, "source", {
  31288. get: function () {
  31289. return this._source;
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31295. get: function () {
  31296. return this._unIndexed;
  31297. },
  31298. set: function (value) {
  31299. if (this._unIndexed !== value) {
  31300. this._unIndexed = value;
  31301. this._markSubMeshesAsAttributesDirty();
  31302. }
  31303. },
  31304. enumerable: true,
  31305. configurable: true
  31306. });
  31307. // Methods
  31308. /**
  31309. * Returns the string "Mesh".
  31310. */
  31311. Mesh.prototype.getClassName = function () {
  31312. return "Mesh";
  31313. };
  31314. /**
  31315. * Returns a string.
  31316. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31317. */
  31318. Mesh.prototype.toString = function (fullDetails) {
  31319. var ret = _super.prototype.toString.call(this, fullDetails);
  31320. ret += ", n vertices: " + this.getTotalVertices();
  31321. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31322. if (this.animations) {
  31323. for (var i = 0; i < this.animations.length; i++) {
  31324. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31325. }
  31326. }
  31327. if (fullDetails) {
  31328. if (this._geometry) {
  31329. var ib = this.getIndices();
  31330. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31331. if (vb && ib) {
  31332. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31333. }
  31334. }
  31335. else {
  31336. ret += ", flat shading: UNKNOWN";
  31337. }
  31338. }
  31339. return ret;
  31340. };
  31341. Mesh.prototype._unBindEffect = function () {
  31342. _super.prototype._unBindEffect.call(this);
  31343. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31344. var instance = _a[_i];
  31345. instance._unBindEffect();
  31346. }
  31347. };
  31348. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31349. /**
  31350. * True if the mesh has some Levels Of Details (LOD).
  31351. * Returns a boolean.
  31352. */
  31353. get: function () {
  31354. return this._LODLevels.length > 0;
  31355. },
  31356. enumerable: true,
  31357. configurable: true
  31358. });
  31359. /**
  31360. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31361. * @returns an array of {BABYLON.MeshLODLevel}
  31362. */
  31363. Mesh.prototype.getLODLevels = function () {
  31364. return this._LODLevels;
  31365. };
  31366. Mesh.prototype._sortLODLevels = function () {
  31367. this._LODLevels.sort(function (a, b) {
  31368. if (a.distance < b.distance) {
  31369. return 1;
  31370. }
  31371. if (a.distance > b.distance) {
  31372. return -1;
  31373. }
  31374. return 0;
  31375. });
  31376. };
  31377. /**
  31378. * Add a mesh as LOD level triggered at the given distance.
  31379. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31380. * @param {number} distance The distance from the center of the object to show this level
  31381. * @param {Mesh} mesh The mesh to be added as LOD level
  31382. * @return {Mesh} This mesh (for chaining)
  31383. */
  31384. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31385. if (mesh && mesh._masterMesh) {
  31386. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31387. return this;
  31388. }
  31389. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31390. this._LODLevels.push(level);
  31391. if (mesh) {
  31392. mesh._masterMesh = this;
  31393. }
  31394. this._sortLODLevels();
  31395. return this;
  31396. };
  31397. /**
  31398. * Returns the LOD level mesh at the passed distance or null if not found.
  31399. * It is related to the method `addLODLevel(distance, mesh)`.
  31400. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31401. * Returns an object Mesh or `null`.
  31402. */
  31403. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31404. for (var index = 0; index < this._LODLevels.length; index++) {
  31405. var level = this._LODLevels[index];
  31406. if (level.distance === distance) {
  31407. return level.mesh;
  31408. }
  31409. }
  31410. return null;
  31411. };
  31412. /**
  31413. * Remove a mesh from the LOD array
  31414. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31415. * @param {Mesh} mesh The mesh to be removed.
  31416. * @return {Mesh} This mesh (for chaining)
  31417. */
  31418. Mesh.prototype.removeLODLevel = function (mesh) {
  31419. for (var index = 0; index < this._LODLevels.length; index++) {
  31420. if (this._LODLevels[index].mesh === mesh) {
  31421. this._LODLevels.splice(index, 1);
  31422. if (mesh) {
  31423. mesh._masterMesh = null;
  31424. }
  31425. }
  31426. }
  31427. this._sortLODLevels();
  31428. return this;
  31429. };
  31430. /**
  31431. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31432. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31433. */
  31434. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31435. if (!this._LODLevels || this._LODLevels.length === 0) {
  31436. return this;
  31437. }
  31438. var bSphere;
  31439. if (boundingSphere) {
  31440. bSphere = boundingSphere;
  31441. }
  31442. else {
  31443. var boundingInfo = this.getBoundingInfo();
  31444. bSphere = boundingInfo.boundingSphere;
  31445. }
  31446. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31447. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31448. if (this.onLODLevelSelection) {
  31449. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31450. }
  31451. return this;
  31452. }
  31453. for (var index = 0; index < this._LODLevels.length; index++) {
  31454. var level = this._LODLevels[index];
  31455. if (level.distance < distanceToCamera) {
  31456. if (level.mesh) {
  31457. level.mesh._preActivate();
  31458. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31459. }
  31460. if (this.onLODLevelSelection) {
  31461. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31462. }
  31463. return level.mesh;
  31464. }
  31465. }
  31466. if (this.onLODLevelSelection) {
  31467. this.onLODLevelSelection(distanceToCamera, this, this);
  31468. }
  31469. return this;
  31470. };
  31471. Object.defineProperty(Mesh.prototype, "geometry", {
  31472. /**
  31473. * Returns the mesh internal Geometry object.
  31474. */
  31475. get: function () {
  31476. return this._geometry;
  31477. },
  31478. enumerable: true,
  31479. configurable: true
  31480. });
  31481. /**
  31482. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31483. */
  31484. Mesh.prototype.getTotalVertices = function () {
  31485. if (this._geometry === null || this._geometry === undefined) {
  31486. return 0;
  31487. }
  31488. return this._geometry.getTotalVertices();
  31489. };
  31490. /**
  31491. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31492. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31493. * You can force the copy with forceCopy === true
  31494. * Returns null if the mesh has no geometry or no vertex buffer.
  31495. * Possible `kind` values :
  31496. * - BABYLON.VertexBuffer.PositionKind
  31497. * - BABYLON.VertexBuffer.UVKind
  31498. * - BABYLON.VertexBuffer.UV2Kind
  31499. * - BABYLON.VertexBuffer.UV3Kind
  31500. * - BABYLON.VertexBuffer.UV4Kind
  31501. * - BABYLON.VertexBuffer.UV5Kind
  31502. * - BABYLON.VertexBuffer.UV6Kind
  31503. * - BABYLON.VertexBuffer.ColorKind
  31504. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31505. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31506. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31507. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31508. */
  31509. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31510. if (!this._geometry) {
  31511. return null;
  31512. }
  31513. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31514. };
  31515. /**
  31516. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31517. * Returns `null` if the mesh has no geometry.
  31518. * Possible `kind` values :
  31519. * - BABYLON.VertexBuffer.PositionKind
  31520. * - BABYLON.VertexBuffer.UVKind
  31521. * - BABYLON.VertexBuffer.UV2Kind
  31522. * - BABYLON.VertexBuffer.UV3Kind
  31523. * - BABYLON.VertexBuffer.UV4Kind
  31524. * - BABYLON.VertexBuffer.UV5Kind
  31525. * - BABYLON.VertexBuffer.UV6Kind
  31526. * - BABYLON.VertexBuffer.ColorKind
  31527. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31528. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31529. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31530. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31531. */
  31532. Mesh.prototype.getVertexBuffer = function (kind) {
  31533. if (!this._geometry) {
  31534. return null;
  31535. }
  31536. return this._geometry.getVertexBuffer(kind);
  31537. };
  31538. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31539. if (!this._geometry) {
  31540. if (this._delayInfo) {
  31541. return this._delayInfo.indexOf(kind) !== -1;
  31542. }
  31543. return false;
  31544. }
  31545. return this._geometry.isVerticesDataPresent(kind);
  31546. };
  31547. /**
  31548. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31549. * Possible `kind` values :
  31550. * - BABYLON.VertexBuffer.PositionKind
  31551. * - BABYLON.VertexBuffer.UVKind
  31552. * - BABYLON.VertexBuffer.UV2Kind
  31553. * - BABYLON.VertexBuffer.UV3Kind
  31554. * - BABYLON.VertexBuffer.UV4Kind
  31555. * - BABYLON.VertexBuffer.UV5Kind
  31556. * - BABYLON.VertexBuffer.UV6Kind
  31557. * - BABYLON.VertexBuffer.ColorKind
  31558. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31559. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31560. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31561. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31562. */
  31563. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31564. if (!this._geometry) {
  31565. if (this._delayInfo) {
  31566. return this._delayInfo.indexOf(kind) !== -1;
  31567. }
  31568. return false;
  31569. }
  31570. return this._geometry.isVertexBufferUpdatable(kind);
  31571. };
  31572. /**
  31573. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31574. * Possible `kind` values :
  31575. * - BABYLON.VertexBuffer.PositionKind
  31576. * - BABYLON.VertexBuffer.UVKind
  31577. * - BABYLON.VertexBuffer.UV2Kind
  31578. * - BABYLON.VertexBuffer.UV3Kind
  31579. * - BABYLON.VertexBuffer.UV4Kind
  31580. * - BABYLON.VertexBuffer.UV5Kind
  31581. * - BABYLON.VertexBuffer.UV6Kind
  31582. * - BABYLON.VertexBuffer.ColorKind
  31583. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31584. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31585. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31586. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31587. */
  31588. Mesh.prototype.getVerticesDataKinds = function () {
  31589. if (!this._geometry) {
  31590. var result = new Array();
  31591. if (this._delayInfo) {
  31592. this._delayInfo.forEach(function (kind, index, array) {
  31593. result.push(kind);
  31594. });
  31595. }
  31596. return result;
  31597. }
  31598. return this._geometry.getVerticesDataKinds();
  31599. };
  31600. /**
  31601. * Returns a positive integer : the total number of indices in this mesh geometry.
  31602. * Returns zero if the mesh has no geometry.
  31603. */
  31604. Mesh.prototype.getTotalIndices = function () {
  31605. if (!this._geometry) {
  31606. return 0;
  31607. }
  31608. return this._geometry.getTotalIndices();
  31609. };
  31610. /**
  31611. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31612. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31613. * Returns an empty array if the mesh has no geometry.
  31614. */
  31615. Mesh.prototype.getIndices = function (copyWhenShared) {
  31616. if (!this._geometry) {
  31617. return [];
  31618. }
  31619. return this._geometry.getIndices(copyWhenShared);
  31620. };
  31621. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31622. get: function () {
  31623. return this._masterMesh !== null && this._masterMesh !== undefined;
  31624. },
  31625. enumerable: true,
  31626. configurable: true
  31627. });
  31628. /**
  31629. * Determine if the current mesh is ready to be rendered
  31630. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31631. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31632. * @returns true if all associated assets are ready (material, textures, shaders)
  31633. */
  31634. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31635. if (completeCheck === void 0) { completeCheck = false; }
  31636. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31637. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31638. return false;
  31639. }
  31640. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31641. return false;
  31642. }
  31643. if (!this.subMeshes || this.subMeshes.length === 0) {
  31644. return true;
  31645. }
  31646. if (!completeCheck) {
  31647. return true;
  31648. }
  31649. var engine = this.getEngine();
  31650. var scene = this.getScene();
  31651. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31652. this.computeWorldMatrix();
  31653. var mat = this.material || scene.defaultMaterial;
  31654. if (mat) {
  31655. if (mat.storeEffectOnSubMeshes) {
  31656. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31657. var subMesh = _a[_i];
  31658. var effectiveMaterial = subMesh.getMaterial();
  31659. if (effectiveMaterial) {
  31660. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31661. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31662. return false;
  31663. }
  31664. }
  31665. else {
  31666. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31667. return false;
  31668. }
  31669. }
  31670. }
  31671. }
  31672. }
  31673. else {
  31674. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31675. return false;
  31676. }
  31677. }
  31678. }
  31679. // Shadows
  31680. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31681. var light = _c[_b];
  31682. var generator = light.getShadowGenerator();
  31683. if (generator) {
  31684. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31685. var subMesh = _e[_d];
  31686. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31687. return false;
  31688. }
  31689. }
  31690. }
  31691. }
  31692. // LOD
  31693. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31694. var lod = _g[_f];
  31695. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31696. return false;
  31697. }
  31698. }
  31699. return true;
  31700. };
  31701. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31702. /**
  31703. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31704. * This property is pertinent only for updatable parametric shapes.
  31705. */
  31706. get: function () {
  31707. return this._areNormalsFrozen;
  31708. },
  31709. enumerable: true,
  31710. configurable: true
  31711. });
  31712. /**
  31713. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31714. * It has no effect at all on other shapes.
  31715. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31716. * Returns the Mesh.
  31717. */
  31718. Mesh.prototype.freezeNormals = function () {
  31719. this._areNormalsFrozen = true;
  31720. return this;
  31721. };
  31722. /**
  31723. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31724. * It has no effect at all on other shapes.
  31725. * It reactivates the mesh normals computation if it was previously frozen.
  31726. * Returns the Mesh.
  31727. */
  31728. Mesh.prototype.unfreezeNormals = function () {
  31729. this._areNormalsFrozen = false;
  31730. return this;
  31731. };
  31732. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31733. /**
  31734. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31735. */
  31736. set: function (count) {
  31737. this._overridenInstanceCount = count;
  31738. },
  31739. enumerable: true,
  31740. configurable: true
  31741. });
  31742. // Methods
  31743. Mesh.prototype._preActivate = function () {
  31744. var sceneRenderId = this.getScene().getRenderId();
  31745. if (this._preActivateId === sceneRenderId) {
  31746. return this;
  31747. }
  31748. this._preActivateId = sceneRenderId;
  31749. this._visibleInstances = null;
  31750. return this;
  31751. };
  31752. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31753. if (this._visibleInstances) {
  31754. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31755. }
  31756. return this;
  31757. };
  31758. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31759. if (!this._visibleInstances) {
  31760. this._visibleInstances = {};
  31761. this._visibleInstances.defaultRenderId = renderId;
  31762. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31763. }
  31764. if (!this._visibleInstances[renderId]) {
  31765. this._visibleInstances[renderId] = new Array();
  31766. }
  31767. this._visibleInstances[renderId].push(instance);
  31768. return this;
  31769. };
  31770. /**
  31771. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31772. * This means the mesh underlying bounding box and sphere are recomputed.
  31773. * Returns the Mesh.
  31774. */
  31775. Mesh.prototype.refreshBoundingInfo = function () {
  31776. return this._refreshBoundingInfo(false);
  31777. };
  31778. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31779. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31780. return this;
  31781. }
  31782. var data = this._getPositionData(applySkeleton);
  31783. if (data) {
  31784. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31785. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31786. }
  31787. if (this.subMeshes) {
  31788. for (var index = 0; index < this.subMeshes.length; index++) {
  31789. this.subMeshes[index].refreshBoundingInfo();
  31790. }
  31791. }
  31792. this._updateBoundingInfo();
  31793. return this;
  31794. };
  31795. Mesh.prototype._getPositionData = function (applySkeleton) {
  31796. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31797. if (data && applySkeleton && this.skeleton) {
  31798. data = BABYLON.Tools.Slice(data);
  31799. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31800. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31801. if (matricesWeightsData && matricesIndicesData) {
  31802. var needExtras = this.numBoneInfluencers > 4;
  31803. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31804. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31805. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31806. var tempVector = BABYLON.Tmp.Vector3[0];
  31807. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31808. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31809. var matWeightIdx = 0;
  31810. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31811. finalMatrix.reset();
  31812. var inf;
  31813. var weight;
  31814. for (inf = 0; inf < 4; inf++) {
  31815. weight = matricesWeightsData[matWeightIdx + inf];
  31816. if (weight <= 0)
  31817. break;
  31818. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31819. finalMatrix.addToSelf(tempMatrix);
  31820. }
  31821. if (needExtras) {
  31822. for (inf = 0; inf < 4; inf++) {
  31823. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31824. if (weight <= 0)
  31825. break;
  31826. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31827. finalMatrix.addToSelf(tempMatrix);
  31828. }
  31829. }
  31830. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31831. tempVector.toArray(data, index);
  31832. }
  31833. }
  31834. }
  31835. return data;
  31836. };
  31837. Mesh.prototype._createGlobalSubMesh = function (force) {
  31838. var totalVertices = this.getTotalVertices();
  31839. if (!totalVertices || !this.getIndices()) {
  31840. return null;
  31841. }
  31842. // Check if we need to recreate the submeshes
  31843. if (this.subMeshes && this.subMeshes.length > 0) {
  31844. var ib = this.getIndices();
  31845. if (!ib) {
  31846. return null;
  31847. }
  31848. var totalIndices = ib.length;
  31849. var needToRecreate = false;
  31850. if (force) {
  31851. needToRecreate = true;
  31852. }
  31853. else {
  31854. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31855. var submesh = _a[_i];
  31856. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31857. needToRecreate = true;
  31858. break;
  31859. }
  31860. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31861. needToRecreate = true;
  31862. break;
  31863. }
  31864. }
  31865. }
  31866. if (!needToRecreate) {
  31867. return this.subMeshes[0];
  31868. }
  31869. }
  31870. this.releaseSubMeshes();
  31871. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31872. };
  31873. Mesh.prototype.subdivide = function (count) {
  31874. if (count < 1) {
  31875. return;
  31876. }
  31877. var totalIndices = this.getTotalIndices();
  31878. var subdivisionSize = (totalIndices / count) | 0;
  31879. var offset = 0;
  31880. // Ensure that subdivisionSize is a multiple of 3
  31881. while (subdivisionSize % 3 !== 0) {
  31882. subdivisionSize++;
  31883. }
  31884. this.releaseSubMeshes();
  31885. for (var index = 0; index < count; index++) {
  31886. if (offset >= totalIndices) {
  31887. break;
  31888. }
  31889. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31890. offset += subdivisionSize;
  31891. }
  31892. this.synchronizeInstances();
  31893. };
  31894. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31895. if (updatable === void 0) { updatable = false; }
  31896. if (!this._geometry) {
  31897. var vertexData = new BABYLON.VertexData();
  31898. vertexData.set(data, kind);
  31899. var scene = this.getScene();
  31900. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31901. }
  31902. else {
  31903. this._geometry.setVerticesData(kind, data, updatable, stride);
  31904. }
  31905. return this;
  31906. };
  31907. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31908. if (updatable === void 0) { updatable = true; }
  31909. var vb = this.getVertexBuffer(kind);
  31910. if (!vb || vb.isUpdatable() === updatable) {
  31911. return;
  31912. }
  31913. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31914. };
  31915. /**
  31916. * Sets the mesh VertexBuffer.
  31917. * Returns the Mesh.
  31918. */
  31919. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31920. if (!this._geometry) {
  31921. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31922. }
  31923. this._geometry.setVerticesBuffer(buffer);
  31924. return this;
  31925. };
  31926. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31927. if (!this._geometry) {
  31928. return this;
  31929. }
  31930. if (!makeItUnique) {
  31931. this._geometry.updateVerticesData(kind, data, updateExtends);
  31932. }
  31933. else {
  31934. this.makeGeometryUnique();
  31935. this.updateVerticesData(kind, data, updateExtends, false);
  31936. }
  31937. return this;
  31938. };
  31939. /**
  31940. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31941. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31942. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31943. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31944. * Returns the Mesh.
  31945. */
  31946. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31947. if (computeNormals === void 0) { computeNormals = true; }
  31948. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31949. if (!positions) {
  31950. return this;
  31951. }
  31952. positionFunction(positions);
  31953. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31954. if (computeNormals) {
  31955. var indices = this.getIndices();
  31956. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31957. if (!normals) {
  31958. return this;
  31959. }
  31960. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31961. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31962. }
  31963. return this;
  31964. };
  31965. /**
  31966. * Creates a un-shared specific occurence of the geometry for the mesh.
  31967. * Returns the Mesh.
  31968. */
  31969. Mesh.prototype.makeGeometryUnique = function () {
  31970. if (!this._geometry) {
  31971. return this;
  31972. }
  31973. var oldGeometry = this._geometry;
  31974. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31975. oldGeometry.releaseForMesh(this, true);
  31976. geometry.applyToMesh(this);
  31977. return this;
  31978. };
  31979. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31980. if (totalVertices === void 0) { totalVertices = null; }
  31981. if (updatable === void 0) { updatable = false; }
  31982. if (!this._geometry) {
  31983. var vertexData = new BABYLON.VertexData();
  31984. vertexData.indices = indices;
  31985. var scene = this.getScene();
  31986. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31987. }
  31988. else {
  31989. this._geometry.setIndices(indices, totalVertices, updatable);
  31990. }
  31991. return this;
  31992. };
  31993. /**
  31994. * Update the current index buffer
  31995. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31996. * Returns the Mesh.
  31997. */
  31998. Mesh.prototype.updateIndices = function (indices, offset) {
  31999. if (!this._geometry) {
  32000. return this;
  32001. }
  32002. this._geometry.updateIndices(indices, offset);
  32003. return this;
  32004. };
  32005. /**
  32006. * Invert the geometry to move from a right handed system to a left handed one.
  32007. * Returns the Mesh.
  32008. */
  32009. Mesh.prototype.toLeftHanded = function () {
  32010. if (!this._geometry) {
  32011. return this;
  32012. }
  32013. this._geometry.toLeftHanded();
  32014. return this;
  32015. };
  32016. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32017. if (!this._geometry) {
  32018. return this;
  32019. }
  32020. var engine = this.getScene().getEngine();
  32021. // Wireframe
  32022. var indexToBind;
  32023. if (this._unIndexed) {
  32024. indexToBind = null;
  32025. }
  32026. else {
  32027. switch (fillMode) {
  32028. case BABYLON.Material.PointFillMode:
  32029. indexToBind = null;
  32030. break;
  32031. case BABYLON.Material.WireFrameFillMode:
  32032. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32033. break;
  32034. default:
  32035. case BABYLON.Material.TriangleFillMode:
  32036. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32037. break;
  32038. }
  32039. }
  32040. // VBOs
  32041. this._geometry._bind(effect, indexToBind);
  32042. return this;
  32043. };
  32044. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32045. if (alternate === void 0) { alternate = false; }
  32046. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32047. return this;
  32048. }
  32049. this.onBeforeDrawObservable.notifyObservers(this);
  32050. var scene = this.getScene();
  32051. var engine = scene.getEngine();
  32052. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32053. // or triangles as points
  32054. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32055. }
  32056. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32057. // Triangles as wireframe
  32058. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32059. }
  32060. else {
  32061. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32062. }
  32063. if (scene._isAlternateRenderingEnabled && !alternate) {
  32064. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32065. if (!effect || !scene.activeCamera) {
  32066. return this;
  32067. }
  32068. scene._switchToAlternateCameraConfiguration(true);
  32069. this._effectiveMaterial.bindView(effect);
  32070. this._effectiveMaterial.bindViewProjection(effect);
  32071. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32072. this._draw(subMesh, fillMode, instancesCount, true);
  32073. engine.setViewport(scene.activeCamera.viewport);
  32074. scene._switchToAlternateCameraConfiguration(false);
  32075. this._effectiveMaterial.bindView(effect);
  32076. this._effectiveMaterial.bindViewProjection(effect);
  32077. }
  32078. return this;
  32079. };
  32080. /**
  32081. * Registers for this mesh a javascript function called just before the rendering process.
  32082. * This function is passed the current mesh.
  32083. * Return the Mesh.
  32084. */
  32085. Mesh.prototype.registerBeforeRender = function (func) {
  32086. this.onBeforeRenderObservable.add(func);
  32087. return this;
  32088. };
  32089. /**
  32090. * Disposes a previously registered javascript function called before the rendering.
  32091. * This function is passed the current mesh.
  32092. * Returns the Mesh.
  32093. */
  32094. Mesh.prototype.unregisterBeforeRender = function (func) {
  32095. this.onBeforeRenderObservable.removeCallback(func);
  32096. return this;
  32097. };
  32098. /**
  32099. * Registers for this mesh a javascript function called just after the rendering is complete.
  32100. * This function is passed the current mesh.
  32101. * Returns the Mesh.
  32102. */
  32103. Mesh.prototype.registerAfterRender = function (func) {
  32104. this.onAfterRenderObservable.add(func);
  32105. return this;
  32106. };
  32107. /**
  32108. * Disposes a previously registered javascript function called after the rendering.
  32109. * This function is passed the current mesh.
  32110. * Return the Mesh.
  32111. */
  32112. Mesh.prototype.unregisterAfterRender = function (func) {
  32113. this.onAfterRenderObservable.removeCallback(func);
  32114. return this;
  32115. };
  32116. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32117. var scene = this.getScene();
  32118. this._batchCache.mustReturn = false;
  32119. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32120. this._batchCache.visibleInstances[subMeshId] = null;
  32121. if (this._visibleInstances) {
  32122. var currentRenderId = scene.getRenderId();
  32123. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32124. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32125. var selfRenderId = this._renderId;
  32126. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32127. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32128. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32129. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32130. }
  32131. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32132. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32133. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32134. this._batchCache.mustReturn = true;
  32135. return this._batchCache;
  32136. }
  32137. if (currentRenderId !== selfRenderId) {
  32138. this._batchCache.renderSelf[subMeshId] = false;
  32139. }
  32140. }
  32141. this._renderIdForInstances[subMeshId] = currentRenderId;
  32142. }
  32143. return this._batchCache;
  32144. };
  32145. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32146. var visibleInstances = batch.visibleInstances[subMesh._id];
  32147. if (!visibleInstances) {
  32148. return this;
  32149. }
  32150. var matricesCount = visibleInstances.length + 1;
  32151. var bufferSize = matricesCount * 16 * 4;
  32152. var currentInstancesBufferSize = this._instancesBufferSize;
  32153. var instancesBuffer = this._instancesBuffer;
  32154. while (this._instancesBufferSize < bufferSize) {
  32155. this._instancesBufferSize *= 2;
  32156. }
  32157. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32158. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32159. }
  32160. var offset = 0;
  32161. var instancesCount = 0;
  32162. var world = this.getWorldMatrix();
  32163. if (batch.renderSelf[subMesh._id]) {
  32164. world.copyToArray(this._instancesData, offset);
  32165. offset += 16;
  32166. instancesCount++;
  32167. }
  32168. if (visibleInstances) {
  32169. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32170. var instance = visibleInstances[instanceIndex];
  32171. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32172. offset += 16;
  32173. instancesCount++;
  32174. }
  32175. }
  32176. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32177. if (instancesBuffer) {
  32178. instancesBuffer.dispose();
  32179. }
  32180. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32181. this._instancesBuffer = instancesBuffer;
  32182. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32183. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32184. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32185. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32186. }
  32187. else {
  32188. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32189. }
  32190. this._bind(subMesh, effect, fillMode);
  32191. this._draw(subMesh, fillMode, instancesCount);
  32192. engine.unbindInstanceAttributes();
  32193. return this;
  32194. };
  32195. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32196. var scene = this.getScene();
  32197. var engine = scene.getEngine();
  32198. if (hardwareInstancedRendering) {
  32199. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32200. }
  32201. else {
  32202. if (batch.renderSelf[subMesh._id]) {
  32203. // Draw
  32204. if (onBeforeDraw) {
  32205. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32206. }
  32207. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32208. }
  32209. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32210. if (visibleInstancesForSubMesh) {
  32211. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32212. var instance = visibleInstancesForSubMesh[instanceIndex];
  32213. // World
  32214. var world = instance.getWorldMatrix();
  32215. if (onBeforeDraw) {
  32216. onBeforeDraw(true, world, effectiveMaterial);
  32217. }
  32218. // Draw
  32219. this._draw(subMesh, fillMode);
  32220. }
  32221. }
  32222. }
  32223. return this;
  32224. };
  32225. /**
  32226. * Triggers the draw call for the mesh.
  32227. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32228. * Returns the Mesh.
  32229. */
  32230. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32231. this._checkOcclusionQuery();
  32232. if (this._isOccluded) {
  32233. return this;
  32234. }
  32235. var scene = this.getScene();
  32236. // Managing instances
  32237. var batch = this._getInstancesRenderList(subMesh._id);
  32238. if (batch.mustReturn) {
  32239. return this;
  32240. }
  32241. // Checking geometry state
  32242. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32243. return this;
  32244. }
  32245. this.onBeforeRenderObservable.notifyObservers(this);
  32246. var engine = scene.getEngine();
  32247. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32248. // Material
  32249. var material = subMesh.getMaterial();
  32250. if (!material) {
  32251. return this;
  32252. }
  32253. this._effectiveMaterial = material;
  32254. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32255. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32256. return this;
  32257. }
  32258. }
  32259. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32260. return this;
  32261. }
  32262. // Alpha mode
  32263. if (enableAlphaMode) {
  32264. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32265. }
  32266. // Outline - step 1
  32267. var savedDepthWrite = engine.getDepthWrite();
  32268. if (this.renderOutline) {
  32269. engine.setDepthWrite(false);
  32270. scene.getOutlineRenderer().render(subMesh, batch);
  32271. engine.setDepthWrite(savedDepthWrite);
  32272. }
  32273. var effect;
  32274. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32275. effect = subMesh.effect;
  32276. }
  32277. else {
  32278. effect = this._effectiveMaterial.getEffect();
  32279. }
  32280. if (!effect) {
  32281. return this;
  32282. }
  32283. var sideOrientation = this.overrideMaterialSideOrientation;
  32284. if (sideOrientation == null) {
  32285. sideOrientation = this._effectiveMaterial.sideOrientation;
  32286. if (this._getWorldMatrixDeterminant() < 0) {
  32287. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32288. }
  32289. }
  32290. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32291. if (this._effectiveMaterial.forceDepthWrite) {
  32292. engine.setDepthWrite(true);
  32293. }
  32294. // Bind
  32295. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32296. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32297. this._bind(subMesh, effect, fillMode);
  32298. }
  32299. var world = this.getWorldMatrix();
  32300. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32301. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32302. }
  32303. else {
  32304. this._effectiveMaterial.bind(world, this);
  32305. }
  32306. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32307. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32308. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32309. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32310. }
  32311. // Draw
  32312. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32313. // Unbind
  32314. this._effectiveMaterial.unbind();
  32315. // Outline - step 2
  32316. if (this.renderOutline && savedDepthWrite) {
  32317. engine.setDepthWrite(true);
  32318. engine.setColorWrite(false);
  32319. scene.getOutlineRenderer().render(subMesh, batch);
  32320. engine.setColorWrite(true);
  32321. }
  32322. // Overlay
  32323. if (this.renderOverlay) {
  32324. var currentMode = engine.getAlphaMode();
  32325. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32326. scene.getOutlineRenderer().render(subMesh, batch, true);
  32327. engine.setAlphaMode(currentMode);
  32328. }
  32329. this.onAfterRenderObservable.notifyObservers(this);
  32330. return this;
  32331. };
  32332. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32333. if (isInstance && effectiveMaterial) {
  32334. effectiveMaterial.bindOnlyWorldMatrix(world);
  32335. }
  32336. };
  32337. /**
  32338. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32339. */
  32340. Mesh.prototype.getEmittedParticleSystems = function () {
  32341. var results = new Array();
  32342. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32343. var particleSystem = this.getScene().particleSystems[index];
  32344. if (particleSystem.emitter === this) {
  32345. results.push(particleSystem);
  32346. }
  32347. }
  32348. return results;
  32349. };
  32350. /**
  32351. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32352. */
  32353. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32354. var results = new Array();
  32355. var descendants = this.getDescendants();
  32356. descendants.push(this);
  32357. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32358. var particleSystem = this.getScene().particleSystems[index];
  32359. var emitter = particleSystem.emitter;
  32360. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32361. results.push(particleSystem);
  32362. }
  32363. }
  32364. return results;
  32365. };
  32366. /**
  32367. * Normalize matrix weights so that all vertices have a total weight set to 1
  32368. */
  32369. Mesh.prototype.cleanMatrixWeights = function () {
  32370. var epsilon = 1e-3;
  32371. var noInfluenceBoneIndex = 0.0;
  32372. if (this.skeleton) {
  32373. noInfluenceBoneIndex = this.skeleton.bones.length;
  32374. }
  32375. else {
  32376. return;
  32377. }
  32378. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32379. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32380. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32381. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32382. var influencers = this.numBoneInfluencers;
  32383. var size = matricesWeights.length;
  32384. for (var i = 0; i < size; i += 4) {
  32385. var weight = 0.0;
  32386. var firstZeroWeight = -1;
  32387. for (var j = 0; j < 4; j++) {
  32388. var w = matricesWeights[i + j];
  32389. weight += w;
  32390. if (w < epsilon && firstZeroWeight < 0) {
  32391. firstZeroWeight = j;
  32392. }
  32393. }
  32394. if (matricesWeightsExtra) {
  32395. for (var j = 0; j < 4; j++) {
  32396. var w = matricesWeightsExtra[i + j];
  32397. weight += w;
  32398. if (w < epsilon && firstZeroWeight < 0) {
  32399. firstZeroWeight = j + 4;
  32400. }
  32401. }
  32402. }
  32403. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32404. firstZeroWeight = influencers - 1;
  32405. }
  32406. if (weight > epsilon) {
  32407. var mweight = 1.0 / weight;
  32408. for (var j = 0; j < 4; j++) {
  32409. matricesWeights[i + j] *= mweight;
  32410. }
  32411. if (matricesWeightsExtra) {
  32412. for (var j = 0; j < 4; j++) {
  32413. matricesWeightsExtra[i + j] *= mweight;
  32414. }
  32415. }
  32416. }
  32417. else {
  32418. if (firstZeroWeight >= 4) {
  32419. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32420. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32421. }
  32422. else {
  32423. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32424. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32425. }
  32426. }
  32427. }
  32428. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32429. if (matricesIndicesExtra) {
  32430. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32431. }
  32432. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32433. if (matricesWeightsExtra) {
  32434. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32435. }
  32436. };
  32437. Mesh.prototype._checkDelayState = function () {
  32438. var scene = this.getScene();
  32439. if (this._geometry) {
  32440. this._geometry.load(scene);
  32441. }
  32442. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32443. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32444. this._queueLoad(scene);
  32445. }
  32446. return this;
  32447. };
  32448. Mesh.prototype._queueLoad = function (scene) {
  32449. var _this = this;
  32450. scene._addPendingData(this);
  32451. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32452. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32453. if (data instanceof ArrayBuffer) {
  32454. _this._delayLoadingFunction(data, _this);
  32455. }
  32456. else {
  32457. _this._delayLoadingFunction(JSON.parse(data), _this);
  32458. }
  32459. _this.instances.forEach(function (instance) {
  32460. instance._syncSubMeshes();
  32461. });
  32462. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32463. scene._removePendingData(_this);
  32464. }, function () { }, scene.database, getBinaryData);
  32465. return this;
  32466. };
  32467. /**
  32468. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32469. */
  32470. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32471. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32472. return false;
  32473. }
  32474. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32475. return false;
  32476. }
  32477. this._checkDelayState();
  32478. return true;
  32479. };
  32480. /**
  32481. * Sets the mesh material by the material or multiMaterial `id` property.
  32482. * The material `id` is a string identifying the material or the multiMaterial.
  32483. * This method returns the Mesh.
  32484. */
  32485. Mesh.prototype.setMaterialByID = function (id) {
  32486. var materials = this.getScene().materials;
  32487. var index;
  32488. for (index = materials.length - 1; index > -1; index--) {
  32489. if (materials[index].id === id) {
  32490. this.material = materials[index];
  32491. return this;
  32492. }
  32493. }
  32494. // Multi
  32495. var multiMaterials = this.getScene().multiMaterials;
  32496. for (index = multiMaterials.length - 1; index > -1; index--) {
  32497. if (multiMaterials[index].id === id) {
  32498. this.material = multiMaterials[index];
  32499. return this;
  32500. }
  32501. }
  32502. return this;
  32503. };
  32504. /**
  32505. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32506. */
  32507. Mesh.prototype.getAnimatables = function () {
  32508. var results = new Array();
  32509. if (this.material) {
  32510. results.push(this.material);
  32511. }
  32512. if (this.skeleton) {
  32513. results.push(this.skeleton);
  32514. }
  32515. return results;
  32516. };
  32517. /**
  32518. * Modifies the mesh geometry according to the passed transformation matrix.
  32519. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32520. * The mesh normals are modified accordingly the same transformation.
  32521. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32522. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32523. * Returns the Mesh.
  32524. */
  32525. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32526. // Position
  32527. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32528. return this;
  32529. }
  32530. var submeshes = this.subMeshes.splice(0);
  32531. this._resetPointsArrayCache();
  32532. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32533. var temp = new Array();
  32534. var index;
  32535. for (index = 0; index < data.length; index += 3) {
  32536. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32537. }
  32538. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32539. // Normals
  32540. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32541. return this;
  32542. }
  32543. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32544. temp = [];
  32545. for (index = 0; index < data.length; index += 3) {
  32546. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32547. }
  32548. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32549. // flip faces?
  32550. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32551. this.flipFaces();
  32552. }
  32553. // Restore submeshes
  32554. this.releaseSubMeshes();
  32555. this.subMeshes = submeshes;
  32556. return this;
  32557. };
  32558. /**
  32559. * Modifies the mesh geometry according to its own current World Matrix.
  32560. * The mesh World Matrix is then reset.
  32561. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32562. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32563. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32564. * Returns the Mesh.
  32565. */
  32566. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32567. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32568. this.scaling.copyFromFloats(1, 1, 1);
  32569. this.position.copyFromFloats(0, 0, 0);
  32570. this.rotation.copyFromFloats(0, 0, 0);
  32571. //only if quaternion is already set
  32572. if (this.rotationQuaternion) {
  32573. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32574. }
  32575. this._worldMatrix = BABYLON.Matrix.Identity();
  32576. return this;
  32577. };
  32578. Object.defineProperty(Mesh.prototype, "_positions", {
  32579. // Cache
  32580. get: function () {
  32581. if (this._geometry) {
  32582. return this._geometry._positions;
  32583. }
  32584. return null;
  32585. },
  32586. enumerable: true,
  32587. configurable: true
  32588. });
  32589. Mesh.prototype._resetPointsArrayCache = function () {
  32590. if (this._geometry) {
  32591. this._geometry._resetPointsArrayCache();
  32592. }
  32593. return this;
  32594. };
  32595. Mesh.prototype._generatePointsArray = function () {
  32596. if (this._geometry) {
  32597. return this._geometry._generatePointsArray();
  32598. }
  32599. return false;
  32600. };
  32601. /**
  32602. * Returns a new Mesh object generated from the current mesh properties.
  32603. * This method must not get confused with createInstance().
  32604. * The parameter `name` is a string, the name given to the new mesh.
  32605. * The optional parameter `newParent` can be any Node object (default `null`).
  32606. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32607. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32608. */
  32609. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32610. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32611. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32612. };
  32613. /**
  32614. * Releases resources associated with this mesh.
  32615. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32616. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32617. */
  32618. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32619. var _this = this;
  32620. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32621. this.morphTargetManager = null;
  32622. if (this._geometry) {
  32623. this._geometry.releaseForMesh(this, true);
  32624. }
  32625. // Sources
  32626. var meshes = this.getScene().meshes;
  32627. meshes.forEach(function (abstractMesh) {
  32628. var mesh = abstractMesh;
  32629. if (mesh._source && mesh._source === _this) {
  32630. mesh._source = null;
  32631. }
  32632. });
  32633. this._source = null;
  32634. // Instances
  32635. if (this._instancesBuffer) {
  32636. this._instancesBuffer.dispose();
  32637. this._instancesBuffer = null;
  32638. }
  32639. while (this.instances.length) {
  32640. this.instances[0].dispose();
  32641. }
  32642. // Effect layers.
  32643. var effectLayers = this.getScene().effectLayers;
  32644. for (var i = 0; i < effectLayers.length; i++) {
  32645. var effectLayer = effectLayers[i];
  32646. if (effectLayer) {
  32647. effectLayer._disposeMesh(this);
  32648. }
  32649. }
  32650. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32651. };
  32652. /**
  32653. * Modifies the mesh geometry according to a displacement map.
  32654. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  32655. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32656. * This method returns nothing.
  32657. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32658. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32659. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32660. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32661. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32662. *
  32663. * Returns the Mesh.
  32664. */
  32665. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32666. var _this = this;
  32667. var scene = this.getScene();
  32668. var onload = function (img) {
  32669. // Getting height map data
  32670. var canvas = document.createElement("canvas");
  32671. var context = canvas.getContext("2d");
  32672. var heightMapWidth = img.width;
  32673. var heightMapHeight = img.height;
  32674. canvas.width = heightMapWidth;
  32675. canvas.height = heightMapHeight;
  32676. context.drawImage(img, 0, 0);
  32677. // Create VertexData from map data
  32678. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32679. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32680. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32681. //execute success callback, if set
  32682. if (onSuccess) {
  32683. onSuccess(_this);
  32684. }
  32685. };
  32686. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32687. return this;
  32688. };
  32689. /**
  32690. * Modifies the mesh geometry according to a displacementMap buffer.
  32691. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  32692. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32693. * This method returns nothing.
  32694. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32695. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32696. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32697. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32698. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32699. *
  32700. * Returns the Mesh.
  32701. */
  32702. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32703. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32704. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32705. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32706. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32707. return this;
  32708. }
  32709. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32710. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32711. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32712. var position = BABYLON.Vector3.Zero();
  32713. var normal = BABYLON.Vector3.Zero();
  32714. var uv = BABYLON.Vector2.Zero();
  32715. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32716. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32717. for (var index = 0; index < positions.length; index += 3) {
  32718. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32719. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32720. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32721. // Compute height
  32722. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32723. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32724. var pos = (u + v * heightMapWidth) * 4;
  32725. var r = buffer[pos] / 255.0;
  32726. var g = buffer[pos + 1] / 255.0;
  32727. var b = buffer[pos + 2] / 255.0;
  32728. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32729. normal.normalize();
  32730. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32731. position = position.add(normal);
  32732. position.toArray(positions, index);
  32733. }
  32734. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32735. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32736. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32737. return this;
  32738. };
  32739. /**
  32740. * Modify the mesh to get a flat shading rendering.
  32741. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32742. * This method returns the Mesh.
  32743. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32744. */
  32745. Mesh.prototype.convertToFlatShadedMesh = function () {
  32746. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32747. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32748. var kinds = this.getVerticesDataKinds();
  32749. var vbs = {};
  32750. var data = {};
  32751. var newdata = {};
  32752. var updatableNormals = false;
  32753. var kindIndex;
  32754. var kind;
  32755. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32756. kind = kinds[kindIndex];
  32757. var vertexBuffer = this.getVertexBuffer(kind);
  32758. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32759. updatableNormals = vertexBuffer.isUpdatable();
  32760. kinds.splice(kindIndex, 1);
  32761. kindIndex--;
  32762. continue;
  32763. }
  32764. vbs[kind] = vertexBuffer;
  32765. data[kind] = vbs[kind].getData();
  32766. newdata[kind] = [];
  32767. }
  32768. // Save previous submeshes
  32769. var previousSubmeshes = this.subMeshes.slice(0);
  32770. var indices = this.getIndices();
  32771. var totalIndices = this.getTotalIndices();
  32772. // Generating unique vertices per face
  32773. var index;
  32774. for (index = 0; index < totalIndices; index++) {
  32775. var vertexIndex = indices[index];
  32776. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32777. kind = kinds[kindIndex];
  32778. var stride = vbs[kind].getStrideSize();
  32779. for (var offset = 0; offset < stride; offset++) {
  32780. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32781. }
  32782. }
  32783. }
  32784. // Updating faces & normal
  32785. var normals = [];
  32786. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32787. for (index = 0; index < totalIndices; index += 3) {
  32788. indices[index] = index;
  32789. indices[index + 1] = index + 1;
  32790. indices[index + 2] = index + 2;
  32791. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32792. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32793. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32794. var p1p2 = p1.subtract(p2);
  32795. var p3p2 = p3.subtract(p2);
  32796. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32797. // Store same normals for every vertex
  32798. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32799. normals.push(normal.x);
  32800. normals.push(normal.y);
  32801. normals.push(normal.z);
  32802. }
  32803. }
  32804. this.setIndices(indices);
  32805. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32806. // Updating vertex buffers
  32807. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32808. kind = kinds[kindIndex];
  32809. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32810. }
  32811. // Updating submeshes
  32812. this.releaseSubMeshes();
  32813. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32814. var previousOne = previousSubmeshes[submeshIndex];
  32815. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32816. }
  32817. this.synchronizeInstances();
  32818. return this;
  32819. };
  32820. /**
  32821. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32822. * In other words, more vertices, no more indices and a single bigger VBO.
  32823. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32824. * Returns the Mesh.
  32825. */
  32826. Mesh.prototype.convertToUnIndexedMesh = function () {
  32827. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32828. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32829. var kinds = this.getVerticesDataKinds();
  32830. var vbs = {};
  32831. var data = {};
  32832. var newdata = {};
  32833. var kindIndex;
  32834. var kind;
  32835. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32836. kind = kinds[kindIndex];
  32837. var vertexBuffer = this.getVertexBuffer(kind);
  32838. vbs[kind] = vertexBuffer;
  32839. data[kind] = vbs[kind].getData();
  32840. newdata[kind] = [];
  32841. }
  32842. // Save previous submeshes
  32843. var previousSubmeshes = this.subMeshes.slice(0);
  32844. var indices = this.getIndices();
  32845. var totalIndices = this.getTotalIndices();
  32846. // Generating unique vertices per face
  32847. var index;
  32848. for (index = 0; index < totalIndices; index++) {
  32849. var vertexIndex = indices[index];
  32850. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32851. kind = kinds[kindIndex];
  32852. var stride = vbs[kind].getStrideSize();
  32853. for (var offset = 0; offset < stride; offset++) {
  32854. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32855. }
  32856. }
  32857. }
  32858. // Updating indices
  32859. for (index = 0; index < totalIndices; index += 3) {
  32860. indices[index] = index;
  32861. indices[index + 1] = index + 1;
  32862. indices[index + 2] = index + 2;
  32863. }
  32864. this.setIndices(indices);
  32865. // Updating vertex buffers
  32866. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32867. kind = kinds[kindIndex];
  32868. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32869. }
  32870. // Updating submeshes
  32871. this.releaseSubMeshes();
  32872. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32873. var previousOne = previousSubmeshes[submeshIndex];
  32874. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32875. }
  32876. this._unIndexed = true;
  32877. this.synchronizeInstances();
  32878. return this;
  32879. };
  32880. /**
  32881. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32882. * This method returns the Mesh.
  32883. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32884. */
  32885. Mesh.prototype.flipFaces = function (flipNormals) {
  32886. if (flipNormals === void 0) { flipNormals = false; }
  32887. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32888. var i;
  32889. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32890. for (i = 0; i < vertex_data.normals.length; i++) {
  32891. vertex_data.normals[i] *= -1;
  32892. }
  32893. }
  32894. if (vertex_data.indices) {
  32895. var temp;
  32896. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32897. // reassign indices
  32898. temp = vertex_data.indices[i + 1];
  32899. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32900. vertex_data.indices[i + 2] = temp;
  32901. }
  32902. }
  32903. vertex_data.applyToMesh(this);
  32904. return this;
  32905. };
  32906. // Instances
  32907. /**
  32908. * Creates a new InstancedMesh object from the mesh model.
  32909. * An instance shares the same properties and the same material than its model.
  32910. * Only these properties of each instance can then be set individually :
  32911. * - position
  32912. * - rotation
  32913. * - rotationQuaternion
  32914. * - setPivotMatrix
  32915. * - scaling
  32916. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32917. * Warning : this method is not supported for Line mesh and LineSystem
  32918. */
  32919. Mesh.prototype.createInstance = function (name) {
  32920. return new BABYLON.InstancedMesh(name, this);
  32921. };
  32922. /**
  32923. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32924. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32925. * This method returns the Mesh.
  32926. */
  32927. Mesh.prototype.synchronizeInstances = function () {
  32928. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32929. var instance = this.instances[instanceIndex];
  32930. instance._syncSubMeshes();
  32931. }
  32932. return this;
  32933. };
  32934. /**
  32935. * Simplify the mesh according to the given array of settings.
  32936. * Function will return immediately and will simplify async. It returns the Mesh.
  32937. * @param settings a collection of simplification settings.
  32938. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32939. * @param type the type of simplification to run.
  32940. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32941. */
  32942. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32943. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32944. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32945. this.getScene().simplificationQueue.addTask({
  32946. settings: settings,
  32947. parallelProcessing: parallelProcessing,
  32948. mesh: this,
  32949. simplificationType: simplificationType,
  32950. successCallback: successCallback
  32951. });
  32952. return this;
  32953. };
  32954. /**
  32955. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32956. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32957. * This should be used together with the simplification to avoid disappearing triangles.
  32958. * Returns the Mesh.
  32959. * @param successCallback an optional success callback to be called after the optimization finished.
  32960. */
  32961. Mesh.prototype.optimizeIndices = function (successCallback) {
  32962. var _this = this;
  32963. var indices = this.getIndices();
  32964. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32965. if (!positions || !indices) {
  32966. return this;
  32967. }
  32968. var vectorPositions = new Array();
  32969. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32970. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32971. }
  32972. var dupes = new Array();
  32973. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32974. var realPos = vectorPositions.length - 1 - iteration;
  32975. var testedPosition = vectorPositions[realPos];
  32976. for (var j = 0; j < realPos; ++j) {
  32977. var againstPosition = vectorPositions[j];
  32978. if (testedPosition.equals(againstPosition)) {
  32979. dupes[realPos] = j;
  32980. break;
  32981. }
  32982. }
  32983. }, function () {
  32984. for (var i = 0; i < indices.length; ++i) {
  32985. indices[i] = dupes[indices[i]] || indices[i];
  32986. }
  32987. //indices are now reordered
  32988. var originalSubMeshes = _this.subMeshes.slice(0);
  32989. _this.setIndices(indices);
  32990. _this.subMeshes = originalSubMeshes;
  32991. if (successCallback) {
  32992. successCallback(_this);
  32993. }
  32994. });
  32995. return this;
  32996. };
  32997. Mesh.prototype.serialize = function (serializationObject) {
  32998. serializationObject.name = this.name;
  32999. serializationObject.id = this.id;
  33000. serializationObject.type = this.getClassName();
  33001. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33002. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33003. }
  33004. serializationObject.position = this.position.asArray();
  33005. if (this.rotationQuaternion) {
  33006. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33007. }
  33008. else if (this.rotation) {
  33009. serializationObject.rotation = this.rotation.asArray();
  33010. }
  33011. serializationObject.scaling = this.scaling.asArray();
  33012. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33013. serializationObject.isEnabled = this.isEnabled(false);
  33014. serializationObject.isVisible = this.isVisible;
  33015. serializationObject.infiniteDistance = this.infiniteDistance;
  33016. serializationObject.pickable = this.isPickable;
  33017. serializationObject.receiveShadows = this.receiveShadows;
  33018. serializationObject.billboardMode = this.billboardMode;
  33019. serializationObject.visibility = this.visibility;
  33020. serializationObject.checkCollisions = this.checkCollisions;
  33021. serializationObject.isBlocker = this.isBlocker;
  33022. // Parent
  33023. if (this.parent) {
  33024. serializationObject.parentId = this.parent.id;
  33025. }
  33026. // Geometry
  33027. serializationObject.isUnIndexed = this.isUnIndexed;
  33028. var geometry = this._geometry;
  33029. if (geometry) {
  33030. var geometryId = geometry.id;
  33031. serializationObject.geometryId = geometryId;
  33032. // SubMeshes
  33033. serializationObject.subMeshes = [];
  33034. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33035. var subMesh = this.subMeshes[subIndex];
  33036. serializationObject.subMeshes.push({
  33037. materialIndex: subMesh.materialIndex,
  33038. verticesStart: subMesh.verticesStart,
  33039. verticesCount: subMesh.verticesCount,
  33040. indexStart: subMesh.indexStart,
  33041. indexCount: subMesh.indexCount
  33042. });
  33043. }
  33044. }
  33045. // Material
  33046. if (this.material) {
  33047. serializationObject.materialId = this.material.id;
  33048. }
  33049. else {
  33050. this.material = null;
  33051. }
  33052. // Morph targets
  33053. if (this.morphTargetManager) {
  33054. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33055. }
  33056. // Skeleton
  33057. if (this.skeleton) {
  33058. serializationObject.skeletonId = this.skeleton.id;
  33059. }
  33060. // Physics
  33061. //TODO implement correct serialization for physics impostors.
  33062. var impostor = this.getPhysicsImpostor();
  33063. if (impostor) {
  33064. serializationObject.physicsMass = impostor.getParam("mass");
  33065. serializationObject.physicsFriction = impostor.getParam("friction");
  33066. serializationObject.physicsRestitution = impostor.getParam("mass");
  33067. serializationObject.physicsImpostor = impostor.type;
  33068. }
  33069. // Metadata
  33070. if (this.metadata) {
  33071. serializationObject.metadata = this.metadata;
  33072. }
  33073. // Instances
  33074. serializationObject.instances = [];
  33075. for (var index = 0; index < this.instances.length; index++) {
  33076. var instance = this.instances[index];
  33077. var serializationInstance = {
  33078. name: instance.name,
  33079. id: instance.id,
  33080. position: instance.position.asArray(),
  33081. scaling: instance.scaling.asArray()
  33082. };
  33083. if (instance.rotationQuaternion) {
  33084. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33085. }
  33086. else if (instance.rotation) {
  33087. serializationInstance.rotation = instance.rotation.asArray();
  33088. }
  33089. serializationObject.instances.push(serializationInstance);
  33090. // Animations
  33091. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33092. serializationInstance.ranges = instance.serializeAnimationRanges();
  33093. }
  33094. //
  33095. // Animations
  33096. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33097. serializationObject.ranges = this.serializeAnimationRanges();
  33098. // Layer mask
  33099. serializationObject.layerMask = this.layerMask;
  33100. // Alpha
  33101. serializationObject.alphaIndex = this.alphaIndex;
  33102. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33103. // Overlay
  33104. serializationObject.overlayAlpha = this.overlayAlpha;
  33105. serializationObject.overlayColor = this.overlayColor.asArray();
  33106. serializationObject.renderOverlay = this.renderOverlay;
  33107. // Fog
  33108. serializationObject.applyFog = this.applyFog;
  33109. // Action Manager
  33110. if (this.actionManager) {
  33111. serializationObject.actions = this.actionManager.serialize(this.name);
  33112. }
  33113. };
  33114. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33115. if (!this.geometry) {
  33116. return;
  33117. }
  33118. this._markSubMeshesAsAttributesDirty();
  33119. var morphTargetManager = this._morphTargetManager;
  33120. if (morphTargetManager && morphTargetManager.vertexCount) {
  33121. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33122. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33123. this.morphTargetManager = null;
  33124. return;
  33125. }
  33126. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33127. var morphTarget = morphTargetManager.getActiveTarget(index);
  33128. var positions = morphTarget.getPositions();
  33129. if (!positions) {
  33130. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33131. return;
  33132. }
  33133. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33134. var normals = morphTarget.getNormals();
  33135. if (normals) {
  33136. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33137. }
  33138. var tangents = morphTarget.getTangents();
  33139. if (tangents) {
  33140. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33141. }
  33142. }
  33143. }
  33144. else {
  33145. var index = 0;
  33146. // Positions
  33147. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33148. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33149. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33150. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33151. }
  33152. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33153. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33154. }
  33155. index++;
  33156. }
  33157. }
  33158. };
  33159. // Statics
  33160. /**
  33161. * Returns a new Mesh object parsed from the source provided.
  33162. * The parameter `parsedMesh` is the source.
  33163. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33164. */
  33165. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33166. var mesh;
  33167. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33168. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33169. }
  33170. else {
  33171. mesh = new Mesh(parsedMesh.name, scene);
  33172. }
  33173. mesh.id = parsedMesh.id;
  33174. if (BABYLON.Tags) {
  33175. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33176. }
  33177. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33178. if (parsedMesh.metadata !== undefined) {
  33179. mesh.metadata = parsedMesh.metadata;
  33180. }
  33181. if (parsedMesh.rotationQuaternion) {
  33182. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33183. }
  33184. else if (parsedMesh.rotation) {
  33185. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33186. }
  33187. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33188. if (parsedMesh.localMatrix) {
  33189. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33190. }
  33191. else if (parsedMesh.pivotMatrix) {
  33192. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33193. }
  33194. mesh.setEnabled(parsedMesh.isEnabled);
  33195. mesh.isVisible = parsedMesh.isVisible;
  33196. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33197. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33198. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33199. if (parsedMesh.applyFog !== undefined) {
  33200. mesh.applyFog = parsedMesh.applyFog;
  33201. }
  33202. if (parsedMesh.pickable !== undefined) {
  33203. mesh.isPickable = parsedMesh.pickable;
  33204. }
  33205. if (parsedMesh.alphaIndex !== undefined) {
  33206. mesh.alphaIndex = parsedMesh.alphaIndex;
  33207. }
  33208. mesh.receiveShadows = parsedMesh.receiveShadows;
  33209. mesh.billboardMode = parsedMesh.billboardMode;
  33210. if (parsedMesh.visibility !== undefined) {
  33211. mesh.visibility = parsedMesh.visibility;
  33212. }
  33213. mesh.checkCollisions = parsedMesh.checkCollisions;
  33214. if (parsedMesh.isBlocker !== undefined) {
  33215. mesh.isBlocker = parsedMesh.isBlocker;
  33216. }
  33217. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33218. // freezeWorldMatrix
  33219. if (parsedMesh.freezeWorldMatrix) {
  33220. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33221. }
  33222. // Parent
  33223. if (parsedMesh.parentId) {
  33224. mesh._waitingParentId = parsedMesh.parentId;
  33225. }
  33226. // Actions
  33227. if (parsedMesh.actions !== undefined) {
  33228. mesh._waitingActions = parsedMesh.actions;
  33229. }
  33230. // Overlay
  33231. if (parsedMesh.overlayAlpha !== undefined) {
  33232. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33233. }
  33234. if (parsedMesh.overlayColor !== undefined) {
  33235. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33236. }
  33237. if (parsedMesh.renderOverlay !== undefined) {
  33238. mesh.renderOverlay = parsedMesh.renderOverlay;
  33239. }
  33240. // Geometry
  33241. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33242. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33243. if (parsedMesh.delayLoadingFile) {
  33244. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33245. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33246. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33247. if (parsedMesh._binaryInfo) {
  33248. mesh._binaryInfo = parsedMesh._binaryInfo;
  33249. }
  33250. mesh._delayInfo = [];
  33251. if (parsedMesh.hasUVs) {
  33252. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33253. }
  33254. if (parsedMesh.hasUVs2) {
  33255. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33256. }
  33257. if (parsedMesh.hasUVs3) {
  33258. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33259. }
  33260. if (parsedMesh.hasUVs4) {
  33261. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33262. }
  33263. if (parsedMesh.hasUVs5) {
  33264. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33265. }
  33266. if (parsedMesh.hasUVs6) {
  33267. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33268. }
  33269. if (parsedMesh.hasColors) {
  33270. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33271. }
  33272. if (parsedMesh.hasMatricesIndices) {
  33273. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33274. }
  33275. if (parsedMesh.hasMatricesWeights) {
  33276. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33277. }
  33278. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33279. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33280. mesh._checkDelayState();
  33281. }
  33282. }
  33283. else {
  33284. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33285. }
  33286. // Material
  33287. if (parsedMesh.materialId) {
  33288. mesh.setMaterialByID(parsedMesh.materialId);
  33289. }
  33290. else {
  33291. mesh.material = null;
  33292. }
  33293. // Morph targets
  33294. if (parsedMesh.morphTargetManagerId > -1) {
  33295. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33296. }
  33297. // Skeleton
  33298. if (parsedMesh.skeletonId > -1) {
  33299. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33300. if (parsedMesh.numBoneInfluencers) {
  33301. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33302. }
  33303. }
  33304. // Animations
  33305. if (parsedMesh.animations) {
  33306. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33307. var parsedAnimation = parsedMesh.animations[animationIndex];
  33308. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33309. }
  33310. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33311. }
  33312. if (parsedMesh.autoAnimate) {
  33313. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33314. }
  33315. // Layer Mask
  33316. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33317. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33318. }
  33319. else {
  33320. mesh.layerMask = 0x0FFFFFFF;
  33321. }
  33322. // Physics
  33323. if (parsedMesh.physicsImpostor) {
  33324. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33325. mass: parsedMesh.physicsMass,
  33326. friction: parsedMesh.physicsFriction,
  33327. restitution: parsedMesh.physicsRestitution
  33328. }, scene);
  33329. }
  33330. // Instances
  33331. if (parsedMesh.instances) {
  33332. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33333. var parsedInstance = parsedMesh.instances[index];
  33334. var instance = mesh.createInstance(parsedInstance.name);
  33335. if (parsedInstance.id) {
  33336. instance.id = parsedInstance.id;
  33337. }
  33338. if (BABYLON.Tags) {
  33339. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33340. }
  33341. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33342. if (parsedInstance.parentId) {
  33343. instance._waitingParentId = parsedInstance.parentId;
  33344. }
  33345. if (parsedInstance.rotationQuaternion) {
  33346. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33347. }
  33348. else if (parsedInstance.rotation) {
  33349. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33350. }
  33351. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33352. instance.checkCollisions = mesh.checkCollisions;
  33353. if (parsedMesh.animations) {
  33354. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33355. parsedAnimation = parsedMesh.animations[animationIndex];
  33356. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33357. }
  33358. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33359. }
  33360. }
  33361. }
  33362. return mesh;
  33363. };
  33364. /**
  33365. * Creates a ribbon mesh.
  33366. * Please consider using the same method from the MeshBuilder class instead.
  33367. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33368. *
  33369. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33370. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33371. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33372. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33373. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  33374. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33375. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  33376. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33377. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33378. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33379. */
  33380. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33381. if (closeArray === void 0) { closeArray = false; }
  33382. if (updatable === void 0) { updatable = false; }
  33383. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33384. pathArray: pathArray,
  33385. closeArray: closeArray,
  33386. closePath: closePath,
  33387. offset: offset,
  33388. updatable: updatable,
  33389. sideOrientation: sideOrientation,
  33390. instance: instance
  33391. }, scene);
  33392. };
  33393. /**
  33394. * Creates a plane polygonal mesh. By default, this is a disc.
  33395. * Please consider using the same method from the MeshBuilder class instead.
  33396. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33397. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  33398. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33399. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33401. */
  33402. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33403. if (scene === void 0) { scene = null; }
  33404. var options = {
  33405. radius: radius,
  33406. tessellation: tessellation,
  33407. sideOrientation: sideOrientation,
  33408. updatable: updatable
  33409. };
  33410. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33411. };
  33412. /**
  33413. * Creates a box mesh.
  33414. * Please consider using the same method from the MeshBuilder class instead.
  33415. * The parameter `size` sets the size (float) of each box side (default 1).
  33416. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33417. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33419. */
  33420. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33421. if (scene === void 0) { scene = null; }
  33422. var options = {
  33423. size: size,
  33424. sideOrientation: sideOrientation,
  33425. updatable: updatable
  33426. };
  33427. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33428. };
  33429. /**
  33430. * Creates a sphere mesh.
  33431. * Please consider using the same method from the MeshBuilder class instead.
  33432. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33433. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33434. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33435. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33436. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33437. */
  33438. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33439. var options = {
  33440. segments: segments,
  33441. diameterX: diameter,
  33442. diameterY: diameter,
  33443. diameterZ: diameter,
  33444. sideOrientation: sideOrientation,
  33445. updatable: updatable
  33446. };
  33447. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33448. };
  33449. /**
  33450. * Creates a cylinder or a cone mesh.
  33451. * Please consider using the same method from the MeshBuilder class instead.
  33452. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33453. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33454. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  33455. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33456. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33457. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33458. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33460. */
  33461. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33462. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33463. if (scene !== undefined) {
  33464. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33465. updatable = scene;
  33466. }
  33467. scene = subdivisions;
  33468. subdivisions = 1;
  33469. }
  33470. var options = {
  33471. height: height,
  33472. diameterTop: diameterTop,
  33473. diameterBottom: diameterBottom,
  33474. tessellation: tessellation,
  33475. subdivisions: subdivisions,
  33476. sideOrientation: sideOrientation,
  33477. updatable: updatable
  33478. };
  33479. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33480. };
  33481. // Torus (Code from SharpDX.org)
  33482. /**
  33483. * Creates a torus mesh.
  33484. * Please consider using the same method from the MeshBuilder class instead.
  33485. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33486. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33487. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33489. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33490. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33491. */
  33492. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33493. var options = {
  33494. diameter: diameter,
  33495. thickness: thickness,
  33496. tessellation: tessellation,
  33497. sideOrientation: sideOrientation,
  33498. updatable: updatable
  33499. };
  33500. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33501. };
  33502. /**
  33503. * Creates a torus knot mesh.
  33504. * Please consider using the same method from the MeshBuilder class instead.
  33505. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33506. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33507. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33508. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33509. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33510. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33512. */
  33513. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33514. var options = {
  33515. radius: radius,
  33516. tube: tube,
  33517. radialSegments: radialSegments,
  33518. tubularSegments: tubularSegments,
  33519. p: p,
  33520. q: q,
  33521. sideOrientation: sideOrientation,
  33522. updatable: updatable
  33523. };
  33524. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33525. };
  33526. /**
  33527. * Creates a line mesh.
  33528. * Please consider using the same method from the MeshBuilder class instead.
  33529. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  33530. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33531. * The parameter `points` is an array successive Vector3.
  33532. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  33533. * When updating an instance, remember that only point positions can change, not the number of points.
  33534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33535. */
  33536. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33537. if (scene === void 0) { scene = null; }
  33538. if (updatable === void 0) { updatable = false; }
  33539. if (instance === void 0) { instance = null; }
  33540. var options = {
  33541. points: points,
  33542. updatable: updatable,
  33543. instance: instance
  33544. };
  33545. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33546. };
  33547. /**
  33548. * Creates a dashed line mesh.
  33549. * Please consider using the same method from the MeshBuilder class instead.
  33550. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  33551. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33552. * The parameter `points` is an array successive Vector3.
  33553. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33554. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33555. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33556. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  33557. * When updating an instance, remember that only point positions can change, not the number of points.
  33558. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33559. */
  33560. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33561. if (scene === void 0) { scene = null; }
  33562. var options = {
  33563. points: points,
  33564. dashSize: dashSize,
  33565. gapSize: gapSize,
  33566. dashNb: dashNb,
  33567. updatable: updatable,
  33568. instance: instance
  33569. };
  33570. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33571. };
  33572. /**
  33573. * Creates a polygon mesh.
  33574. * Please consider using the same method from the MeshBuilder class instead.
  33575. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33576. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  33577. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33579. * Remember you can only change the shape positions, not their number when updating a polygon.
  33580. */
  33581. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33582. var options = {
  33583. shape: shape,
  33584. holes: holes,
  33585. updatable: updatable,
  33586. sideOrientation: sideOrientation
  33587. };
  33588. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33589. };
  33590. /**
  33591. * Creates an extruded polygon mesh, with depth in the Y direction.
  33592. * Please consider using the same method from the MeshBuilder class instead.
  33593. */
  33594. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33595. var options = {
  33596. shape: shape,
  33597. holes: holes,
  33598. depth: depth,
  33599. updatable: updatable,
  33600. sideOrientation: sideOrientation
  33601. };
  33602. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33603. };
  33604. /**
  33605. * Creates an extruded shape mesh.
  33606. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33607. * Please consider using the same method from the MeshBuilder class instead.
  33608. *
  33609. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33610. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  33611. * extruded along the Z axis.
  33612. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33613. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  33614. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33615. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33616. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  33617. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33619. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33621. */
  33622. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33623. if (scene === void 0) { scene = null; }
  33624. var options = {
  33625. shape: shape,
  33626. path: path,
  33627. scale: scale,
  33628. rotation: rotation,
  33629. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33630. sideOrientation: sideOrientation,
  33631. instance: instance,
  33632. updatable: updatable
  33633. };
  33634. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33635. };
  33636. /**
  33637. * Creates an custom extruded shape mesh.
  33638. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33639. * Please consider using the same method from the MeshBuilder class instead.
  33640. *
  33641. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33642. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  33643. * extruded along the Z axis.
  33644. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33645. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  33646. * and the distance of this point from the begining of the path :
  33647. * ```javascript
  33648. * var rotationFunction = function(i, distance) {
  33649. * // do things
  33650. * return rotationValue; }
  33651. * ```
  33652. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33653. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  33654. * and the distance of this point from the begining of the path :
  33655. * ```javascript
  33656. * var scaleFunction = function(i, distance) {
  33657. * // do things
  33658. * return scaleValue;}
  33659. * ```
  33660. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33661. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33662. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33663. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33664. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  33665. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33666. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33667. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33669. */
  33670. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33671. var options = {
  33672. shape: shape,
  33673. path: path,
  33674. scaleFunction: scaleFunction,
  33675. rotationFunction: rotationFunction,
  33676. ribbonCloseArray: ribbonCloseArray,
  33677. ribbonClosePath: ribbonClosePath,
  33678. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33679. sideOrientation: sideOrientation,
  33680. instance: instance,
  33681. updatable: updatable
  33682. };
  33683. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33684. };
  33685. /**
  33686. * Creates lathe mesh.
  33687. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33688. * Please consider using the same method from the MeshBuilder class instead.
  33689. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  33690. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33691. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33692. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33694. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33696. */
  33697. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33698. var options = {
  33699. shape: shape,
  33700. radius: radius,
  33701. tessellation: tessellation,
  33702. sideOrientation: sideOrientation,
  33703. updatable: updatable
  33704. };
  33705. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33706. };
  33707. /**
  33708. * Creates a plane mesh.
  33709. * Please consider using the same method from the MeshBuilder class instead.
  33710. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33711. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33712. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33714. */
  33715. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33716. var options = {
  33717. size: size,
  33718. width: size,
  33719. height: size,
  33720. sideOrientation: sideOrientation,
  33721. updatable: updatable
  33722. };
  33723. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33724. };
  33725. /**
  33726. * Creates a ground mesh.
  33727. * Please consider using the same method from the MeshBuilder class instead.
  33728. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33729. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33731. */
  33732. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33733. var options = {
  33734. width: width,
  33735. height: height,
  33736. subdivisions: subdivisions,
  33737. updatable: updatable
  33738. };
  33739. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33740. };
  33741. /**
  33742. * Creates a tiled ground mesh.
  33743. * Please consider using the same method from the MeshBuilder class instead.
  33744. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33745. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33746. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33747. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33748. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33749. * numbers of subdivisions on the ground width and height of each tile.
  33750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33751. */
  33752. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33753. var options = {
  33754. xmin: xmin,
  33755. zmin: zmin,
  33756. xmax: xmax,
  33757. zmax: zmax,
  33758. subdivisions: subdivisions,
  33759. precision: precision,
  33760. updatable: updatable
  33761. };
  33762. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33763. };
  33764. /**
  33765. * Creates a ground mesh from a height map.
  33766. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33767. * Please consider using the same method from the MeshBuilder class instead.
  33768. * The parameter `url` sets the URL of the height map image resource.
  33769. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33770. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33771. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33772. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33773. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  33774. * This function is passed the newly built mesh :
  33775. * ```javascript
  33776. * function(mesh) { // do things
  33777. * return; }
  33778. * ```
  33779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33780. */
  33781. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33782. var options = {
  33783. width: width,
  33784. height: height,
  33785. subdivisions: subdivisions,
  33786. minHeight: minHeight,
  33787. maxHeight: maxHeight,
  33788. updatable: updatable,
  33789. onReady: onReady
  33790. };
  33791. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33792. };
  33793. /**
  33794. * Creates a tube mesh.
  33795. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33796. * Please consider using the same method from the MeshBuilder class instead.
  33797. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33798. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33799. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33800. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33801. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  33802. * It must return a radius value (positive float) :
  33803. * ```javascript
  33804. * var radiusFunction = function(i, distance) {
  33805. * // do things
  33806. * return radius; }
  33807. * ```
  33808. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33809. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  33810. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33811. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33813. */
  33814. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33815. var options = {
  33816. path: path,
  33817. radius: radius,
  33818. tessellation: tessellation,
  33819. radiusFunction: radiusFunction,
  33820. arc: 1,
  33821. cap: cap,
  33822. updatable: updatable,
  33823. sideOrientation: sideOrientation,
  33824. instance: instance
  33825. };
  33826. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33827. };
  33828. /**
  33829. * Creates a polyhedron mesh.
  33830. * Please consider using the same method from the MeshBuilder class instead.
  33831. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  33832. * to choose the wanted type.
  33833. * The parameter `size` (positive float, default 1) sets the polygon size.
  33834. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33835. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  33836. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  33837. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  33838. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  33839. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  33840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33841. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33843. */
  33844. Mesh.CreatePolyhedron = function (name, options, scene) {
  33845. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33846. };
  33847. /**
  33848. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33849. * Please consider using the same method from the MeshBuilder class instead.
  33850. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33851. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  33852. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33853. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  33854. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33855. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33856. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33857. */
  33858. Mesh.CreateIcoSphere = function (name, options, scene) {
  33859. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33860. };
  33861. /**
  33862. * Creates a decal mesh.
  33863. * Please consider using the same method from the MeshBuilder class instead.
  33864. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  33865. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33866. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33867. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33868. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33869. */
  33870. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33871. var options = {
  33872. position: position,
  33873. normal: normal,
  33874. size: size,
  33875. angle: angle
  33876. };
  33877. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33878. };
  33879. // Skeletons
  33880. /**
  33881. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33882. */
  33883. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33884. if (!this._sourcePositions) {
  33885. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33886. if (!source) {
  33887. return this._sourcePositions;
  33888. }
  33889. this._sourcePositions = new Float32Array(source);
  33890. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33891. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33892. }
  33893. }
  33894. return this._sourcePositions;
  33895. };
  33896. /**
  33897. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33898. */
  33899. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33900. if (!this._sourceNormals) {
  33901. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33902. if (!source) {
  33903. return this._sourceNormals;
  33904. }
  33905. this._sourceNormals = new Float32Array(source);
  33906. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33907. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33908. }
  33909. }
  33910. return this._sourceNormals;
  33911. };
  33912. /**
  33913. * Updates the vertex buffer by applying transformation from the bones.
  33914. * Returns the Mesh.
  33915. *
  33916. * @param {skeleton} skeleton to apply
  33917. */
  33918. Mesh.prototype.applySkeleton = function (skeleton) {
  33919. if (!this.geometry) {
  33920. return this;
  33921. }
  33922. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33923. return this;
  33924. }
  33925. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33926. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33927. return this;
  33928. }
  33929. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33930. return this;
  33931. }
  33932. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33933. return this;
  33934. }
  33935. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33936. return this;
  33937. }
  33938. if (!this._sourcePositions) {
  33939. var submeshes = this.subMeshes.slice();
  33940. this.setPositionsForCPUSkinning();
  33941. this.subMeshes = submeshes;
  33942. }
  33943. if (!this._sourceNormals) {
  33944. this.setNormalsForCPUSkinning();
  33945. }
  33946. // positionsData checks for not being Float32Array will only pass at most once
  33947. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33948. if (!positionsData) {
  33949. return this;
  33950. }
  33951. if (!(positionsData instanceof Float32Array)) {
  33952. positionsData = new Float32Array(positionsData);
  33953. }
  33954. // normalsData checks for not being Float32Array will only pass at most once
  33955. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33956. if (!normalsData) {
  33957. return this;
  33958. }
  33959. if (!(normalsData instanceof Float32Array)) {
  33960. normalsData = new Float32Array(normalsData);
  33961. }
  33962. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33963. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33964. if (!matricesWeightsData || !matricesIndicesData) {
  33965. return this;
  33966. }
  33967. var needExtras = this.numBoneInfluencers > 4;
  33968. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33969. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33970. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33971. var tempVector3 = BABYLON.Vector3.Zero();
  33972. var finalMatrix = new BABYLON.Matrix();
  33973. var tempMatrix = new BABYLON.Matrix();
  33974. var matWeightIdx = 0;
  33975. var inf;
  33976. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33977. var weight;
  33978. for (inf = 0; inf < 4; inf++) {
  33979. weight = matricesWeightsData[matWeightIdx + inf];
  33980. if (weight > 0) {
  33981. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33982. finalMatrix.addToSelf(tempMatrix);
  33983. }
  33984. else
  33985. break;
  33986. }
  33987. if (needExtras) {
  33988. for (inf = 0; inf < 4; inf++) {
  33989. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33990. if (weight > 0) {
  33991. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33992. finalMatrix.addToSelf(tempMatrix);
  33993. }
  33994. else
  33995. break;
  33996. }
  33997. }
  33998. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33999. tempVector3.toArray(positionsData, index);
  34000. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34001. tempVector3.toArray(normalsData, index);
  34002. finalMatrix.reset();
  34003. }
  34004. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34005. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34006. return this;
  34007. };
  34008. // Tools
  34009. /**
  34010. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34011. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34012. */
  34013. Mesh.MinMax = function (meshes) {
  34014. var minVector = null;
  34015. var maxVector = null;
  34016. meshes.forEach(function (mesh, index, array) {
  34017. var boundingInfo = mesh.getBoundingInfo();
  34018. var boundingBox = boundingInfo.boundingBox;
  34019. if (!minVector || !maxVector) {
  34020. minVector = boundingBox.minimumWorld;
  34021. maxVector = boundingBox.maximumWorld;
  34022. }
  34023. else {
  34024. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34025. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34026. }
  34027. });
  34028. if (!minVector || !maxVector) {
  34029. return {
  34030. min: BABYLON.Vector3.Zero(),
  34031. max: BABYLON.Vector3.Zero()
  34032. };
  34033. }
  34034. return {
  34035. min: minVector,
  34036. max: maxVector
  34037. };
  34038. };
  34039. /**
  34040. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34041. */
  34042. Mesh.Center = function (meshesOrMinMaxVector) {
  34043. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34044. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34045. };
  34046. /**
  34047. * Merge the array of meshes into a single mesh for performance reasons.
  34048. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34049. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34050. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34051. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34052. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34053. */
  34054. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34055. if (disposeSource === void 0) { disposeSource = true; }
  34056. var index;
  34057. if (!allow32BitsIndices) {
  34058. var totalVertices = 0;
  34059. // Counting vertices
  34060. for (index = 0; index < meshes.length; index++) {
  34061. if (meshes[index]) {
  34062. totalVertices += meshes[index].getTotalVertices();
  34063. if (totalVertices > 65536) {
  34064. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34065. return null;
  34066. }
  34067. }
  34068. }
  34069. }
  34070. // Merge
  34071. var vertexData = null;
  34072. var otherVertexData;
  34073. var indiceArray = new Array();
  34074. var source = null;
  34075. for (index = 0; index < meshes.length; index++) {
  34076. if (meshes[index]) {
  34077. meshes[index].computeWorldMatrix(true);
  34078. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34079. otherVertexData.transform(meshes[index].getWorldMatrix());
  34080. if (vertexData) {
  34081. vertexData.merge(otherVertexData);
  34082. }
  34083. else {
  34084. vertexData = otherVertexData;
  34085. source = meshes[index];
  34086. }
  34087. if (subdivideWithSubMeshes) {
  34088. indiceArray.push(meshes[index].getTotalIndices());
  34089. }
  34090. }
  34091. }
  34092. source = source;
  34093. if (!meshSubclass) {
  34094. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34095. }
  34096. vertexData.applyToMesh(meshSubclass);
  34097. // Setting properties
  34098. meshSubclass.material = source.material;
  34099. meshSubclass.checkCollisions = source.checkCollisions;
  34100. // Cleaning
  34101. if (disposeSource) {
  34102. for (index = 0; index < meshes.length; index++) {
  34103. if (meshes[index]) {
  34104. meshes[index].dispose();
  34105. }
  34106. }
  34107. }
  34108. // Subdivide
  34109. if (subdivideWithSubMeshes) {
  34110. //-- Suppresions du submesh global
  34111. meshSubclass.releaseSubMeshes();
  34112. index = 0;
  34113. var offset = 0;
  34114. //-- aplique la subdivision en fonction du tableau d'indices
  34115. while (index < indiceArray.length) {
  34116. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34117. offset += indiceArray[index];
  34118. index++;
  34119. }
  34120. }
  34121. return meshSubclass;
  34122. };
  34123. // Consts
  34124. Mesh._FRONTSIDE = 0;
  34125. Mesh._BACKSIDE = 1;
  34126. Mesh._DOUBLESIDE = 2;
  34127. Mesh._DEFAULTSIDE = 0;
  34128. Mesh._NO_CAP = 0;
  34129. Mesh._CAP_START = 1;
  34130. Mesh._CAP_END = 2;
  34131. Mesh._CAP_ALL = 3;
  34132. return Mesh;
  34133. }(BABYLON.AbstractMesh));
  34134. BABYLON.Mesh = Mesh;
  34135. })(BABYLON || (BABYLON = {}));
  34136. //# sourceMappingURL=babylon.mesh.js.map
  34137. var BABYLON;
  34138. (function (BABYLON) {
  34139. var BaseSubMesh = /** @class */ (function () {
  34140. function BaseSubMesh() {
  34141. }
  34142. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34143. get: function () {
  34144. return this._materialEffect;
  34145. },
  34146. enumerable: true,
  34147. configurable: true
  34148. });
  34149. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34150. if (defines === void 0) { defines = null; }
  34151. if (this._materialEffect === effect) {
  34152. if (!effect) {
  34153. this._materialDefines = null;
  34154. }
  34155. return;
  34156. }
  34157. this._materialDefines = defines;
  34158. this._materialEffect = effect;
  34159. };
  34160. return BaseSubMesh;
  34161. }());
  34162. BABYLON.BaseSubMesh = BaseSubMesh;
  34163. var SubMesh = /** @class */ (function (_super) {
  34164. __extends(SubMesh, _super);
  34165. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34166. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34167. var _this = _super.call(this) || this;
  34168. _this.materialIndex = materialIndex;
  34169. _this.verticesStart = verticesStart;
  34170. _this.verticesCount = verticesCount;
  34171. _this.indexStart = indexStart;
  34172. _this.indexCount = indexCount;
  34173. _this._renderId = 0;
  34174. _this._mesh = mesh;
  34175. _this._renderingMesh = renderingMesh || mesh;
  34176. mesh.subMeshes.push(_this);
  34177. _this._trianglePlanes = [];
  34178. _this._id = mesh.subMeshes.length - 1;
  34179. if (createBoundingBox) {
  34180. _this.refreshBoundingInfo();
  34181. mesh.computeWorldMatrix(true);
  34182. }
  34183. return _this;
  34184. }
  34185. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34186. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34187. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34188. };
  34189. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34190. get: function () {
  34191. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34192. },
  34193. enumerable: true,
  34194. configurable: true
  34195. });
  34196. /**
  34197. * Returns the submesh BoudingInfo object.
  34198. */
  34199. SubMesh.prototype.getBoundingInfo = function () {
  34200. if (this.IsGlobal) {
  34201. return this._mesh.getBoundingInfo();
  34202. }
  34203. return this._boundingInfo;
  34204. };
  34205. /**
  34206. * Sets the submesh BoundingInfo.
  34207. * Return the SubMesh.
  34208. */
  34209. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34210. this._boundingInfo = boundingInfo;
  34211. return this;
  34212. };
  34213. /**
  34214. * Returns the mesh of the current submesh.
  34215. */
  34216. SubMesh.prototype.getMesh = function () {
  34217. return this._mesh;
  34218. };
  34219. /**
  34220. * Returns the rendering mesh of the submesh.
  34221. */
  34222. SubMesh.prototype.getRenderingMesh = function () {
  34223. return this._renderingMesh;
  34224. };
  34225. /**
  34226. * Returns the submesh material.
  34227. */
  34228. SubMesh.prototype.getMaterial = function () {
  34229. var rootMaterial = this._renderingMesh.material;
  34230. if (rootMaterial === null || rootMaterial === undefined) {
  34231. return this._mesh.getScene().defaultMaterial;
  34232. }
  34233. else if (rootMaterial.getSubMaterial) {
  34234. var multiMaterial = rootMaterial;
  34235. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34236. if (this._currentMaterial !== effectiveMaterial) {
  34237. this._currentMaterial = effectiveMaterial;
  34238. this._materialDefines = null;
  34239. }
  34240. return effectiveMaterial;
  34241. }
  34242. return rootMaterial;
  34243. };
  34244. // Methods
  34245. /**
  34246. * Sets a new updated BoundingInfo object to the submesh.
  34247. * Returns the SubMesh.
  34248. */
  34249. SubMesh.prototype.refreshBoundingInfo = function () {
  34250. this._lastColliderWorldVertices = null;
  34251. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34252. return this;
  34253. }
  34254. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34255. if (!data) {
  34256. this._boundingInfo = this._mesh.getBoundingInfo();
  34257. return this;
  34258. }
  34259. var indices = this._renderingMesh.getIndices();
  34260. var extend;
  34261. //is this the only submesh?
  34262. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34263. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34264. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34265. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34266. }
  34267. else {
  34268. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34269. }
  34270. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34271. return this;
  34272. };
  34273. SubMesh.prototype._checkCollision = function (collider) {
  34274. var boundingInfo = this.getBoundingInfo();
  34275. return boundingInfo._checkCollision(collider);
  34276. };
  34277. /**
  34278. * Updates the submesh BoundingInfo.
  34279. * Returns the Submesh.
  34280. */
  34281. SubMesh.prototype.updateBoundingInfo = function (world) {
  34282. var boundingInfo = this.getBoundingInfo();
  34283. if (!boundingInfo) {
  34284. this.refreshBoundingInfo();
  34285. boundingInfo = this.getBoundingInfo();
  34286. }
  34287. boundingInfo.update(world);
  34288. return this;
  34289. };
  34290. /**
  34291. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34292. * Boolean returned.
  34293. */
  34294. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34295. var boundingInfo = this.getBoundingInfo();
  34296. if (!boundingInfo) {
  34297. return false;
  34298. }
  34299. return boundingInfo.isInFrustum(frustumPlanes);
  34300. };
  34301. /**
  34302. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34303. * Boolean returned.
  34304. */
  34305. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34306. var boundingInfo = this.getBoundingInfo();
  34307. if (!boundingInfo) {
  34308. return false;
  34309. }
  34310. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34311. };
  34312. /**
  34313. * Renders the submesh.
  34314. * Returns it.
  34315. */
  34316. SubMesh.prototype.render = function (enableAlphaMode) {
  34317. this._renderingMesh.render(this, enableAlphaMode);
  34318. return this;
  34319. };
  34320. /**
  34321. * Returns a new Index Buffer.
  34322. * Type returned : WebGLBuffer.
  34323. */
  34324. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34325. if (!this._linesIndexBuffer) {
  34326. var linesIndices = [];
  34327. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34328. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34329. }
  34330. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34331. this.linesIndexCount = linesIndices.length;
  34332. }
  34333. return this._linesIndexBuffer;
  34334. };
  34335. /**
  34336. * True is the passed Ray intersects the submesh bounding box.
  34337. * Boolean returned.
  34338. */
  34339. SubMesh.prototype.canIntersects = function (ray) {
  34340. var boundingInfo = this.getBoundingInfo();
  34341. if (!boundingInfo) {
  34342. return false;
  34343. }
  34344. return ray.intersectsBox(boundingInfo.boundingBox);
  34345. };
  34346. /**
  34347. * Returns an object IntersectionInfo.
  34348. */
  34349. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34350. var intersectInfo = null;
  34351. var material = this.getMaterial();
  34352. if (!material) {
  34353. return null;
  34354. }
  34355. switch (material.fillMode) {
  34356. case BABYLON.Material.PointListDrawMode:
  34357. case BABYLON.Material.LineListDrawMode:
  34358. case BABYLON.Material.LineLoopDrawMode:
  34359. case BABYLON.Material.LineStripDrawMode:
  34360. case BABYLON.Material.TriangleFanDrawMode:
  34361. case BABYLON.Material.TriangleStripDrawMode:
  34362. return null;
  34363. }
  34364. // LineMesh first as it's also a Mesh...
  34365. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34366. var lineMesh = this._mesh;
  34367. // Line test
  34368. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34369. var p0 = positions[indices[index]];
  34370. var p1 = positions[indices[index + 1]];
  34371. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34372. if (length < 0) {
  34373. continue;
  34374. }
  34375. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34376. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34377. if (fastCheck) {
  34378. break;
  34379. }
  34380. }
  34381. }
  34382. }
  34383. else {
  34384. // Triangles test
  34385. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34386. var p0 = positions[indices[index]];
  34387. var p1 = positions[indices[index + 1]];
  34388. var p2 = positions[indices[index + 2]];
  34389. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34390. if (currentIntersectInfo) {
  34391. if (currentIntersectInfo.distance < 0) {
  34392. continue;
  34393. }
  34394. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34395. intersectInfo = currentIntersectInfo;
  34396. intersectInfo.faceId = index / 3;
  34397. if (fastCheck) {
  34398. break;
  34399. }
  34400. }
  34401. }
  34402. }
  34403. }
  34404. return intersectInfo;
  34405. };
  34406. SubMesh.prototype._rebuild = function () {
  34407. if (this._linesIndexBuffer) {
  34408. this._linesIndexBuffer = null;
  34409. }
  34410. };
  34411. // Clone
  34412. /**
  34413. * Creates a new Submesh from the passed Mesh.
  34414. */
  34415. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34416. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34417. if (!this.IsGlobal) {
  34418. var boundingInfo = this.getBoundingInfo();
  34419. if (!boundingInfo) {
  34420. return result;
  34421. }
  34422. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34423. }
  34424. return result;
  34425. };
  34426. // Dispose
  34427. /**
  34428. * Disposes the Submesh.
  34429. * Returns nothing.
  34430. */
  34431. SubMesh.prototype.dispose = function () {
  34432. if (this._linesIndexBuffer) {
  34433. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34434. this._linesIndexBuffer = null;
  34435. }
  34436. // Remove from mesh
  34437. var index = this._mesh.subMeshes.indexOf(this);
  34438. this._mesh.subMeshes.splice(index, 1);
  34439. };
  34440. // Statics
  34441. /**
  34442. * Creates a new Submesh from the passed parameters :
  34443. * - materialIndex (integer) : the index of the main mesh material.
  34444. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34445. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34446. * - mesh (Mesh) : the main mesh to create the submesh from.
  34447. * - renderingMesh (optional Mesh) : rendering mesh.
  34448. */
  34449. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34450. var minVertexIndex = Number.MAX_VALUE;
  34451. var maxVertexIndex = -Number.MAX_VALUE;
  34452. renderingMesh = (renderingMesh || mesh);
  34453. var indices = renderingMesh.getIndices();
  34454. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34455. var vertexIndex = indices[index];
  34456. if (vertexIndex < minVertexIndex)
  34457. minVertexIndex = vertexIndex;
  34458. if (vertexIndex > maxVertexIndex)
  34459. maxVertexIndex = vertexIndex;
  34460. }
  34461. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34462. };
  34463. return SubMesh;
  34464. }(BaseSubMesh));
  34465. BABYLON.SubMesh = SubMesh;
  34466. })(BABYLON || (BABYLON = {}));
  34467. //# sourceMappingURL=babylon.subMesh.js.map
  34468. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34469. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34470. s = arguments[i];
  34471. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34472. t[p] = s[p];
  34473. }
  34474. return t;
  34475. };
  34476. var BABYLON;
  34477. (function (BABYLON) {
  34478. /**
  34479. * Manages the defines for the Material
  34480. */
  34481. var MaterialDefines = /** @class */ (function () {
  34482. function MaterialDefines() {
  34483. this._isDirty = true;
  34484. /** @hidden */
  34485. this._areLightsDirty = true;
  34486. /** @hidden */
  34487. this._areAttributesDirty = true;
  34488. /** @hidden */
  34489. this._areTexturesDirty = true;
  34490. /** @hidden */
  34491. this._areFresnelDirty = true;
  34492. /** @hidden */
  34493. this._areMiscDirty = true;
  34494. /** @hidden */
  34495. this._areImageProcessingDirty = true;
  34496. /** @hidden */
  34497. this._normals = false;
  34498. /** @hidden */
  34499. this._uvs = false;
  34500. /** @hidden */
  34501. this._needNormals = false;
  34502. /** @hidden */
  34503. this._needUVs = false;
  34504. }
  34505. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34506. /**
  34507. * Specifies if the material needs to be re-calculated
  34508. */
  34509. get: function () {
  34510. return this._isDirty;
  34511. },
  34512. enumerable: true,
  34513. configurable: true
  34514. });
  34515. /**
  34516. * Marks the material to indicate that it has been re-calculated
  34517. */
  34518. MaterialDefines.prototype.markAsProcessed = function () {
  34519. this._isDirty = false;
  34520. this._areAttributesDirty = false;
  34521. this._areTexturesDirty = false;
  34522. this._areFresnelDirty = false;
  34523. this._areLightsDirty = false;
  34524. this._areMiscDirty = false;
  34525. this._areImageProcessingDirty = false;
  34526. };
  34527. /**
  34528. * Marks the material to indicate that it needs to be re-calculated
  34529. */
  34530. MaterialDefines.prototype.markAsUnprocessed = function () {
  34531. this._isDirty = true;
  34532. };
  34533. /**
  34534. * Marks the material to indicate all of its defines need to be re-calculated
  34535. */
  34536. MaterialDefines.prototype.markAllAsDirty = function () {
  34537. this._areTexturesDirty = true;
  34538. this._areAttributesDirty = true;
  34539. this._areLightsDirty = true;
  34540. this._areFresnelDirty = true;
  34541. this._areMiscDirty = true;
  34542. this._areImageProcessingDirty = true;
  34543. this._isDirty = true;
  34544. };
  34545. /**
  34546. * Marks the material to indicate that image processing needs to be re-calculated
  34547. */
  34548. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34549. this._areImageProcessingDirty = true;
  34550. this._isDirty = true;
  34551. };
  34552. /**
  34553. * Marks the material to indicate the lights need to be re-calculated
  34554. */
  34555. MaterialDefines.prototype.markAsLightDirty = function () {
  34556. this._areLightsDirty = true;
  34557. this._isDirty = true;
  34558. };
  34559. /**
  34560. * Marks the attribute state as changed
  34561. */
  34562. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34563. this._areAttributesDirty = true;
  34564. this._isDirty = true;
  34565. };
  34566. /**
  34567. * Marks the texture state as changed
  34568. */
  34569. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34570. this._areTexturesDirty = true;
  34571. this._isDirty = true;
  34572. };
  34573. /**
  34574. * Marks the fresnel state as changed
  34575. */
  34576. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34577. this._areFresnelDirty = true;
  34578. this._isDirty = true;
  34579. };
  34580. /**
  34581. * Marks the misc state as changed
  34582. */
  34583. MaterialDefines.prototype.markAsMiscDirty = function () {
  34584. this._areMiscDirty = true;
  34585. this._isDirty = true;
  34586. };
  34587. /**
  34588. * Rebuilds the material defines
  34589. */
  34590. MaterialDefines.prototype.rebuild = function () {
  34591. if (this._keys) {
  34592. delete this._keys;
  34593. }
  34594. this._keys = [];
  34595. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34596. var key = _a[_i];
  34597. if (key[0] === "_") {
  34598. continue;
  34599. }
  34600. this._keys.push(key);
  34601. }
  34602. };
  34603. /**
  34604. * Specifies if two material defines are equal
  34605. * @param other - A material define instance to compare to
  34606. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34607. */
  34608. MaterialDefines.prototype.isEqual = function (other) {
  34609. if (this._keys.length !== other._keys.length) {
  34610. return false;
  34611. }
  34612. for (var index = 0; index < this._keys.length; index++) {
  34613. var prop = this._keys[index];
  34614. if (this[prop] !== other[prop]) {
  34615. return false;
  34616. }
  34617. }
  34618. return true;
  34619. };
  34620. /**
  34621. * Clones this instance's defines to another instance
  34622. * @param other - material defines to clone values to
  34623. */
  34624. MaterialDefines.prototype.cloneTo = function (other) {
  34625. if (this._keys.length !== other._keys.length) {
  34626. other._keys = this._keys.slice(0);
  34627. }
  34628. for (var index = 0; index < this._keys.length; index++) {
  34629. var prop = this._keys[index];
  34630. other[prop] = this[prop];
  34631. }
  34632. };
  34633. /**
  34634. * Resets the material define values
  34635. */
  34636. MaterialDefines.prototype.reset = function () {
  34637. for (var index = 0; index < this._keys.length; index++) {
  34638. var prop = this._keys[index];
  34639. var type = typeof this[prop];
  34640. switch (type) {
  34641. case "number":
  34642. this[prop] = 0;
  34643. break;
  34644. case "string":
  34645. this[prop] = "";
  34646. break;
  34647. default:
  34648. this[prop] = false;
  34649. break;
  34650. }
  34651. }
  34652. };
  34653. /**
  34654. * Converts the material define values to a string
  34655. * @returns - String of material define information
  34656. */
  34657. MaterialDefines.prototype.toString = function () {
  34658. var result = "";
  34659. for (var index = 0; index < this._keys.length; index++) {
  34660. var prop = this._keys[index];
  34661. var value = this[prop];
  34662. var type = typeof value;
  34663. switch (type) {
  34664. case "number":
  34665. case "string":
  34666. result += "#define " + prop + " " + value + "\n";
  34667. break;
  34668. default:
  34669. if (value) {
  34670. result += "#define " + prop + "\n";
  34671. }
  34672. break;
  34673. }
  34674. }
  34675. return result;
  34676. };
  34677. return MaterialDefines;
  34678. }());
  34679. BABYLON.MaterialDefines = MaterialDefines;
  34680. /**
  34681. * Base class for the main features of a material in Babylon.js
  34682. */
  34683. var Material = /** @class */ (function () {
  34684. /**
  34685. * Creates a material instance
  34686. * @param name defines the name of the material
  34687. * @param scene defines the scene to reference
  34688. * @param doNotAdd specifies if the material should be added to the scene
  34689. */
  34690. function Material(name, scene, doNotAdd) {
  34691. /**
  34692. * Specifies if the ready state should be checked on each call
  34693. */
  34694. this.checkReadyOnEveryCall = false;
  34695. /**
  34696. * Specifies if the ready state should be checked once
  34697. */
  34698. this.checkReadyOnlyOnce = false;
  34699. /**
  34700. * The state of the material
  34701. */
  34702. this.state = "";
  34703. /**
  34704. * The alpha value of the material
  34705. */
  34706. this._alpha = 1.0;
  34707. /**
  34708. * Specifies if back face culling is enabled
  34709. */
  34710. this._backFaceCulling = true;
  34711. /**
  34712. * Specifies if the material should be serialized
  34713. */
  34714. this.doNotSerialize = false;
  34715. /**
  34716. * Specifies if the effect should be stored on sub meshes
  34717. */
  34718. this.storeEffectOnSubMeshes = false;
  34719. /**
  34720. * An event triggered when the material is disposed
  34721. */
  34722. this.onDisposeObservable = new BABYLON.Observable();
  34723. /**
  34724. * An event triggered when the material is bound
  34725. */
  34726. this.onBindObservable = new BABYLON.Observable();
  34727. /**
  34728. * An event triggered when the material is unbound
  34729. */
  34730. this.onUnBindObservable = new BABYLON.Observable();
  34731. /**
  34732. * Stores the value of the alpha mode
  34733. */
  34734. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34735. /**
  34736. * Stores the state of the need depth pre-pass value
  34737. */
  34738. this._needDepthPrePass = false;
  34739. /**
  34740. * Specifies if depth writing should be disabled
  34741. */
  34742. this.disableDepthWrite = false;
  34743. /**
  34744. * Specifies if depth writing should be forced
  34745. */
  34746. this.forceDepthWrite = false;
  34747. /**
  34748. * Specifies if there should be a separate pass for culling
  34749. */
  34750. this.separateCullingPass = false;
  34751. /**
  34752. * Stores the state specifing if fog should be enabled
  34753. */
  34754. this._fogEnabled = true;
  34755. /**
  34756. * Stores the size of points
  34757. */
  34758. this.pointSize = 1.0;
  34759. /**
  34760. * Stores the z offset value
  34761. */
  34762. this.zOffset = 0;
  34763. /**
  34764. * Specifies if the material was previously ready
  34765. */
  34766. this._wasPreviouslyReady = false;
  34767. /**
  34768. * Stores the fill mode state
  34769. */
  34770. this._fillMode = Material.TriangleFillMode;
  34771. this.name = name;
  34772. this.id = name || BABYLON.Tools.RandomId();
  34773. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34774. if (this._scene.useRightHandedSystem) {
  34775. this.sideOrientation = Material.ClockWiseSideOrientation;
  34776. }
  34777. else {
  34778. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34779. }
  34780. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34781. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34782. if (!doNotAdd) {
  34783. this._scene.materials.push(this);
  34784. }
  34785. }
  34786. Object.defineProperty(Material, "TriangleFillMode", {
  34787. /**
  34788. * Returns the triangle fill mode
  34789. */
  34790. get: function () {
  34791. return Material._TriangleFillMode;
  34792. },
  34793. enumerable: true,
  34794. configurable: true
  34795. });
  34796. Object.defineProperty(Material, "WireFrameFillMode", {
  34797. /**
  34798. * Returns the wireframe mode
  34799. */
  34800. get: function () {
  34801. return Material._WireFrameFillMode;
  34802. },
  34803. enumerable: true,
  34804. configurable: true
  34805. });
  34806. Object.defineProperty(Material, "PointFillMode", {
  34807. /**
  34808. * Returns the point fill mode
  34809. */
  34810. get: function () {
  34811. return Material._PointFillMode;
  34812. },
  34813. enumerable: true,
  34814. configurable: true
  34815. });
  34816. Object.defineProperty(Material, "PointListDrawMode", {
  34817. /**
  34818. * Returns the point list draw mode
  34819. */
  34820. get: function () {
  34821. return Material._PointListDrawMode;
  34822. },
  34823. enumerable: true,
  34824. configurable: true
  34825. });
  34826. Object.defineProperty(Material, "LineListDrawMode", {
  34827. /**
  34828. * Returns the line list draw mode
  34829. */
  34830. get: function () {
  34831. return Material._LineListDrawMode;
  34832. },
  34833. enumerable: true,
  34834. configurable: true
  34835. });
  34836. Object.defineProperty(Material, "LineLoopDrawMode", {
  34837. /**
  34838. * Returns the line loop draw mode
  34839. */
  34840. get: function () {
  34841. return Material._LineLoopDrawMode;
  34842. },
  34843. enumerable: true,
  34844. configurable: true
  34845. });
  34846. Object.defineProperty(Material, "LineStripDrawMode", {
  34847. /**
  34848. * Returns the line strip draw mode
  34849. */
  34850. get: function () {
  34851. return Material._LineStripDrawMode;
  34852. },
  34853. enumerable: true,
  34854. configurable: true
  34855. });
  34856. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34857. /**
  34858. * Returns the triangle strip draw mode
  34859. */
  34860. get: function () {
  34861. return Material._TriangleStripDrawMode;
  34862. },
  34863. enumerable: true,
  34864. configurable: true
  34865. });
  34866. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34867. /**
  34868. * Returns the triangle fan draw mode
  34869. */
  34870. get: function () {
  34871. return Material._TriangleFanDrawMode;
  34872. },
  34873. enumerable: true,
  34874. configurable: true
  34875. });
  34876. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34877. /**
  34878. * Returns the clock-wise side orientation
  34879. */
  34880. get: function () {
  34881. return Material._ClockWiseSideOrientation;
  34882. },
  34883. enumerable: true,
  34884. configurable: true
  34885. });
  34886. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34887. /**
  34888. * Returns the counter clock-wise side orientation
  34889. */
  34890. get: function () {
  34891. return Material._CounterClockWiseSideOrientation;
  34892. },
  34893. enumerable: true,
  34894. configurable: true
  34895. });
  34896. Object.defineProperty(Material, "TextureDirtyFlag", {
  34897. /**
  34898. * Returns the dirty texture flag value
  34899. */
  34900. get: function () {
  34901. return Material._TextureDirtyFlag;
  34902. },
  34903. enumerable: true,
  34904. configurable: true
  34905. });
  34906. Object.defineProperty(Material, "LightDirtyFlag", {
  34907. /**
  34908. * Returns the dirty light flag value
  34909. */
  34910. get: function () {
  34911. return Material._LightDirtyFlag;
  34912. },
  34913. enumerable: true,
  34914. configurable: true
  34915. });
  34916. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34917. /**
  34918. * Returns the dirty fresnel flag value
  34919. */
  34920. get: function () {
  34921. return Material._FresnelDirtyFlag;
  34922. },
  34923. enumerable: true,
  34924. configurable: true
  34925. });
  34926. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34927. /**
  34928. * Returns the dirty attributes flag value
  34929. */
  34930. get: function () {
  34931. return Material._AttributesDirtyFlag;
  34932. },
  34933. enumerable: true,
  34934. configurable: true
  34935. });
  34936. Object.defineProperty(Material, "MiscDirtyFlag", {
  34937. /**
  34938. * Returns the dirty misc flag value
  34939. */
  34940. get: function () {
  34941. return Material._MiscDirtyFlag;
  34942. },
  34943. enumerable: true,
  34944. configurable: true
  34945. });
  34946. Object.defineProperty(Material.prototype, "alpha", {
  34947. /**
  34948. * Gets the alpha value of the material
  34949. */
  34950. get: function () {
  34951. return this._alpha;
  34952. },
  34953. /**
  34954. * Sets the alpha value of the material
  34955. */
  34956. set: function (value) {
  34957. if (this._alpha === value) {
  34958. return;
  34959. }
  34960. this._alpha = value;
  34961. this.markAsDirty(Material.MiscDirtyFlag);
  34962. },
  34963. enumerable: true,
  34964. configurable: true
  34965. });
  34966. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34967. /**
  34968. * Gets the back-face culling state
  34969. */
  34970. get: function () {
  34971. return this._backFaceCulling;
  34972. },
  34973. /**
  34974. * Sets the back-face culling state
  34975. */
  34976. set: function (value) {
  34977. if (this._backFaceCulling === value) {
  34978. return;
  34979. }
  34980. this._backFaceCulling = value;
  34981. this.markAsDirty(Material.TextureDirtyFlag);
  34982. },
  34983. enumerable: true,
  34984. configurable: true
  34985. });
  34986. Object.defineProperty(Material.prototype, "onDispose", {
  34987. /**
  34988. * Called during a dispose event
  34989. */
  34990. set: function (callback) {
  34991. if (this._onDisposeObserver) {
  34992. this.onDisposeObservable.remove(this._onDisposeObserver);
  34993. }
  34994. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34995. },
  34996. enumerable: true,
  34997. configurable: true
  34998. });
  34999. Object.defineProperty(Material.prototype, "onBind", {
  35000. /**
  35001. * Called during a bind event
  35002. */
  35003. set: function (callback) {
  35004. if (this._onBindObserver) {
  35005. this.onBindObservable.remove(this._onBindObserver);
  35006. }
  35007. this._onBindObserver = this.onBindObservable.add(callback);
  35008. },
  35009. enumerable: true,
  35010. configurable: true
  35011. });
  35012. Object.defineProperty(Material.prototype, "alphaMode", {
  35013. /**
  35014. * Gets the value of the alpha mode
  35015. */
  35016. get: function () {
  35017. return this._alphaMode;
  35018. },
  35019. /**
  35020. * Sets the value of the alpha mode.
  35021. *
  35022. * | Value | Type | Description |
  35023. * | --- | --- | --- |
  35024. * | 0 | ALPHA_DISABLE | |
  35025. * | 1 | ALPHA_ADD | |
  35026. * | 2 | ALPHA_COMBINE | |
  35027. * | 3 | ALPHA_SUBTRACT | |
  35028. * | 4 | ALPHA_MULTIPLY | |
  35029. * | 5 | ALPHA_MAXIMIZED | |
  35030. * | 6 | ALPHA_ONEONE | |
  35031. * | 7 | ALPHA_PREMULTIPLIED | |
  35032. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35033. * | 9 | ALPHA_INTERPOLATE | |
  35034. * | 10 | ALPHA_SCREENMODE | |
  35035. *
  35036. */
  35037. set: function (value) {
  35038. if (this._alphaMode === value) {
  35039. return;
  35040. }
  35041. this._alphaMode = value;
  35042. this.markAsDirty(Material.TextureDirtyFlag);
  35043. },
  35044. enumerable: true,
  35045. configurable: true
  35046. });
  35047. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35048. /**
  35049. * Gets the depth pre-pass value
  35050. */
  35051. get: function () {
  35052. return this._needDepthPrePass;
  35053. },
  35054. /**
  35055. * Sets the need depth pre-pass value
  35056. */
  35057. set: function (value) {
  35058. if (this._needDepthPrePass === value) {
  35059. return;
  35060. }
  35061. this._needDepthPrePass = value;
  35062. if (this._needDepthPrePass) {
  35063. this.checkReadyOnEveryCall = true;
  35064. }
  35065. },
  35066. enumerable: true,
  35067. configurable: true
  35068. });
  35069. Object.defineProperty(Material.prototype, "fogEnabled", {
  35070. /**
  35071. * Gets the value of the fog enabled state
  35072. */
  35073. get: function () {
  35074. return this._fogEnabled;
  35075. },
  35076. /**
  35077. * Sets the state for enabling fog
  35078. */
  35079. set: function (value) {
  35080. if (this._fogEnabled === value) {
  35081. return;
  35082. }
  35083. this._fogEnabled = value;
  35084. this.markAsDirty(Material.MiscDirtyFlag);
  35085. },
  35086. enumerable: true,
  35087. configurable: true
  35088. });
  35089. Object.defineProperty(Material.prototype, "wireframe", {
  35090. /**
  35091. * Gets a value specifying if wireframe mode is enabled
  35092. */
  35093. get: function () {
  35094. switch (this._fillMode) {
  35095. case Material.WireFrameFillMode:
  35096. case Material.LineListDrawMode:
  35097. case Material.LineLoopDrawMode:
  35098. case Material.LineStripDrawMode:
  35099. return true;
  35100. }
  35101. return this._scene.forceWireframe;
  35102. },
  35103. /**
  35104. * Sets the state of wireframe mode
  35105. */
  35106. set: function (value) {
  35107. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35108. },
  35109. enumerable: true,
  35110. configurable: true
  35111. });
  35112. Object.defineProperty(Material.prototype, "pointsCloud", {
  35113. /**
  35114. * Gets the value specifying if point clouds are enabled
  35115. */
  35116. get: function () {
  35117. switch (this._fillMode) {
  35118. case Material.PointFillMode:
  35119. case Material.PointListDrawMode:
  35120. return true;
  35121. }
  35122. return this._scene.forcePointsCloud;
  35123. },
  35124. /**
  35125. * Sets the state of point cloud mode
  35126. */
  35127. set: function (value) {
  35128. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35129. },
  35130. enumerable: true,
  35131. configurable: true
  35132. });
  35133. Object.defineProperty(Material.prototype, "fillMode", {
  35134. /**
  35135. * Gets the material fill mode
  35136. */
  35137. get: function () {
  35138. return this._fillMode;
  35139. },
  35140. /**
  35141. * Sets the material fill mode
  35142. */
  35143. set: function (value) {
  35144. if (this._fillMode === value) {
  35145. return;
  35146. }
  35147. this._fillMode = value;
  35148. this.markAsDirty(Material.MiscDirtyFlag);
  35149. },
  35150. enumerable: true,
  35151. configurable: true
  35152. });
  35153. /**
  35154. * Returns a string representation of the current material
  35155. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35156. * @returns a string with material information
  35157. */
  35158. Material.prototype.toString = function (fullDetails) {
  35159. var ret = "Name: " + this.name;
  35160. if (fullDetails) {
  35161. }
  35162. return ret;
  35163. };
  35164. /**
  35165. * Gets the class name of the material
  35166. * @returns a string with the class name of the material
  35167. */
  35168. Material.prototype.getClassName = function () {
  35169. return "Material";
  35170. };
  35171. Object.defineProperty(Material.prototype, "isFrozen", {
  35172. /**
  35173. * Specifies if updates for the material been locked
  35174. */
  35175. get: function () {
  35176. return this.checkReadyOnlyOnce;
  35177. },
  35178. enumerable: true,
  35179. configurable: true
  35180. });
  35181. /**
  35182. * Locks updates for the material
  35183. */
  35184. Material.prototype.freeze = function () {
  35185. this.checkReadyOnlyOnce = true;
  35186. };
  35187. /**
  35188. * Unlocks updates for the material
  35189. */
  35190. Material.prototype.unfreeze = function () {
  35191. this.checkReadyOnlyOnce = false;
  35192. };
  35193. /**
  35194. * Specifies if the material is ready to be used
  35195. * @param mesh defines the mesh to check
  35196. * @param useInstances specifies if instances should be used
  35197. * @returns a boolean indicating if the material is ready to be used
  35198. */
  35199. Material.prototype.isReady = function (mesh, useInstances) {
  35200. return true;
  35201. };
  35202. /**
  35203. * Specifies that the submesh is ready to be used
  35204. * @param mesh defines the mesh to check
  35205. * @param subMesh defines which submesh to check
  35206. * @param useInstances specifies that instances should be used
  35207. * @returns a boolean indicating that the submesh is ready or not
  35208. */
  35209. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35210. return false;
  35211. };
  35212. /**
  35213. * Returns the material effect
  35214. * @returns the effect associated with the material
  35215. */
  35216. Material.prototype.getEffect = function () {
  35217. return this._effect;
  35218. };
  35219. /**
  35220. * Returns the current scene
  35221. * @returns a Scene
  35222. */
  35223. Material.prototype.getScene = function () {
  35224. return this._scene;
  35225. };
  35226. /**
  35227. * Specifies if the material will require alpha blending
  35228. * @returns a boolean specifying if alpha blending is needed
  35229. */
  35230. Material.prototype.needAlphaBlending = function () {
  35231. return (this.alpha < 1.0);
  35232. };
  35233. /**
  35234. * Specifies if the mesh will require alpha blending
  35235. * @param mesh defines the mesh to check
  35236. * @returns a boolean specifying if alpha blending is needed for the mesh
  35237. */
  35238. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35239. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35240. };
  35241. /**
  35242. * Specifies if this material should be rendered in alpha test mode
  35243. * @returns a boolean specifying if an alpha test is needed.
  35244. */
  35245. Material.prototype.needAlphaTesting = function () {
  35246. return false;
  35247. };
  35248. /**
  35249. * Gets the texture used for the alpha test
  35250. * @returns the texture to use for alpha testing
  35251. */
  35252. Material.prototype.getAlphaTestTexture = function () {
  35253. return null;
  35254. };
  35255. /**
  35256. * Marks the material to indicate that it needs to be re-calculated
  35257. */
  35258. Material.prototype.markDirty = function () {
  35259. this._wasPreviouslyReady = false;
  35260. };
  35261. /** @hidden */
  35262. Material.prototype._preBind = function (effect, overrideOrientation) {
  35263. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35264. var engine = this._scene.getEngine();
  35265. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35266. var reverse = orientation === Material.ClockWiseSideOrientation;
  35267. engine.enableEffect(effect ? effect : this._effect);
  35268. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35269. return reverse;
  35270. };
  35271. /**
  35272. * Binds the material to the mesh
  35273. * @param world defines the world transformation matrix
  35274. * @param mesh defines the mesh to bind the material to
  35275. */
  35276. Material.prototype.bind = function (world, mesh) {
  35277. };
  35278. /**
  35279. * Binds the submesh to the material
  35280. * @param world defines the world transformation matrix
  35281. * @param mesh defines the mesh containing the submesh
  35282. * @param subMesh defines the submesh to bind the material to
  35283. */
  35284. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35285. };
  35286. /**
  35287. * Binds the world matrix to the material
  35288. * @param world defines the world transformation matrix
  35289. */
  35290. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35291. };
  35292. /**
  35293. * Binds the scene's uniform buffer to the effect.
  35294. * @param effect defines the effect to bind to the scene uniform buffer
  35295. * @param sceneUbo defines the uniform buffer storing scene data
  35296. */
  35297. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35298. sceneUbo.bindToEffect(effect, "Scene");
  35299. };
  35300. /**
  35301. * Binds the view matrix to the effect
  35302. * @param effect defines the effect to bind the view matrix to
  35303. */
  35304. Material.prototype.bindView = function (effect) {
  35305. if (!this._useUBO) {
  35306. effect.setMatrix("view", this.getScene().getViewMatrix());
  35307. }
  35308. else {
  35309. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35310. }
  35311. };
  35312. /**
  35313. * Binds the view projection matrix to the effect
  35314. * @param effect defines the effect to bind the view projection matrix to
  35315. */
  35316. Material.prototype.bindViewProjection = function (effect) {
  35317. if (!this._useUBO) {
  35318. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35319. }
  35320. else {
  35321. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35322. }
  35323. };
  35324. /**
  35325. * Specifies if material alpha testing should be turned on for the mesh
  35326. * @param mesh defines the mesh to check
  35327. */
  35328. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35329. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35330. };
  35331. /**
  35332. * Processes to execute after binding the material to a mesh
  35333. * @param mesh defines the rendered mesh
  35334. */
  35335. Material.prototype._afterBind = function (mesh) {
  35336. this._scene._cachedMaterial = this;
  35337. if (mesh) {
  35338. this._scene._cachedVisibility = mesh.visibility;
  35339. }
  35340. else {
  35341. this._scene._cachedVisibility = 1;
  35342. }
  35343. if (mesh) {
  35344. this.onBindObservable.notifyObservers(mesh);
  35345. }
  35346. if (this.disableDepthWrite) {
  35347. var engine = this._scene.getEngine();
  35348. this._cachedDepthWriteState = engine.getDepthWrite();
  35349. engine.setDepthWrite(false);
  35350. }
  35351. };
  35352. /**
  35353. * Unbinds the material from the mesh
  35354. */
  35355. Material.prototype.unbind = function () {
  35356. this.onUnBindObservable.notifyObservers(this);
  35357. if (this.disableDepthWrite) {
  35358. var engine = this._scene.getEngine();
  35359. engine.setDepthWrite(this._cachedDepthWriteState);
  35360. }
  35361. };
  35362. /**
  35363. * Gets the active textures from the material
  35364. * @returns an array of textures
  35365. */
  35366. Material.prototype.getActiveTextures = function () {
  35367. return [];
  35368. };
  35369. /**
  35370. * Specifies if the material uses a texture
  35371. * @param texture defines the texture to check against the material
  35372. * @returns a boolean specifying if the material uses the texture
  35373. */
  35374. Material.prototype.hasTexture = function (texture) {
  35375. return false;
  35376. };
  35377. /**
  35378. * Makes a duplicate of the material, and gives it a new name
  35379. * @param name defines the new name for the duplicated material
  35380. * @returns the cloned material
  35381. */
  35382. Material.prototype.clone = function (name) {
  35383. return null;
  35384. };
  35385. /**
  35386. * Gets the meshes bound to the material
  35387. * @returns an array of meshes bound to the material
  35388. */
  35389. Material.prototype.getBindedMeshes = function () {
  35390. var result = new Array();
  35391. for (var index = 0; index < this._scene.meshes.length; index++) {
  35392. var mesh = this._scene.meshes[index];
  35393. if (mesh.material === this) {
  35394. result.push(mesh);
  35395. }
  35396. }
  35397. return result;
  35398. };
  35399. /**
  35400. * Force shader compilation
  35401. * @param mesh defines the mesh associated with this material
  35402. * @param onCompiled defines a function to execute once the material is compiled
  35403. * @param options defines the options to configure the compilation
  35404. */
  35405. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35406. var _this = this;
  35407. var localOptions = __assign({ clipPlane: false }, options);
  35408. var subMesh = new BABYLON.BaseSubMesh();
  35409. var scene = this.getScene();
  35410. var checkReady = function () {
  35411. if (!_this._scene || !_this._scene.getEngine()) {
  35412. return;
  35413. }
  35414. if (subMesh._materialDefines) {
  35415. subMesh._materialDefines._renderId = -1;
  35416. }
  35417. var clipPlaneState = scene.clipPlane;
  35418. if (localOptions.clipPlane) {
  35419. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35420. }
  35421. if (_this.storeEffectOnSubMeshes) {
  35422. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35423. if (onCompiled) {
  35424. onCompiled(_this);
  35425. }
  35426. }
  35427. else {
  35428. setTimeout(checkReady, 16);
  35429. }
  35430. }
  35431. else {
  35432. if (_this.isReady(mesh)) {
  35433. if (onCompiled) {
  35434. onCompiled(_this);
  35435. }
  35436. }
  35437. else {
  35438. setTimeout(checkReady, 16);
  35439. }
  35440. }
  35441. if (localOptions.clipPlane) {
  35442. scene.clipPlane = clipPlaneState;
  35443. }
  35444. };
  35445. checkReady();
  35446. };
  35447. /**
  35448. * Force shader compilation
  35449. * @param mesh defines the mesh that will use this material
  35450. * @param options defines additional options for compiling the shaders
  35451. * @returns a promise that resolves when the compilation completes
  35452. */
  35453. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35454. var _this = this;
  35455. return new Promise(function (resolve) {
  35456. _this.forceCompilation(mesh, function () {
  35457. resolve();
  35458. }, options);
  35459. });
  35460. };
  35461. /**
  35462. * Marks a define in the material to indicate that it needs to be re-computed
  35463. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35464. */
  35465. Material.prototype.markAsDirty = function (flag) {
  35466. if (flag & Material.TextureDirtyFlag) {
  35467. this._markAllSubMeshesAsTexturesDirty();
  35468. }
  35469. if (flag & Material.LightDirtyFlag) {
  35470. this._markAllSubMeshesAsLightsDirty();
  35471. }
  35472. if (flag & Material.FresnelDirtyFlag) {
  35473. this._markAllSubMeshesAsFresnelDirty();
  35474. }
  35475. if (flag & Material.AttributesDirtyFlag) {
  35476. this._markAllSubMeshesAsAttributesDirty();
  35477. }
  35478. if (flag & Material.MiscDirtyFlag) {
  35479. this._markAllSubMeshesAsMiscDirty();
  35480. }
  35481. this.getScene().resetCachedMaterial();
  35482. };
  35483. /**
  35484. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35485. * @param func defines a function which checks material defines against the submeshes
  35486. */
  35487. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35488. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35489. var mesh = _a[_i];
  35490. if (!mesh.subMeshes) {
  35491. continue;
  35492. }
  35493. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35494. var subMesh = _c[_b];
  35495. if (subMesh.getMaterial() !== this) {
  35496. continue;
  35497. }
  35498. if (!subMesh._materialDefines) {
  35499. continue;
  35500. }
  35501. func(subMesh._materialDefines);
  35502. }
  35503. }
  35504. };
  35505. /**
  35506. * Indicates that image processing needs to be re-calculated for all submeshes
  35507. */
  35508. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35509. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35510. };
  35511. /**
  35512. * Indicates that textures need to be re-calculated for all submeshes
  35513. */
  35514. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35515. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35516. };
  35517. /**
  35518. * Indicates that fresnel needs to be re-calculated for all submeshes
  35519. */
  35520. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35521. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35522. };
  35523. /**
  35524. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35525. */
  35526. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35527. this._markAllSubMeshesAsDirty(function (defines) {
  35528. defines.markAsFresnelDirty();
  35529. defines.markAsMiscDirty();
  35530. });
  35531. };
  35532. /**
  35533. * Indicates that lights need to be re-calculated for all submeshes
  35534. */
  35535. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35536. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35537. };
  35538. /**
  35539. * Indicates that attributes need to be re-calculated for all submeshes
  35540. */
  35541. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35542. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35543. };
  35544. /**
  35545. * Indicates that misc needs to be re-calculated for all submeshes
  35546. */
  35547. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35548. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35549. };
  35550. /**
  35551. * Indicates that textures and misc need to be re-calculated for all submeshes
  35552. */
  35553. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35554. this._markAllSubMeshesAsDirty(function (defines) {
  35555. defines.markAsTexturesDirty();
  35556. defines.markAsMiscDirty();
  35557. });
  35558. };
  35559. /**
  35560. * Disposes the material
  35561. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35562. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35563. */
  35564. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35565. // Animations
  35566. this.getScene().stopAnimation(this);
  35567. this.getScene().freeProcessedMaterials();
  35568. // Remove from scene
  35569. var index = this._scene.materials.indexOf(this);
  35570. if (index >= 0) {
  35571. this._scene.materials.splice(index, 1);
  35572. }
  35573. // Remove from meshes
  35574. for (index = 0; index < this._scene.meshes.length; index++) {
  35575. var mesh = this._scene.meshes[index];
  35576. if (mesh.material === this) {
  35577. mesh.material = null;
  35578. if (mesh.geometry) {
  35579. var geometry = (mesh.geometry);
  35580. if (this.storeEffectOnSubMeshes) {
  35581. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35582. var subMesh = _a[_i];
  35583. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35584. if (forceDisposeEffect && subMesh._materialEffect) {
  35585. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35586. }
  35587. }
  35588. }
  35589. else {
  35590. geometry._releaseVertexArrayObject(this._effect);
  35591. }
  35592. }
  35593. }
  35594. }
  35595. this._uniformBuffer.dispose();
  35596. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35597. if (forceDisposeEffect && this._effect) {
  35598. if (!this.storeEffectOnSubMeshes) {
  35599. this._scene.getEngine()._releaseEffect(this._effect);
  35600. }
  35601. this._effect = null;
  35602. }
  35603. // Callback
  35604. this.onDisposeObservable.notifyObservers(this);
  35605. this.onDisposeObservable.clear();
  35606. this.onBindObservable.clear();
  35607. this.onUnBindObservable.clear();
  35608. };
  35609. /**
  35610. * Serializes this material
  35611. * @returns the serialized material object
  35612. */
  35613. Material.prototype.serialize = function () {
  35614. return BABYLON.SerializationHelper.Serialize(this);
  35615. };
  35616. /**
  35617. * Creates a MultiMaterial from parsed MultiMaterial data.
  35618. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35619. * @param scene defines the hosting scene
  35620. * @returns a new MultiMaterial
  35621. */
  35622. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35623. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35624. multiMaterial.id = parsedMultiMaterial.id;
  35625. if (BABYLON.Tags) {
  35626. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35627. }
  35628. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35629. var subMatId = parsedMultiMaterial.materials[matIndex];
  35630. if (subMatId) {
  35631. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35632. }
  35633. else {
  35634. multiMaterial.subMaterials.push(null);
  35635. }
  35636. }
  35637. return multiMaterial;
  35638. };
  35639. /**
  35640. * Creates a material from parsed material data
  35641. * @param parsedMaterial defines parsed material data
  35642. * @param scene defines the hosting scene
  35643. * @param rootUrl defines the root URL to use to load textures
  35644. * @returns a new material
  35645. */
  35646. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35647. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35648. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35649. }
  35650. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35651. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35652. if (!BABYLON.LegacyPBRMaterial) {
  35653. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35654. return;
  35655. }
  35656. }
  35657. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35658. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35659. };
  35660. // Triangle views
  35661. Material._TriangleFillMode = 0;
  35662. Material._WireFrameFillMode = 1;
  35663. Material._PointFillMode = 2;
  35664. // Draw modes
  35665. Material._PointListDrawMode = 3;
  35666. Material._LineListDrawMode = 4;
  35667. Material._LineLoopDrawMode = 5;
  35668. Material._LineStripDrawMode = 6;
  35669. Material._TriangleStripDrawMode = 7;
  35670. Material._TriangleFanDrawMode = 8;
  35671. /**
  35672. * Stores the clock-wise side orientation
  35673. */
  35674. Material._ClockWiseSideOrientation = 0;
  35675. /**
  35676. * Stores the counter clock-wise side orientation
  35677. */
  35678. Material._CounterClockWiseSideOrientation = 1;
  35679. /**
  35680. * The dirty texture flag value
  35681. */
  35682. Material._TextureDirtyFlag = 1;
  35683. /**
  35684. * The dirty light flag value
  35685. */
  35686. Material._LightDirtyFlag = 2;
  35687. /**
  35688. * The dirty fresnel flag value
  35689. */
  35690. Material._FresnelDirtyFlag = 4;
  35691. /**
  35692. * The dirty attribute flag value
  35693. */
  35694. Material._AttributesDirtyFlag = 8;
  35695. /**
  35696. * The dirty misc flag value
  35697. */
  35698. Material._MiscDirtyFlag = 16;
  35699. __decorate([
  35700. BABYLON.serialize()
  35701. ], Material.prototype, "id", void 0);
  35702. __decorate([
  35703. BABYLON.serialize()
  35704. ], Material.prototype, "name", void 0);
  35705. __decorate([
  35706. BABYLON.serialize()
  35707. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35708. __decorate([
  35709. BABYLON.serialize()
  35710. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35711. __decorate([
  35712. BABYLON.serialize()
  35713. ], Material.prototype, "state", void 0);
  35714. __decorate([
  35715. BABYLON.serialize("alpha")
  35716. ], Material.prototype, "_alpha", void 0);
  35717. __decorate([
  35718. BABYLON.serialize("backFaceCulling")
  35719. ], Material.prototype, "_backFaceCulling", void 0);
  35720. __decorate([
  35721. BABYLON.serialize()
  35722. ], Material.prototype, "sideOrientation", void 0);
  35723. __decorate([
  35724. BABYLON.serialize("alphaMode")
  35725. ], Material.prototype, "_alphaMode", void 0);
  35726. __decorate([
  35727. BABYLON.serialize()
  35728. ], Material.prototype, "_needDepthPrePass", void 0);
  35729. __decorate([
  35730. BABYLON.serialize()
  35731. ], Material.prototype, "disableDepthWrite", void 0);
  35732. __decorate([
  35733. BABYLON.serialize()
  35734. ], Material.prototype, "forceDepthWrite", void 0);
  35735. __decorate([
  35736. BABYLON.serialize()
  35737. ], Material.prototype, "separateCullingPass", void 0);
  35738. __decorate([
  35739. BABYLON.serialize("fogEnabled")
  35740. ], Material.prototype, "_fogEnabled", void 0);
  35741. __decorate([
  35742. BABYLON.serialize()
  35743. ], Material.prototype, "pointSize", void 0);
  35744. __decorate([
  35745. BABYLON.serialize()
  35746. ], Material.prototype, "zOffset", void 0);
  35747. __decorate([
  35748. BABYLON.serialize()
  35749. ], Material.prototype, "wireframe", null);
  35750. __decorate([
  35751. BABYLON.serialize()
  35752. ], Material.prototype, "pointsCloud", null);
  35753. __decorate([
  35754. BABYLON.serialize()
  35755. ], Material.prototype, "fillMode", null);
  35756. return Material;
  35757. }());
  35758. BABYLON.Material = Material;
  35759. })(BABYLON || (BABYLON = {}));
  35760. //# sourceMappingURL=babylon.material.js.map
  35761. var BABYLON;
  35762. (function (BABYLON) {
  35763. var UniformBuffer = /** @class */ (function () {
  35764. /**
  35765. * Uniform buffer objects.
  35766. *
  35767. * Handles blocks of uniform on the GPU.
  35768. *
  35769. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35770. *
  35771. * For more information, please refer to :
  35772. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35773. */
  35774. function UniformBuffer(engine, data, dynamic) {
  35775. this._engine = engine;
  35776. this._noUBO = !engine.supportsUniformBuffers;
  35777. this._dynamic = dynamic;
  35778. this._data = data || [];
  35779. this._uniformLocations = {};
  35780. this._uniformSizes = {};
  35781. this._uniformLocationPointer = 0;
  35782. this._needSync = false;
  35783. if (this._noUBO) {
  35784. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35785. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35786. this.updateFloat = this._updateFloatForEffect;
  35787. this.updateFloat2 = this._updateFloat2ForEffect;
  35788. this.updateFloat3 = this._updateFloat3ForEffect;
  35789. this.updateFloat4 = this._updateFloat4ForEffect;
  35790. this.updateMatrix = this._updateMatrixForEffect;
  35791. this.updateVector3 = this._updateVector3ForEffect;
  35792. this.updateVector4 = this._updateVector4ForEffect;
  35793. this.updateColor3 = this._updateColor3ForEffect;
  35794. this.updateColor4 = this._updateColor4ForEffect;
  35795. }
  35796. else {
  35797. this._engine._uniformBuffers.push(this);
  35798. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35799. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35800. this.updateFloat = this._updateFloatForUniform;
  35801. this.updateFloat2 = this._updateFloat2ForUniform;
  35802. this.updateFloat3 = this._updateFloat3ForUniform;
  35803. this.updateFloat4 = this._updateFloat4ForUniform;
  35804. this.updateMatrix = this._updateMatrixForUniform;
  35805. this.updateVector3 = this._updateVector3ForUniform;
  35806. this.updateVector4 = this._updateVector4ForUniform;
  35807. this.updateColor3 = this._updateColor3ForUniform;
  35808. this.updateColor4 = this._updateColor4ForUniform;
  35809. }
  35810. }
  35811. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35812. // Properties
  35813. /**
  35814. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35815. * or just falling back on setUniformXXX calls.
  35816. */
  35817. get: function () {
  35818. return !this._noUBO;
  35819. },
  35820. enumerable: true,
  35821. configurable: true
  35822. });
  35823. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35824. /**
  35825. * Indicates if the WebGL underlying uniform buffer is in sync
  35826. * with the javascript cache data.
  35827. */
  35828. get: function () {
  35829. return !this._needSync;
  35830. },
  35831. enumerable: true,
  35832. configurable: true
  35833. });
  35834. /**
  35835. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35836. * Also, a dynamic UniformBuffer will disable cache verification and always
  35837. * update the underlying WebGL uniform buffer to the GPU.
  35838. */
  35839. UniformBuffer.prototype.isDynamic = function () {
  35840. return this._dynamic !== undefined;
  35841. };
  35842. /**
  35843. * The data cache on JS side.
  35844. */
  35845. UniformBuffer.prototype.getData = function () {
  35846. return this._bufferData;
  35847. };
  35848. /**
  35849. * The underlying WebGL Uniform buffer.
  35850. */
  35851. UniformBuffer.prototype.getBuffer = function () {
  35852. return this._buffer;
  35853. };
  35854. /**
  35855. * std140 layout specifies how to align data within an UBO structure.
  35856. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35857. * for specs.
  35858. */
  35859. UniformBuffer.prototype._fillAlignment = function (size) {
  35860. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35861. // and 4x4 matrices
  35862. // TODO : change if other types are used
  35863. var alignment;
  35864. if (size <= 2) {
  35865. alignment = size;
  35866. }
  35867. else {
  35868. alignment = 4;
  35869. }
  35870. if ((this._uniformLocationPointer % alignment) !== 0) {
  35871. var oldPointer = this._uniformLocationPointer;
  35872. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35873. var diff = this._uniformLocationPointer - oldPointer;
  35874. for (var i = 0; i < diff; i++) {
  35875. this._data.push(0);
  35876. }
  35877. }
  35878. };
  35879. /**
  35880. * Adds an uniform in the buffer.
  35881. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35882. * for the layout to be correct !
  35883. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35884. * @param {number|number[]} size Data size, or data directly.
  35885. */
  35886. UniformBuffer.prototype.addUniform = function (name, size) {
  35887. if (this._noUBO) {
  35888. return;
  35889. }
  35890. if (this._uniformLocations[name] !== undefined) {
  35891. // Already existing uniform
  35892. return;
  35893. }
  35894. // This function must be called in the order of the shader layout !
  35895. // size can be the size of the uniform, or data directly
  35896. var data;
  35897. if (size instanceof Array) {
  35898. data = size;
  35899. size = data.length;
  35900. }
  35901. else {
  35902. size = size;
  35903. data = [];
  35904. // Fill with zeros
  35905. for (var i = 0; i < size; i++) {
  35906. data.push(0);
  35907. }
  35908. }
  35909. this._fillAlignment(size);
  35910. this._uniformSizes[name] = size;
  35911. this._uniformLocations[name] = this._uniformLocationPointer;
  35912. this._uniformLocationPointer += size;
  35913. for (var i = 0; i < size; i++) {
  35914. this._data.push(data[i]);
  35915. }
  35916. this._needSync = true;
  35917. };
  35918. /**
  35919. * Wrapper for addUniform.
  35920. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35921. * @param {Matrix} mat A 4x4 matrix.
  35922. */
  35923. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35924. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35925. };
  35926. /**
  35927. * Wrapper for addUniform.
  35928. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35929. * @param {number} x
  35930. * @param {number} y
  35931. */
  35932. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35933. var temp = [x, y];
  35934. this.addUniform(name, temp);
  35935. };
  35936. /**
  35937. * Wrapper for addUniform.
  35938. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35939. * @param {number} x
  35940. * @param {number} y
  35941. * @param {number} z
  35942. */
  35943. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35944. var temp = [x, y, z];
  35945. this.addUniform(name, temp);
  35946. };
  35947. /**
  35948. * Wrapper for addUniform.
  35949. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35950. * @param {Color3} color
  35951. */
  35952. UniformBuffer.prototype.addColor3 = function (name, color) {
  35953. var temp = new Array();
  35954. color.toArray(temp);
  35955. this.addUniform(name, temp);
  35956. };
  35957. /**
  35958. * Wrapper for addUniform.
  35959. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35960. * @param {Color3} color
  35961. * @param {number} alpha
  35962. */
  35963. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35964. var temp = new Array();
  35965. color.toArray(temp);
  35966. temp.push(alpha);
  35967. this.addUniform(name, temp);
  35968. };
  35969. /**
  35970. * Wrapper for addUniform.
  35971. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35972. * @param {Vector3} vector
  35973. */
  35974. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35975. var temp = new Array();
  35976. vector.toArray(temp);
  35977. this.addUniform(name, temp);
  35978. };
  35979. /**
  35980. * Wrapper for addUniform.
  35981. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35982. */
  35983. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35984. this.addUniform(name, 12);
  35985. };
  35986. /**
  35987. * Wrapper for addUniform.
  35988. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35989. */
  35990. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35991. this.addUniform(name, 8);
  35992. };
  35993. /**
  35994. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35995. */
  35996. UniformBuffer.prototype.create = function () {
  35997. if (this._noUBO) {
  35998. return;
  35999. }
  36000. if (this._buffer) {
  36001. return; // nothing to do
  36002. }
  36003. // See spec, alignment must be filled as a vec4
  36004. this._fillAlignment(4);
  36005. this._bufferData = new Float32Array(this._data);
  36006. this._rebuild();
  36007. this._needSync = true;
  36008. };
  36009. UniformBuffer.prototype._rebuild = function () {
  36010. if (this._noUBO) {
  36011. return;
  36012. }
  36013. if (this._dynamic) {
  36014. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36015. }
  36016. else {
  36017. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36018. }
  36019. };
  36020. /**
  36021. * Updates the WebGL Uniform Buffer on the GPU.
  36022. * If the `dynamic` flag is set to true, no cache comparison is done.
  36023. * Otherwise, the buffer will be updated only if the cache differs.
  36024. */
  36025. UniformBuffer.prototype.update = function () {
  36026. if (!this._buffer) {
  36027. this.create();
  36028. return;
  36029. }
  36030. if (!this._dynamic && !this._needSync) {
  36031. return;
  36032. }
  36033. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36034. this._needSync = false;
  36035. };
  36036. /**
  36037. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36038. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36039. * @param {number[]|Float32Array} data Flattened data
  36040. * @param {number} size Size of the data.
  36041. */
  36042. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36043. var location = this._uniformLocations[uniformName];
  36044. if (location === undefined) {
  36045. if (this._buffer) {
  36046. // Cannot add an uniform if the buffer is already created
  36047. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36048. return;
  36049. }
  36050. this.addUniform(uniformName, size);
  36051. location = this._uniformLocations[uniformName];
  36052. }
  36053. if (!this._buffer) {
  36054. this.create();
  36055. }
  36056. if (!this._dynamic) {
  36057. // Cache for static uniform buffers
  36058. var changed = false;
  36059. for (var i = 0; i < size; i++) {
  36060. if (this._bufferData[location + i] !== data[i]) {
  36061. changed = true;
  36062. this._bufferData[location + i] = data[i];
  36063. }
  36064. }
  36065. this._needSync = this._needSync || changed;
  36066. }
  36067. else {
  36068. // No cache for dynamic
  36069. for (var i = 0; i < size; i++) {
  36070. this._bufferData[location + i] = data[i];
  36071. }
  36072. }
  36073. };
  36074. // Update methods
  36075. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36076. // To match std140, matrix must be realigned
  36077. for (var i = 0; i < 3; i++) {
  36078. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36079. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36080. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36081. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36082. }
  36083. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36084. };
  36085. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36086. this._currentEffect.setMatrix3x3(name, matrix);
  36087. };
  36088. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36089. this._currentEffect.setMatrix2x2(name, matrix);
  36090. };
  36091. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36092. // To match std140, matrix must be realigned
  36093. for (var i = 0; i < 2; i++) {
  36094. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36095. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36096. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36097. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36098. }
  36099. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36100. };
  36101. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36102. this._currentEffect.setFloat(name, x);
  36103. };
  36104. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36105. UniformBuffer._tempBuffer[0] = x;
  36106. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36107. };
  36108. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36109. if (suffix === void 0) { suffix = ""; }
  36110. this._currentEffect.setFloat2(name + suffix, x, y);
  36111. };
  36112. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36113. if (suffix === void 0) { suffix = ""; }
  36114. UniformBuffer._tempBuffer[0] = x;
  36115. UniformBuffer._tempBuffer[1] = y;
  36116. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36117. };
  36118. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36119. if (suffix === void 0) { suffix = ""; }
  36120. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36121. };
  36122. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36123. if (suffix === void 0) { suffix = ""; }
  36124. UniformBuffer._tempBuffer[0] = x;
  36125. UniformBuffer._tempBuffer[1] = y;
  36126. UniformBuffer._tempBuffer[2] = z;
  36127. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36128. };
  36129. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36130. if (suffix === void 0) { suffix = ""; }
  36131. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36132. };
  36133. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36134. if (suffix === void 0) { suffix = ""; }
  36135. UniformBuffer._tempBuffer[0] = x;
  36136. UniformBuffer._tempBuffer[1] = y;
  36137. UniformBuffer._tempBuffer[2] = z;
  36138. UniformBuffer._tempBuffer[3] = w;
  36139. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36140. };
  36141. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36142. this._currentEffect.setMatrix(name, mat);
  36143. };
  36144. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36145. this.updateUniform(name, mat.toArray(), 16);
  36146. };
  36147. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36148. this._currentEffect.setVector3(name, vector);
  36149. };
  36150. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36151. vector.toArray(UniformBuffer._tempBuffer);
  36152. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36153. };
  36154. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36155. this._currentEffect.setVector4(name, vector);
  36156. };
  36157. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36158. vector.toArray(UniformBuffer._tempBuffer);
  36159. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36160. };
  36161. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36162. if (suffix === void 0) { suffix = ""; }
  36163. this._currentEffect.setColor3(name + suffix, color);
  36164. };
  36165. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36166. if (suffix === void 0) { suffix = ""; }
  36167. color.toArray(UniformBuffer._tempBuffer);
  36168. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36169. };
  36170. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36171. if (suffix === void 0) { suffix = ""; }
  36172. this._currentEffect.setColor4(name + suffix, color, alpha);
  36173. };
  36174. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36175. if (suffix === void 0) { suffix = ""; }
  36176. color.toArray(UniformBuffer._tempBuffer);
  36177. UniformBuffer._tempBuffer[3] = alpha;
  36178. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36179. };
  36180. /**
  36181. * Sets a sampler uniform on the effect.
  36182. * @param {string} name Name of the sampler.
  36183. * @param {Texture} texture
  36184. */
  36185. UniformBuffer.prototype.setTexture = function (name, texture) {
  36186. this._currentEffect.setTexture(name, texture);
  36187. };
  36188. /**
  36189. * Directly updates the value of the uniform in the cache AND on the GPU.
  36190. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36191. * @param {number[]|Float32Array} data Flattened data
  36192. */
  36193. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36194. this.updateUniform(uniformName, data, data.length);
  36195. this.update();
  36196. };
  36197. /**
  36198. * Binds this uniform buffer to an effect.
  36199. * @param {Effect} effect
  36200. * @param {string} name Name of the uniform block in the shader.
  36201. */
  36202. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36203. this._currentEffect = effect;
  36204. if (this._noUBO || !this._buffer) {
  36205. return;
  36206. }
  36207. effect.bindUniformBuffer(this._buffer, name);
  36208. };
  36209. /**
  36210. * Disposes the uniform buffer.
  36211. */
  36212. UniformBuffer.prototype.dispose = function () {
  36213. if (this._noUBO) {
  36214. return;
  36215. }
  36216. var index = this._engine._uniformBuffers.indexOf(this);
  36217. if (index !== -1) {
  36218. this._engine._uniformBuffers.splice(index, 1);
  36219. }
  36220. if (!this._buffer) {
  36221. return;
  36222. }
  36223. if (this._engine._releaseBuffer(this._buffer)) {
  36224. this._buffer = null;
  36225. }
  36226. };
  36227. // Pool for avoiding memory leaks
  36228. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36229. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36230. return UniformBuffer;
  36231. }());
  36232. BABYLON.UniformBuffer = UniformBuffer;
  36233. })(BABYLON || (BABYLON = {}));
  36234. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36235. var BABYLON;
  36236. (function (BABYLON) {
  36237. /**
  36238. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36239. */
  36240. var VertexData = /** @class */ (function () {
  36241. function VertexData() {
  36242. }
  36243. /**
  36244. * Uses the passed data array to set the set the values for the specified kind of data
  36245. * @param data a linear array of floating numbers
  36246. * @param kind the type of data that is being set, eg positions, colors etc
  36247. */
  36248. VertexData.prototype.set = function (data, kind) {
  36249. switch (kind) {
  36250. case BABYLON.VertexBuffer.PositionKind:
  36251. this.positions = data;
  36252. break;
  36253. case BABYLON.VertexBuffer.NormalKind:
  36254. this.normals = data;
  36255. break;
  36256. case BABYLON.VertexBuffer.TangentKind:
  36257. this.tangents = data;
  36258. break;
  36259. case BABYLON.VertexBuffer.UVKind:
  36260. this.uvs = data;
  36261. break;
  36262. case BABYLON.VertexBuffer.UV2Kind:
  36263. this.uvs2 = data;
  36264. break;
  36265. case BABYLON.VertexBuffer.UV3Kind:
  36266. this.uvs3 = data;
  36267. break;
  36268. case BABYLON.VertexBuffer.UV4Kind:
  36269. this.uvs4 = data;
  36270. break;
  36271. case BABYLON.VertexBuffer.UV5Kind:
  36272. this.uvs5 = data;
  36273. break;
  36274. case BABYLON.VertexBuffer.UV6Kind:
  36275. this.uvs6 = data;
  36276. break;
  36277. case BABYLON.VertexBuffer.ColorKind:
  36278. this.colors = data;
  36279. break;
  36280. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36281. this.matricesIndices = data;
  36282. break;
  36283. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36284. this.matricesWeights = data;
  36285. break;
  36286. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36287. this.matricesIndicesExtra = data;
  36288. break;
  36289. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36290. this.matricesWeightsExtra = data;
  36291. break;
  36292. }
  36293. };
  36294. /**
  36295. * Associates the vertexData to the passed Mesh.
  36296. * Sets it as updatable or not (default `false`)
  36297. * @param mesh the mesh the vertexData is applied to
  36298. * @param updatable when used and having the value true allows new data to update the vertexData
  36299. * @returns the VertexData
  36300. */
  36301. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36302. this._applyTo(mesh, updatable);
  36303. return this;
  36304. };
  36305. /**
  36306. * Associates the vertexData to the passed Geometry.
  36307. * Sets it as updatable or not (default `false`)
  36308. * @param geometry the geometry the vertexData is applied to
  36309. * @param updatable when used and having the value true allows new data to update the vertexData
  36310. * @returns VertexData
  36311. */
  36312. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36313. this._applyTo(geometry, updatable);
  36314. return this;
  36315. };
  36316. /**
  36317. * Updates the associated mesh
  36318. * @param mesh the mesh to be updated
  36319. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36320. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36321. * @returns VertexData
  36322. */
  36323. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36324. this._update(mesh);
  36325. return this;
  36326. };
  36327. /**
  36328. * Updates the associated geometry
  36329. * @param geometry the geometry to be updated
  36330. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36331. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36332. * @returns VertexData.
  36333. */
  36334. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36335. this._update(geometry);
  36336. return this;
  36337. };
  36338. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36339. if (updatable === void 0) { updatable = false; }
  36340. if (this.positions) {
  36341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36342. }
  36343. if (this.normals) {
  36344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36345. }
  36346. if (this.tangents) {
  36347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36348. }
  36349. if (this.uvs) {
  36350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36351. }
  36352. if (this.uvs2) {
  36353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36354. }
  36355. if (this.uvs3) {
  36356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36357. }
  36358. if (this.uvs4) {
  36359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36360. }
  36361. if (this.uvs5) {
  36362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36363. }
  36364. if (this.uvs6) {
  36365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36366. }
  36367. if (this.colors) {
  36368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36369. }
  36370. if (this.matricesIndices) {
  36371. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36372. }
  36373. if (this.matricesWeights) {
  36374. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36375. }
  36376. if (this.matricesIndicesExtra) {
  36377. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36378. }
  36379. if (this.matricesWeightsExtra) {
  36380. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36381. }
  36382. if (this.indices) {
  36383. meshOrGeometry.setIndices(this.indices, null, updatable);
  36384. }
  36385. return this;
  36386. };
  36387. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36388. if (this.positions) {
  36389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36390. }
  36391. if (this.normals) {
  36392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36393. }
  36394. if (this.tangents) {
  36395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36396. }
  36397. if (this.uvs) {
  36398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36399. }
  36400. if (this.uvs2) {
  36401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36402. }
  36403. if (this.uvs3) {
  36404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36405. }
  36406. if (this.uvs4) {
  36407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36408. }
  36409. if (this.uvs5) {
  36410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36411. }
  36412. if (this.uvs6) {
  36413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36414. }
  36415. if (this.colors) {
  36416. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36417. }
  36418. if (this.matricesIndices) {
  36419. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36420. }
  36421. if (this.matricesWeights) {
  36422. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36423. }
  36424. if (this.matricesIndicesExtra) {
  36425. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36426. }
  36427. if (this.matricesWeightsExtra) {
  36428. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36429. }
  36430. if (this.indices) {
  36431. meshOrGeometry.setIndices(this.indices, null);
  36432. }
  36433. return this;
  36434. };
  36435. /**
  36436. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36437. * @param matrix the transforming matrix
  36438. * @returns the VertexData
  36439. */
  36440. VertexData.prototype.transform = function (matrix) {
  36441. var transformed = BABYLON.Vector3.Zero();
  36442. var index;
  36443. if (this.positions) {
  36444. var position = BABYLON.Vector3.Zero();
  36445. for (index = 0; index < this.positions.length; index += 3) {
  36446. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36447. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36448. this.positions[index] = transformed.x;
  36449. this.positions[index + 1] = transformed.y;
  36450. this.positions[index + 2] = transformed.z;
  36451. }
  36452. }
  36453. if (this.normals) {
  36454. var normal = BABYLON.Vector3.Zero();
  36455. for (index = 0; index < this.normals.length; index += 3) {
  36456. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36457. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36458. this.normals[index] = transformed.x;
  36459. this.normals[index + 1] = transformed.y;
  36460. this.normals[index + 2] = transformed.z;
  36461. }
  36462. }
  36463. if (this.tangents) {
  36464. var tangent = BABYLON.Vector4.Zero();
  36465. var tangentTransformed = BABYLON.Vector4.Zero();
  36466. for (index = 0; index < this.tangents.length; index += 4) {
  36467. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36468. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36469. this.tangents[index] = tangentTransformed.x;
  36470. this.tangents[index + 1] = tangentTransformed.y;
  36471. this.tangents[index + 2] = tangentTransformed.z;
  36472. this.tangents[index + 3] = tangentTransformed.w;
  36473. }
  36474. }
  36475. return this;
  36476. };
  36477. /**
  36478. * Merges the passed VertexData into the current one
  36479. * @param other the VertexData to be merged into the current one
  36480. * @returns the modified VertexData
  36481. */
  36482. VertexData.prototype.merge = function (other) {
  36483. this._validate();
  36484. other._validate();
  36485. if (!this.normals !== !other.normals ||
  36486. !this.tangents !== !other.tangents ||
  36487. !this.uvs !== !other.uvs ||
  36488. !this.uvs2 !== !other.uvs2 ||
  36489. !this.uvs3 !== !other.uvs3 ||
  36490. !this.uvs4 !== !other.uvs4 ||
  36491. !this.uvs5 !== !other.uvs5 ||
  36492. !this.uvs6 !== !other.uvs6 ||
  36493. !this.colors !== !other.colors ||
  36494. !this.matricesIndices !== !other.matricesIndices ||
  36495. !this.matricesWeights !== !other.matricesWeights ||
  36496. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36497. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36498. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36499. }
  36500. if (other.indices) {
  36501. if (!this.indices) {
  36502. this.indices = [];
  36503. }
  36504. var offset = this.positions ? this.positions.length / 3 : 0;
  36505. for (var index = 0; index < other.indices.length; index++) {
  36506. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36507. this.indices.push(other.indices[index] + offset);
  36508. }
  36509. }
  36510. this.positions = this._mergeElement(this.positions, other.positions);
  36511. this.normals = this._mergeElement(this.normals, other.normals);
  36512. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36513. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36514. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36515. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36516. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36517. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36518. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36519. this.colors = this._mergeElement(this.colors, other.colors);
  36520. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36521. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36522. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36523. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36524. return this;
  36525. };
  36526. VertexData.prototype._mergeElement = function (source, other) {
  36527. if (!source) {
  36528. return other;
  36529. }
  36530. if (!other) {
  36531. return source;
  36532. }
  36533. var len = other.length + source.length;
  36534. var isSrcTypedArray = source instanceof Float32Array;
  36535. var isOthTypedArray = other instanceof Float32Array;
  36536. // use non-loop method when the source is Float32Array
  36537. if (isSrcTypedArray) {
  36538. var ret32 = new Float32Array(len);
  36539. ret32.set(source);
  36540. ret32.set(other, source.length);
  36541. return ret32;
  36542. // source is number[], when other is also use concat
  36543. }
  36544. else if (!isOthTypedArray) {
  36545. return source.concat(other);
  36546. // source is a number[], but other is a Float32Array, loop required
  36547. }
  36548. else {
  36549. var ret = source.slice(0); // copy source to a separate array
  36550. for (var i = 0, len = other.length; i < len; i++) {
  36551. ret.push(other[i]);
  36552. }
  36553. return ret;
  36554. }
  36555. };
  36556. VertexData.prototype._validate = function () {
  36557. if (!this.positions) {
  36558. throw new Error("Positions are required");
  36559. }
  36560. var getElementCount = function (kind, values) {
  36561. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36562. if ((values.length % stride) !== 0) {
  36563. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36564. }
  36565. return values.length / stride;
  36566. };
  36567. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36568. var validateElementCount = function (kind, values) {
  36569. var elementCount = getElementCount(kind, values);
  36570. if (elementCount !== positionsElementCount) {
  36571. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36572. }
  36573. };
  36574. if (this.normals)
  36575. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36576. if (this.tangents)
  36577. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36578. if (this.uvs)
  36579. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36580. if (this.uvs2)
  36581. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36582. if (this.uvs3)
  36583. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36584. if (this.uvs4)
  36585. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36586. if (this.uvs5)
  36587. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36588. if (this.uvs6)
  36589. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36590. if (this.colors)
  36591. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36592. if (this.matricesIndices)
  36593. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36594. if (this.matricesWeights)
  36595. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36596. if (this.matricesIndicesExtra)
  36597. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36598. if (this.matricesWeightsExtra)
  36599. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36600. };
  36601. /**
  36602. * Serializes the VertexData
  36603. * @returns a serialized object
  36604. */
  36605. VertexData.prototype.serialize = function () {
  36606. var serializationObject = this.serialize();
  36607. if (this.positions) {
  36608. serializationObject.positions = this.positions;
  36609. }
  36610. if (this.normals) {
  36611. serializationObject.normals = this.normals;
  36612. }
  36613. if (this.tangents) {
  36614. serializationObject.tangents = this.tangents;
  36615. }
  36616. if (this.uvs) {
  36617. serializationObject.uvs = this.uvs;
  36618. }
  36619. if (this.uvs2) {
  36620. serializationObject.uvs2 = this.uvs2;
  36621. }
  36622. if (this.uvs3) {
  36623. serializationObject.uvs3 = this.uvs3;
  36624. }
  36625. if (this.uvs4) {
  36626. serializationObject.uvs4 = this.uvs4;
  36627. }
  36628. if (this.uvs5) {
  36629. serializationObject.uvs5 = this.uvs5;
  36630. }
  36631. if (this.uvs6) {
  36632. serializationObject.uvs6 = this.uvs6;
  36633. }
  36634. if (this.colors) {
  36635. serializationObject.colors = this.colors;
  36636. }
  36637. if (this.matricesIndices) {
  36638. serializationObject.matricesIndices = this.matricesIndices;
  36639. serializationObject.matricesIndices._isExpanded = true;
  36640. }
  36641. if (this.matricesWeights) {
  36642. serializationObject.matricesWeights = this.matricesWeights;
  36643. }
  36644. if (this.matricesIndicesExtra) {
  36645. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36646. serializationObject.matricesIndicesExtra._isExpanded = true;
  36647. }
  36648. if (this.matricesWeightsExtra) {
  36649. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36650. }
  36651. serializationObject.indices = this.indices;
  36652. return serializationObject;
  36653. };
  36654. // Statics
  36655. /**
  36656. * Extracts the vertexData from a mesh
  36657. * @param mesh the mesh from which to extract the VertexData
  36658. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36659. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36660. * @returns the object VertexData associated to the passed mesh
  36661. */
  36662. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36663. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36664. };
  36665. /**
  36666. * Extracts the vertexData from the geometry
  36667. * @param geometry the geometry from which to extract the VertexData
  36668. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36669. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36670. * @returns the object VertexData associated to the passed mesh
  36671. */
  36672. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36673. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36674. };
  36675. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36676. var result = new VertexData();
  36677. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36678. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36679. }
  36680. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36681. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36682. }
  36683. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36684. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36685. }
  36686. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36687. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36688. }
  36689. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36690. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36691. }
  36692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36693. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36694. }
  36695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36696. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36697. }
  36698. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36699. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36700. }
  36701. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36702. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36703. }
  36704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36705. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36706. }
  36707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36708. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36709. }
  36710. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36711. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36712. }
  36713. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36714. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36715. }
  36716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36717. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36718. }
  36719. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36720. return result;
  36721. };
  36722. /**
  36723. * Creates the VertexData for a Ribbon
  36724. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36725. * * pathArray array of paths, each of which an array of successive Vector3
  36726. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36727. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36728. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36729. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36730. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36731. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36732. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36733. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36734. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36735. * @returns the VertexData of the ribbon
  36736. */
  36737. VertexData.CreateRibbon = function (options) {
  36738. var pathArray = options.pathArray;
  36739. var closeArray = options.closeArray || false;
  36740. var closePath = options.closePath || false;
  36741. var invertUV = options.invertUV || false;
  36742. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36743. var offset = options.offset || defaultOffset;
  36744. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36745. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36746. var customUV = options.uvs;
  36747. var customColors = options.colors;
  36748. var positions = [];
  36749. var indices = [];
  36750. var normals = [];
  36751. var uvs = [];
  36752. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36753. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36754. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36755. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36756. var minlg; // minimal length among all paths from pathArray
  36757. var lg = []; // array of path lengths : nb of vertex per path
  36758. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36759. var p; // path iterator
  36760. var i; // point iterator
  36761. var j; // point iterator
  36762. // if single path in pathArray
  36763. if (pathArray.length < 2) {
  36764. var ar1 = [];
  36765. var ar2 = [];
  36766. for (i = 0; i < pathArray[0].length - offset; i++) {
  36767. ar1.push(pathArray[0][i]);
  36768. ar2.push(pathArray[0][i + offset]);
  36769. }
  36770. pathArray = [ar1, ar2];
  36771. }
  36772. // positions and horizontal distances (u)
  36773. var idc = 0;
  36774. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36775. var path;
  36776. var l;
  36777. minlg = pathArray[0].length;
  36778. var vectlg;
  36779. var dist;
  36780. for (p = 0; p < pathArray.length; p++) {
  36781. uTotalDistance[p] = 0;
  36782. us[p] = [0];
  36783. path = pathArray[p];
  36784. l = path.length;
  36785. minlg = (minlg < l) ? minlg : l;
  36786. j = 0;
  36787. while (j < l) {
  36788. positions.push(path[j].x, path[j].y, path[j].z);
  36789. if (j > 0) {
  36790. vectlg = path[j].subtract(path[j - 1]).length();
  36791. dist = vectlg + uTotalDistance[p];
  36792. us[p].push(dist);
  36793. uTotalDistance[p] = dist;
  36794. }
  36795. j++;
  36796. }
  36797. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36798. j--;
  36799. positions.push(path[0].x, path[0].y, path[0].z);
  36800. vectlg = path[j].subtract(path[0]).length();
  36801. dist = vectlg + uTotalDistance[p];
  36802. us[p].push(dist);
  36803. uTotalDistance[p] = dist;
  36804. }
  36805. lg[p] = l + closePathCorr;
  36806. idx[p] = idc;
  36807. idc += (l + closePathCorr);
  36808. }
  36809. // vertical distances (v)
  36810. var path1;
  36811. var path2;
  36812. var vertex1 = null;
  36813. var vertex2 = null;
  36814. for (i = 0; i < minlg + closePathCorr; i++) {
  36815. vTotalDistance[i] = 0;
  36816. vs[i] = [0];
  36817. for (p = 0; p < pathArray.length - 1; p++) {
  36818. path1 = pathArray[p];
  36819. path2 = pathArray[p + 1];
  36820. if (i === minlg) { // closePath
  36821. vertex1 = path1[0];
  36822. vertex2 = path2[0];
  36823. }
  36824. else {
  36825. vertex1 = path1[i];
  36826. vertex2 = path2[i];
  36827. }
  36828. vectlg = vertex2.subtract(vertex1).length();
  36829. dist = vectlg + vTotalDistance[i];
  36830. vs[i].push(dist);
  36831. vTotalDistance[i] = dist;
  36832. }
  36833. if (closeArray && vertex2 && vertex1) {
  36834. path1 = pathArray[p];
  36835. path2 = pathArray[0];
  36836. if (i === minlg) { // closePath
  36837. vertex2 = path2[0];
  36838. }
  36839. vectlg = vertex2.subtract(vertex1).length();
  36840. dist = vectlg + vTotalDistance[i];
  36841. vTotalDistance[i] = dist;
  36842. }
  36843. }
  36844. // uvs
  36845. var u;
  36846. var v;
  36847. if (customUV) {
  36848. for (p = 0; p < customUV.length; p++) {
  36849. uvs.push(customUV[p].x, customUV[p].y);
  36850. }
  36851. }
  36852. else {
  36853. for (p = 0; p < pathArray.length; p++) {
  36854. for (i = 0; i < minlg + closePathCorr; i++) {
  36855. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36856. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36857. if (invertUV) {
  36858. uvs.push(v, u);
  36859. }
  36860. else {
  36861. uvs.push(u, v);
  36862. }
  36863. }
  36864. }
  36865. }
  36866. // indices
  36867. p = 0; // path index
  36868. var pi = 0; // positions array index
  36869. var l1 = lg[p] - 1; // path1 length
  36870. var l2 = lg[p + 1] - 1; // path2 length
  36871. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36872. var shft = idx[1] - idx[0]; // shift
  36873. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36874. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36875. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  36876. indices.push(pi, pi + shft, pi + 1);
  36877. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36878. pi += 1;
  36879. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36880. p++;
  36881. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36882. shft = idx[0] - idx[p];
  36883. l1 = lg[p] - 1;
  36884. l2 = lg[0] - 1;
  36885. }
  36886. else {
  36887. shft = idx[p + 1] - idx[p];
  36888. l1 = lg[p] - 1;
  36889. l2 = lg[p + 1] - 1;
  36890. }
  36891. pi = idx[p];
  36892. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36893. }
  36894. }
  36895. // normals
  36896. VertexData.ComputeNormals(positions, indices, normals);
  36897. if (closePath) { // update both the first and last vertex normals to their average value
  36898. var indexFirst = 0;
  36899. var indexLast = 0;
  36900. for (p = 0; p < pathArray.length; p++) {
  36901. indexFirst = idx[p] * 3;
  36902. if (p + 1 < pathArray.length) {
  36903. indexLast = (idx[p + 1] - 1) * 3;
  36904. }
  36905. else {
  36906. indexLast = normals.length - 3;
  36907. }
  36908. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36909. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36910. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36911. normals[indexLast] = normals[indexFirst];
  36912. normals[indexLast + 1] = normals[indexFirst + 1];
  36913. normals[indexLast + 2] = normals[indexFirst + 2];
  36914. }
  36915. }
  36916. // sides
  36917. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36918. // Colors
  36919. var colors = null;
  36920. if (customColors) {
  36921. colors = new Float32Array(customColors.length * 4);
  36922. for (var c = 0; c < customColors.length; c++) {
  36923. colors[c * 4] = customColors[c].r;
  36924. colors[c * 4 + 1] = customColors[c].g;
  36925. colors[c * 4 + 2] = customColors[c].b;
  36926. colors[c * 4 + 3] = customColors[c].a;
  36927. }
  36928. }
  36929. // Result
  36930. var vertexData = new VertexData();
  36931. var positions32 = new Float32Array(positions);
  36932. var normals32 = new Float32Array(normals);
  36933. var uvs32 = new Float32Array(uvs);
  36934. vertexData.indices = indices;
  36935. vertexData.positions = positions32;
  36936. vertexData.normals = normals32;
  36937. vertexData.uvs = uvs32;
  36938. if (colors) {
  36939. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36940. }
  36941. if (closePath) {
  36942. vertexData._idx = idx;
  36943. }
  36944. return vertexData;
  36945. };
  36946. /**
  36947. * Creates the VertexData for a box
  36948. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36949. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36950. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36951. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36952. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36953. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36954. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36955. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36956. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36957. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36958. * @returns the VertexData of the box
  36959. */
  36960. VertexData.CreateBox = function (options) {
  36961. var normalsSource = [
  36962. new BABYLON.Vector3(0, 0, 1),
  36963. new BABYLON.Vector3(0, 0, -1),
  36964. new BABYLON.Vector3(1, 0, 0),
  36965. new BABYLON.Vector3(-1, 0, 0),
  36966. new BABYLON.Vector3(0, 1, 0),
  36967. new BABYLON.Vector3(0, -1, 0)
  36968. ];
  36969. var indices = [];
  36970. var positions = [];
  36971. var normals = [];
  36972. var uvs = [];
  36973. var width = options.width || options.size || 1;
  36974. var height = options.height || options.size || 1;
  36975. var depth = options.depth || options.size || 1;
  36976. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36977. var faceUV = options.faceUV || new Array(6);
  36978. var faceColors = options.faceColors;
  36979. var colors = [];
  36980. // default face colors and UV if undefined
  36981. for (var f = 0; f < 6; f++) {
  36982. if (faceUV[f] === undefined) {
  36983. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36984. }
  36985. if (faceColors && faceColors[f] === undefined) {
  36986. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36987. }
  36988. }
  36989. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36990. // Create each face in turn.
  36991. for (var index = 0; index < normalsSource.length; index++) {
  36992. var normal = normalsSource[index];
  36993. // Get two vectors perpendicular to the face normal and to each other.
  36994. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36995. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36996. // Six indices (two triangles) per face.
  36997. var verticesLength = positions.length / 3;
  36998. indices.push(verticesLength);
  36999. indices.push(verticesLength + 1);
  37000. indices.push(verticesLength + 2);
  37001. indices.push(verticesLength);
  37002. indices.push(verticesLength + 2);
  37003. indices.push(verticesLength + 3);
  37004. // Four vertices per face.
  37005. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37006. positions.push(vertex.x, vertex.y, vertex.z);
  37007. normals.push(normal.x, normal.y, normal.z);
  37008. uvs.push(faceUV[index].z, faceUV[index].w);
  37009. if (faceColors) {
  37010. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37011. }
  37012. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37013. positions.push(vertex.x, vertex.y, vertex.z);
  37014. normals.push(normal.x, normal.y, normal.z);
  37015. uvs.push(faceUV[index].x, faceUV[index].w);
  37016. if (faceColors) {
  37017. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37018. }
  37019. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37020. positions.push(vertex.x, vertex.y, vertex.z);
  37021. normals.push(normal.x, normal.y, normal.z);
  37022. uvs.push(faceUV[index].x, faceUV[index].y);
  37023. if (faceColors) {
  37024. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37025. }
  37026. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37027. positions.push(vertex.x, vertex.y, vertex.z);
  37028. normals.push(normal.x, normal.y, normal.z);
  37029. uvs.push(faceUV[index].z, faceUV[index].y);
  37030. if (faceColors) {
  37031. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37032. }
  37033. }
  37034. // sides
  37035. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37036. // Result
  37037. var vertexData = new VertexData();
  37038. vertexData.indices = indices;
  37039. vertexData.positions = positions;
  37040. vertexData.normals = normals;
  37041. vertexData.uvs = uvs;
  37042. if (faceColors) {
  37043. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37044. vertexData.colors = totalColors;
  37045. }
  37046. return vertexData;
  37047. };
  37048. /**
  37049. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37050. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37051. * * segments sets the number of horizontal strips optional, default 32
  37052. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37053. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37054. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37055. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37056. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37057. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37058. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37059. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37060. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37061. * @returns the VertexData of the ellipsoid
  37062. */
  37063. VertexData.CreateSphere = function (options) {
  37064. var segments = options.segments || 32;
  37065. var diameterX = options.diameterX || options.diameter || 1;
  37066. var diameterY = options.diameterY || options.diameter || 1;
  37067. var diameterZ = options.diameterZ || options.diameter || 1;
  37068. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37069. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37070. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37071. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37072. var totalZRotationSteps = 2 + segments;
  37073. var totalYRotationSteps = 2 * totalZRotationSteps;
  37074. var indices = [];
  37075. var positions = [];
  37076. var normals = [];
  37077. var uvs = [];
  37078. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37079. var normalizedZ = zRotationStep / totalZRotationSteps;
  37080. var angleZ = normalizedZ * Math.PI * slice;
  37081. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37082. var normalizedY = yRotationStep / totalYRotationSteps;
  37083. var angleY = normalizedY * Math.PI * 2 * arc;
  37084. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37085. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37086. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37087. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37088. var vertex = complete.multiply(radius);
  37089. var normal = complete.divide(radius).normalize();
  37090. positions.push(vertex.x, vertex.y, vertex.z);
  37091. normals.push(normal.x, normal.y, normal.z);
  37092. uvs.push(normalizedY, normalizedZ);
  37093. }
  37094. if (zRotationStep > 0) {
  37095. var verticesCount = positions.length / 3;
  37096. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37097. indices.push((firstIndex));
  37098. indices.push((firstIndex + 1));
  37099. indices.push(firstIndex + totalYRotationSteps + 1);
  37100. indices.push((firstIndex + totalYRotationSteps + 1));
  37101. indices.push((firstIndex + 1));
  37102. indices.push((firstIndex + totalYRotationSteps + 2));
  37103. }
  37104. }
  37105. }
  37106. // Sides
  37107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37108. // Result
  37109. var vertexData = new VertexData();
  37110. vertexData.indices = indices;
  37111. vertexData.positions = positions;
  37112. vertexData.normals = normals;
  37113. vertexData.uvs = uvs;
  37114. return vertexData;
  37115. };
  37116. /**
  37117. * Creates the VertexData for a cylinder, cone or prism
  37118. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37119. * * height sets the height (y direction) of the cylinder, optional, default 2
  37120. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37121. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37122. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37123. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37124. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37125. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37126. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37127. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37128. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37129. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37130. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37131. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37132. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37133. * @returns the VertexData of the cylinder, cone or prism
  37134. */
  37135. VertexData.CreateCylinder = function (options) {
  37136. var height = options.height || 2;
  37137. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37138. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37139. var tessellation = options.tessellation || 24;
  37140. var subdivisions = options.subdivisions || 1;
  37141. var hasRings = options.hasRings ? true : false;
  37142. var enclose = options.enclose ? true : false;
  37143. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37144. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37145. var faceUV = options.faceUV || new Array(3);
  37146. var faceColors = options.faceColors;
  37147. // default face colors and UV if undefined
  37148. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37149. var ringNb = (hasRings) ? subdivisions : 1;
  37150. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37151. var f;
  37152. for (f = 0; f < surfaceNb; f++) {
  37153. if (faceColors && faceColors[f] === undefined) {
  37154. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37155. }
  37156. }
  37157. for (f = 0; f < surfaceNb; f++) {
  37158. if (faceUV && faceUV[f] === undefined) {
  37159. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37160. }
  37161. }
  37162. var indices = new Array();
  37163. var positions = new Array();
  37164. var normals = new Array();
  37165. var uvs = new Array();
  37166. var colors = new Array();
  37167. var angle_step = Math.PI * 2 * arc / tessellation;
  37168. var angle;
  37169. var h;
  37170. var radius;
  37171. var tan = (diameterBottom - diameterTop) / 2 / height;
  37172. var ringVertex = BABYLON.Vector3.Zero();
  37173. var ringNormal = BABYLON.Vector3.Zero();
  37174. var ringFirstVertex = BABYLON.Vector3.Zero();
  37175. var ringFirstNormal = BABYLON.Vector3.Zero();
  37176. var quadNormal = BABYLON.Vector3.Zero();
  37177. var Y = BABYLON.Axis.Y;
  37178. // positions, normals, uvs
  37179. var i;
  37180. var j;
  37181. var r;
  37182. var ringIdx = 1;
  37183. var s = 1; // surface index
  37184. var cs = 0;
  37185. var v = 0;
  37186. for (i = 0; i <= subdivisions; i++) {
  37187. h = i / subdivisions;
  37188. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37189. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37190. for (r = 0; r < ringIdx; r++) {
  37191. if (hasRings) {
  37192. s += r;
  37193. }
  37194. if (enclose) {
  37195. s += 2 * r;
  37196. }
  37197. for (j = 0; j <= tessellation; j++) {
  37198. angle = j * angle_step;
  37199. // position
  37200. ringVertex.x = Math.cos(-angle) * radius;
  37201. ringVertex.y = -height / 2 + h * height;
  37202. ringVertex.z = Math.sin(-angle) * radius;
  37203. // normal
  37204. if (diameterTop === 0 && i === subdivisions) {
  37205. // if no top cap, reuse former normals
  37206. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37207. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37208. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37209. }
  37210. else {
  37211. ringNormal.x = ringVertex.x;
  37212. ringNormal.z = ringVertex.z;
  37213. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37214. ringNormal.normalize();
  37215. }
  37216. // keep first ring vertex values for enclose
  37217. if (j === 0) {
  37218. ringFirstVertex.copyFrom(ringVertex);
  37219. ringFirstNormal.copyFrom(ringNormal);
  37220. }
  37221. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37222. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37223. if (hasRings) {
  37224. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37225. }
  37226. else {
  37227. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37228. }
  37229. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37230. if (faceColors) {
  37231. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37232. }
  37233. }
  37234. // if enclose, add four vertices and their dedicated normals
  37235. if (arc !== 1 && enclose) {
  37236. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37237. positions.push(0, ringVertex.y, 0);
  37238. positions.push(0, ringVertex.y, 0);
  37239. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37240. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37241. quadNormal.normalize();
  37242. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37243. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37244. quadNormal.normalize();
  37245. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37246. if (hasRings) {
  37247. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37248. }
  37249. else {
  37250. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37251. }
  37252. uvs.push(faceUV[s + 1].x, v);
  37253. uvs.push(faceUV[s + 1].z, v);
  37254. if (hasRings) {
  37255. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37256. }
  37257. else {
  37258. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37259. }
  37260. uvs.push(faceUV[s + 2].x, v);
  37261. uvs.push(faceUV[s + 2].z, v);
  37262. if (faceColors) {
  37263. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37264. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37265. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37266. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37267. }
  37268. }
  37269. if (cs !== s) {
  37270. cs = s;
  37271. }
  37272. }
  37273. }
  37274. // indices
  37275. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37276. var s;
  37277. i = 0;
  37278. for (s = 0; s < subdivisions; s++) {
  37279. var i0 = 0;
  37280. var i1 = 0;
  37281. var i2 = 0;
  37282. var i3 = 0;
  37283. for (j = 0; j < tessellation; j++) {
  37284. i0 = i * (e + 1) + j;
  37285. i1 = (i + 1) * (e + 1) + j;
  37286. i2 = i * (e + 1) + (j + 1);
  37287. i3 = (i + 1) * (e + 1) + (j + 1);
  37288. indices.push(i0, i1, i2);
  37289. indices.push(i3, i2, i1);
  37290. }
  37291. if (arc !== 1 && enclose) { // if enclose, add two quads
  37292. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37293. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37294. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37295. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37296. }
  37297. i = (hasRings) ? (i + 2) : (i + 1);
  37298. }
  37299. // Caps
  37300. var createCylinderCap = function (isTop) {
  37301. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37302. if (radius === 0) {
  37303. return;
  37304. }
  37305. // Cap positions, normals & uvs
  37306. var angle;
  37307. var circleVector;
  37308. var i;
  37309. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37310. var c = null;
  37311. if (faceColors) {
  37312. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37313. }
  37314. // cap center
  37315. var vbase = positions.length / 3;
  37316. var offset = isTop ? height / 2 : -height / 2;
  37317. var center = new BABYLON.Vector3(0, offset, 0);
  37318. positions.push(center.x, center.y, center.z);
  37319. normals.push(0, isTop ? 1 : -1, 0);
  37320. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37321. if (c) {
  37322. colors.push(c.r, c.g, c.b, c.a);
  37323. }
  37324. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37325. for (i = 0; i <= tessellation; i++) {
  37326. angle = Math.PI * 2 * i * arc / tessellation;
  37327. var cos = Math.cos(-angle);
  37328. var sin = Math.sin(-angle);
  37329. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37330. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37331. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37332. normals.push(0, isTop ? 1 : -1, 0);
  37333. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37334. if (c) {
  37335. colors.push(c.r, c.g, c.b, c.a);
  37336. }
  37337. }
  37338. // Cap indices
  37339. for (i = 0; i < tessellation; i++) {
  37340. if (!isTop) {
  37341. indices.push(vbase);
  37342. indices.push(vbase + (i + 1));
  37343. indices.push(vbase + (i + 2));
  37344. }
  37345. else {
  37346. indices.push(vbase);
  37347. indices.push(vbase + (i + 2));
  37348. indices.push(vbase + (i + 1));
  37349. }
  37350. }
  37351. };
  37352. // add caps to geometry
  37353. createCylinderCap(false);
  37354. createCylinderCap(true);
  37355. // Sides
  37356. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37357. var vertexData = new VertexData();
  37358. vertexData.indices = indices;
  37359. vertexData.positions = positions;
  37360. vertexData.normals = normals;
  37361. vertexData.uvs = uvs;
  37362. if (faceColors) {
  37363. vertexData.colors = colors;
  37364. }
  37365. return vertexData;
  37366. };
  37367. /**
  37368. * Creates the VertexData for a torus
  37369. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37370. * * diameter the diameter of the torus, optional default 1
  37371. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37372. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37373. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37374. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37375. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37376. * @returns the VertexData of the torus
  37377. */
  37378. VertexData.CreateTorus = function (options) {
  37379. var indices = [];
  37380. var positions = [];
  37381. var normals = [];
  37382. var uvs = [];
  37383. var diameter = options.diameter || 1;
  37384. var thickness = options.thickness || 0.5;
  37385. var tessellation = options.tessellation || 16;
  37386. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37387. var stride = tessellation + 1;
  37388. for (var i = 0; i <= tessellation; i++) {
  37389. var u = i / tessellation;
  37390. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37391. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37392. for (var j = 0; j <= tessellation; j++) {
  37393. var v = 1 - j / tessellation;
  37394. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37395. var dx = Math.cos(innerAngle);
  37396. var dy = Math.sin(innerAngle);
  37397. // Create a vertex.
  37398. var normal = new BABYLON.Vector3(dx, dy, 0);
  37399. var position = normal.scale(thickness / 2);
  37400. var textureCoordinate = new BABYLON.Vector2(u, v);
  37401. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37402. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37403. positions.push(position.x, position.y, position.z);
  37404. normals.push(normal.x, normal.y, normal.z);
  37405. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37406. // And create indices for two triangles.
  37407. var nextI = (i + 1) % stride;
  37408. var nextJ = (j + 1) % stride;
  37409. indices.push(i * stride + j);
  37410. indices.push(i * stride + nextJ);
  37411. indices.push(nextI * stride + j);
  37412. indices.push(i * stride + nextJ);
  37413. indices.push(nextI * stride + nextJ);
  37414. indices.push(nextI * stride + j);
  37415. }
  37416. }
  37417. // Sides
  37418. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37419. // Result
  37420. var vertexData = new VertexData();
  37421. vertexData.indices = indices;
  37422. vertexData.positions = positions;
  37423. vertexData.normals = normals;
  37424. vertexData.uvs = uvs;
  37425. return vertexData;
  37426. };
  37427. /**
  37428. * Creates the VertexData of the LineSystem
  37429. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37430. * - lines an array of lines, each line being an array of successive Vector3
  37431. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37432. * @returns the VertexData of the LineSystem
  37433. */
  37434. VertexData.CreateLineSystem = function (options) {
  37435. var indices = [];
  37436. var positions = [];
  37437. var lines = options.lines;
  37438. var colors = options.colors;
  37439. var vertexColors = [];
  37440. var idx = 0;
  37441. for (var l = 0; l < lines.length; l++) {
  37442. var points = lines[l];
  37443. for (var index = 0; index < points.length; index++) {
  37444. positions.push(points[index].x, points[index].y, points[index].z);
  37445. if (colors) {
  37446. var color = colors[l];
  37447. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37448. }
  37449. if (index > 0) {
  37450. indices.push(idx - 1);
  37451. indices.push(idx);
  37452. }
  37453. idx++;
  37454. }
  37455. }
  37456. var vertexData = new VertexData();
  37457. vertexData.indices = indices;
  37458. vertexData.positions = positions;
  37459. if (colors) {
  37460. vertexData.colors = vertexColors;
  37461. }
  37462. return vertexData;
  37463. };
  37464. /**
  37465. * Create the VertexData for a DashedLines
  37466. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37467. * - points an array successive Vector3
  37468. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37469. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37470. * - dashNb the intended total number of dashes, optional, default 200
  37471. * @returns the VertexData for the DashedLines
  37472. */
  37473. VertexData.CreateDashedLines = function (options) {
  37474. var dashSize = options.dashSize || 3;
  37475. var gapSize = options.gapSize || 1;
  37476. var dashNb = options.dashNb || 200;
  37477. var points = options.points;
  37478. var positions = new Array();
  37479. var indices = new Array();
  37480. var curvect = BABYLON.Vector3.Zero();
  37481. var lg = 0;
  37482. var nb = 0;
  37483. var shft = 0;
  37484. var dashshft = 0;
  37485. var curshft = 0;
  37486. var idx = 0;
  37487. var i = 0;
  37488. for (i = 0; i < points.length - 1; i++) {
  37489. points[i + 1].subtractToRef(points[i], curvect);
  37490. lg += curvect.length();
  37491. }
  37492. shft = lg / dashNb;
  37493. dashshft = dashSize * shft / (dashSize + gapSize);
  37494. for (i = 0; i < points.length - 1; i++) {
  37495. points[i + 1].subtractToRef(points[i], curvect);
  37496. nb = Math.floor(curvect.length() / shft);
  37497. curvect.normalize();
  37498. for (var j = 0; j < nb; j++) {
  37499. curshft = shft * j;
  37500. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37501. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37502. indices.push(idx, idx + 1);
  37503. idx += 2;
  37504. }
  37505. }
  37506. // Result
  37507. var vertexData = new VertexData();
  37508. vertexData.positions = positions;
  37509. vertexData.indices = indices;
  37510. return vertexData;
  37511. };
  37512. /**
  37513. * Creates the VertexData for a Ground
  37514. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37515. * - width the width (x direction) of the ground, optional, default 1
  37516. * - height the height (z direction) of the ground, optional, default 1
  37517. * - subdivisions the number of subdivisions per side, optional, default 1
  37518. * @returns the VertexData of the Ground
  37519. */
  37520. VertexData.CreateGround = function (options) {
  37521. var indices = [];
  37522. var positions = [];
  37523. var normals = [];
  37524. var uvs = [];
  37525. var row, col;
  37526. var width = options.width || 1;
  37527. var height = options.height || 1;
  37528. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37529. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37530. for (row = 0; row <= subdivisionsY; row++) {
  37531. for (col = 0; col <= subdivisionsX; col++) {
  37532. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37533. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37534. positions.push(position.x, position.y, position.z);
  37535. normals.push(normal.x, normal.y, normal.z);
  37536. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37537. }
  37538. }
  37539. for (row = 0; row < subdivisionsY; row++) {
  37540. for (col = 0; col < subdivisionsX; col++) {
  37541. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37542. indices.push(col + 1 + row * (subdivisionsX + 1));
  37543. indices.push(col + row * (subdivisionsX + 1));
  37544. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37545. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37546. indices.push(col + row * (subdivisionsX + 1));
  37547. }
  37548. }
  37549. // Result
  37550. var vertexData = new VertexData();
  37551. vertexData.indices = indices;
  37552. vertexData.positions = positions;
  37553. vertexData.normals = normals;
  37554. vertexData.uvs = uvs;
  37555. return vertexData;
  37556. };
  37557. /**
  37558. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37559. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37560. * * xmin the ground minimum X coordinate, optional, default -1
  37561. * * zmin the ground minimum Z coordinate, optional, default -1
  37562. * * xmax the ground maximum X coordinate, optional, default 1
  37563. * * zmax the ground maximum Z coordinate, optional, default 1
  37564. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37565. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37566. * @returns the VertexData of the TiledGround
  37567. */
  37568. VertexData.CreateTiledGround = function (options) {
  37569. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37570. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37571. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37572. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37573. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37574. var precision = options.precision || { w: 1, h: 1 };
  37575. var indices = new Array();
  37576. var positions = new Array();
  37577. var normals = new Array();
  37578. var uvs = new Array();
  37579. var row, col, tileRow, tileCol;
  37580. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37581. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37582. precision.w = (precision.w < 1) ? 1 : precision.w;
  37583. precision.h = (precision.h < 1) ? 1 : precision.h;
  37584. var tileSize = {
  37585. 'w': (xmax - xmin) / subdivisions.w,
  37586. 'h': (zmax - zmin) / subdivisions.h
  37587. };
  37588. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37589. // Indices
  37590. var base = positions.length / 3;
  37591. var rowLength = precision.w + 1;
  37592. for (row = 0; row < precision.h; row++) {
  37593. for (col = 0; col < precision.w; col++) {
  37594. var square = [
  37595. base + col + row * rowLength,
  37596. base + (col + 1) + row * rowLength,
  37597. base + (col + 1) + (row + 1) * rowLength,
  37598. base + col + (row + 1) * rowLength
  37599. ];
  37600. indices.push(square[1]);
  37601. indices.push(square[2]);
  37602. indices.push(square[3]);
  37603. indices.push(square[0]);
  37604. indices.push(square[1]);
  37605. indices.push(square[3]);
  37606. }
  37607. }
  37608. // Position, normals and uvs
  37609. var position = BABYLON.Vector3.Zero();
  37610. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37611. for (row = 0; row <= precision.h; row++) {
  37612. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37613. for (col = 0; col <= precision.w; col++) {
  37614. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37615. position.y = 0;
  37616. positions.push(position.x, position.y, position.z);
  37617. normals.push(normal.x, normal.y, normal.z);
  37618. uvs.push(col / precision.w, row / precision.h);
  37619. }
  37620. }
  37621. }
  37622. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37623. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37624. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37625. }
  37626. }
  37627. // Result
  37628. var vertexData = new VertexData();
  37629. vertexData.indices = indices;
  37630. vertexData.positions = positions;
  37631. vertexData.normals = normals;
  37632. vertexData.uvs = uvs;
  37633. return vertexData;
  37634. };
  37635. /**
  37636. * Creates the VertexData of the Ground designed from a heightmap
  37637. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37638. * * width the width (x direction) of the ground
  37639. * * height the height (z direction) of the ground
  37640. * * subdivisions the number of subdivisions per side
  37641. * * minHeight the minimum altitude on the ground, optional, default 0
  37642. * * maxHeight the maximum altitude on the ground, optional default 1
  37643. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37644. * * buffer the array holding the image color data
  37645. * * bufferWidth the width of image
  37646. * * bufferHeight the height of image
  37647. * @returns the VertexData of the Ground designed from a heightmap
  37648. */
  37649. VertexData.CreateGroundFromHeightMap = function (options) {
  37650. var indices = [];
  37651. var positions = [];
  37652. var normals = [];
  37653. var uvs = [];
  37654. var row, col;
  37655. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37656. // Vertices
  37657. for (row = 0; row <= options.subdivisions; row++) {
  37658. for (col = 0; col <= options.subdivisions; col++) {
  37659. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  37660. // Compute height
  37661. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37662. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37663. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37664. var r = options.buffer[pos] / 255.0;
  37665. var g = options.buffer[pos + 1] / 255.0;
  37666. var b = options.buffer[pos + 2] / 255.0;
  37667. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37668. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37669. // Add vertex
  37670. positions.push(position.x, position.y, position.z);
  37671. normals.push(0, 0, 0);
  37672. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37673. }
  37674. }
  37675. // Indices
  37676. for (row = 0; row < options.subdivisions; row++) {
  37677. for (col = 0; col < options.subdivisions; col++) {
  37678. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37679. indices.push(col + 1 + row * (options.subdivisions + 1));
  37680. indices.push(col + row * (options.subdivisions + 1));
  37681. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37682. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37683. indices.push(col + row * (options.subdivisions + 1));
  37684. }
  37685. }
  37686. // Normals
  37687. VertexData.ComputeNormals(positions, indices, normals);
  37688. // Result
  37689. var vertexData = new VertexData();
  37690. vertexData.indices = indices;
  37691. vertexData.positions = positions;
  37692. vertexData.normals = normals;
  37693. vertexData.uvs = uvs;
  37694. return vertexData;
  37695. };
  37696. /**
  37697. * Creates the VertexData for a Plane
  37698. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37699. * * size sets the width and height of the plane to the value of size, optional default 1
  37700. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37701. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37702. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37703. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37704. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37705. * @returns the VertexData of the box
  37706. */
  37707. VertexData.CreatePlane = function (options) {
  37708. var indices = [];
  37709. var positions = [];
  37710. var normals = [];
  37711. var uvs = [];
  37712. var width = options.width || options.size || 1;
  37713. var height = options.height || options.size || 1;
  37714. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37715. // Vertices
  37716. var halfWidth = width / 2.0;
  37717. var halfHeight = height / 2.0;
  37718. positions.push(-halfWidth, -halfHeight, 0);
  37719. normals.push(0, 0, -1.0);
  37720. uvs.push(0.0, 0.0);
  37721. positions.push(halfWidth, -halfHeight, 0);
  37722. normals.push(0, 0, -1.0);
  37723. uvs.push(1.0, 0.0);
  37724. positions.push(halfWidth, halfHeight, 0);
  37725. normals.push(0, 0, -1.0);
  37726. uvs.push(1.0, 1.0);
  37727. positions.push(-halfWidth, halfHeight, 0);
  37728. normals.push(0, 0, -1.0);
  37729. uvs.push(0.0, 1.0);
  37730. // Indices
  37731. indices.push(0);
  37732. indices.push(1);
  37733. indices.push(2);
  37734. indices.push(0);
  37735. indices.push(2);
  37736. indices.push(3);
  37737. // Sides
  37738. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37739. // Result
  37740. var vertexData = new VertexData();
  37741. vertexData.indices = indices;
  37742. vertexData.positions = positions;
  37743. vertexData.normals = normals;
  37744. vertexData.uvs = uvs;
  37745. return vertexData;
  37746. };
  37747. /**
  37748. * Creates the VertexData of the Disc or regular Polygon
  37749. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37750. * * radius the radius of the disc, optional default 0.5
  37751. * * tessellation the number of polygon sides, optional, default 64
  37752. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37753. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37754. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37755. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37756. * @returns the VertexData of the box
  37757. */
  37758. VertexData.CreateDisc = function (options) {
  37759. var positions = new Array();
  37760. var indices = new Array();
  37761. var normals = new Array();
  37762. var uvs = new Array();
  37763. var radius = options.radius || 0.5;
  37764. var tessellation = options.tessellation || 64;
  37765. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37766. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37767. // positions and uvs
  37768. positions.push(0, 0, 0); // disc center first
  37769. uvs.push(0.5, 0.5);
  37770. var theta = Math.PI * 2 * arc;
  37771. var step = theta / tessellation;
  37772. for (var a = 0; a < theta; a += step) {
  37773. var x = Math.cos(a);
  37774. var y = Math.sin(a);
  37775. var u = (x + 1) / 2;
  37776. var v = (1 - y) / 2;
  37777. positions.push(radius * x, radius * y, 0);
  37778. uvs.push(u, v);
  37779. }
  37780. if (arc === 1) {
  37781. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37782. uvs.push(uvs[2], uvs[3]);
  37783. }
  37784. //indices
  37785. var vertexNb = positions.length / 3;
  37786. for (var i = 1; i < vertexNb - 1; i++) {
  37787. indices.push(i + 1, 0, i);
  37788. }
  37789. // result
  37790. VertexData.ComputeNormals(positions, indices, normals);
  37791. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37792. var vertexData = new VertexData();
  37793. vertexData.indices = indices;
  37794. vertexData.positions = positions;
  37795. vertexData.normals = normals;
  37796. vertexData.uvs = uvs;
  37797. return vertexData;
  37798. };
  37799. /**
  37800. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37801. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37802. * @param polygon a mesh built from polygonTriangulation.build()
  37803. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37804. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37805. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37806. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37807. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37808. * @returns the VertexData of the Polygon
  37809. */
  37810. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37811. var faceUV = fUV || new Array(3);
  37812. var faceColors = fColors;
  37813. var colors = [];
  37814. // default face colors and UV if undefined
  37815. for (var f = 0; f < 3; f++) {
  37816. if (faceUV[f] === undefined) {
  37817. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37818. }
  37819. if (faceColors && faceColors[f] === undefined) {
  37820. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37821. }
  37822. }
  37823. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37824. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37825. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37826. var indices = polygon.getIndices();
  37827. // set face colours and textures
  37828. var idx = 0;
  37829. var face = 0;
  37830. for (var index = 0; index < normals.length; index += 3) {
  37831. //Edge Face no. 1
  37832. if (Math.abs(normals[index + 1]) < 0.001) {
  37833. face = 1;
  37834. }
  37835. //Top Face no. 0
  37836. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37837. face = 0;
  37838. }
  37839. //Bottom Face no. 2
  37840. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37841. face = 2;
  37842. }
  37843. idx = index / 3;
  37844. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37845. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37846. if (faceColors) {
  37847. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37848. }
  37849. }
  37850. // sides
  37851. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37852. // Result
  37853. var vertexData = new VertexData();
  37854. vertexData.indices = indices;
  37855. vertexData.positions = positions;
  37856. vertexData.normals = normals;
  37857. vertexData.uvs = uvs;
  37858. if (faceColors) {
  37859. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37860. vertexData.colors = totalColors;
  37861. }
  37862. return vertexData;
  37863. };
  37864. /**
  37865. * Creates the VertexData of the IcoSphere
  37866. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37867. * * radius the radius of the IcoSphere, optional default 1
  37868. * * radiusX allows stretching in the x direction, optional, default radius
  37869. * * radiusY allows stretching in the y direction, optional, default radius
  37870. * * radiusZ allows stretching in the z direction, optional, default radius
  37871. * * flat when true creates a flat shaded mesh, optional, default true
  37872. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37873. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37874. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37875. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37876. * @returns the VertexData of the IcoSphere
  37877. */
  37878. VertexData.CreateIcoSphere = function (options) {
  37879. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37880. var radius = options.radius || 1;
  37881. var flat = (options.flat === undefined) ? true : options.flat;
  37882. var subdivisions = options.subdivisions || 4;
  37883. var radiusX = options.radiusX || radius;
  37884. var radiusY = options.radiusY || radius;
  37885. var radiusZ = options.radiusZ || radius;
  37886. var t = (1 + Math.sqrt(5)) / 2;
  37887. // 12 vertex x,y,z
  37888. var ico_vertices = [
  37889. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37890. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37891. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37892. ];
  37893. // index of 3 vertex makes a face of icopshere
  37894. var ico_indices = [
  37895. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37896. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37897. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37898. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37899. ];
  37900. // vertex for uv have aliased position, not for UV
  37901. var vertices_unalias_id = [
  37902. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37903. // vertex alias
  37904. 0,
  37905. 2,
  37906. 3,
  37907. 3,
  37908. 3,
  37909. 4,
  37910. 7,
  37911. 8,
  37912. 9,
  37913. 9,
  37914. 10,
  37915. 11 // 23: B + 12
  37916. ];
  37917. // uv as integer step (not pixels !)
  37918. var ico_vertexuv = [
  37919. 5, 1, 3, 1, 6, 4, 0, 0,
  37920. 5, 3, 4, 2, 2, 2, 4, 0,
  37921. 2, 0, 1, 1, 6, 0, 6, 2,
  37922. // vertex alias (for same vertex on different faces)
  37923. 0, 4,
  37924. 3, 3,
  37925. 4, 4,
  37926. 3, 1,
  37927. 4, 2,
  37928. 4, 4,
  37929. 0, 2,
  37930. 1, 1,
  37931. 2, 2,
  37932. 3, 3,
  37933. 1, 3,
  37934. 2, 4 // 23: B + 12
  37935. ];
  37936. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37937. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37938. // First island of uv mapping
  37939. // v = 4h 3+ 2
  37940. // v = 3h 9+ 4
  37941. // v = 2h 9+ 5 B
  37942. // v = 1h 9 1 0
  37943. // v = 0h 3 8 7 A
  37944. // u = 0 1 2 3 4 5 6 *a
  37945. // Second island of uv mapping
  37946. // v = 4h 0+ B+ 4+
  37947. // v = 3h A+ 2+
  37948. // v = 2h 7+ 6 3+
  37949. // v = 1h 8+ 3+
  37950. // v = 0h
  37951. // u = 0 1 2 3 4 5 6 *a
  37952. // Face layout on texture UV mapping
  37953. // ============
  37954. // \ 4 /\ 16 / ======
  37955. // \ / \ / /\ 11 /
  37956. // \/ 7 \/ / \ /
  37957. // ======= / 10 \/
  37958. // /\ 17 /\ =======
  37959. // / \ / \ \ 15 /\
  37960. // / 8 \/ 12 \ \ / \
  37961. // ============ \/ 6 \
  37962. // \ 18 /\ ============
  37963. // \ / \ \ 5 /\ 0 /
  37964. // \/ 13 \ \ / \ /
  37965. // ======= \/ 1 \/
  37966. // =============
  37967. // /\ 19 /\ 2 /\
  37968. // / \ / \ / \
  37969. // / 14 \/ 9 \/ 3 \
  37970. // ===================
  37971. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37972. var ustep = 138 / 1024;
  37973. var vstep = 239 / 1024;
  37974. var uoffset = 60 / 1024;
  37975. var voffset = 26 / 1024;
  37976. // Second island should have margin, not to touch the first island
  37977. // avoid any borderline artefact in pixel rounding
  37978. var island_u_offset = -40 / 1024;
  37979. var island_v_offset = +20 / 1024;
  37980. // face is either island 0 or 1 :
  37981. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37982. var island = [
  37983. 0, 0, 0, 0, 1,
  37984. 0, 0, 1, 1, 0,
  37985. 0, 0, 1, 1, 0,
  37986. 0, 1, 1, 1, 0 // 15 - 19
  37987. ];
  37988. var indices = new Array();
  37989. var positions = new Array();
  37990. var normals = new Array();
  37991. var uvs = new Array();
  37992. var current_indice = 0;
  37993. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37994. var face_vertex_pos = new Array(3);
  37995. var face_vertex_uv = new Array(3);
  37996. var v012;
  37997. for (v012 = 0; v012 < 3; v012++) {
  37998. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37999. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38000. }
  38001. // create all with normals
  38002. for (var face = 0; face < 20; face++) {
  38003. // 3 vertex per face
  38004. for (v012 = 0; v012 < 3; v012++) {
  38005. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38006. var v_id = ico_indices[3 * face + v012];
  38007. // vertex have 3D position (x,y,z)
  38008. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  38009. // Normalize to get normal, then scale to radius
  38010. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38011. // uv Coordinates from vertex ID
  38012. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  38013. }
  38014. // Subdivide the face (interpolate pos, norm, uv)
  38015. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38016. // - norm is linear interpolation of vertex corner normal
  38017. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38018. // - uv is linear interpolation
  38019. //
  38020. // Topology is as below for sub-divide by 2
  38021. // vertex shown as v0,v1,v2
  38022. // interp index is i1 to progress in range [v0,v1[
  38023. // interp index is i2 to progress in range [v0,v2[
  38024. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38025. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38026. //
  38027. //
  38028. // i2 v2
  38029. // ^ ^
  38030. // / / \
  38031. // / / \
  38032. // / / \
  38033. // / / (0,1) \
  38034. // / #---------\
  38035. // / / \ (0,0)'/ \
  38036. // / / \ / \
  38037. // / / \ / \
  38038. // / / (0,0) \ / (1,0) \
  38039. // / #---------#---------\
  38040. // v0 v1
  38041. //
  38042. // --------------------> i1
  38043. //
  38044. // interp of (i1,i2):
  38045. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38046. // along i1 : lerp(x0,x1, i1/(S-i2))
  38047. //
  38048. // centroid of triangle is needed to get help normal computation
  38049. // (c1,c2) are used for centroid location
  38050. var interp_vertex = function (i1, i2, c1, c2) {
  38051. // vertex is interpolated from
  38052. // - face_vertex_pos[0..2]
  38053. // - face_vertex_uv[0..2]
  38054. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38055. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38056. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38057. pos_interp.normalize();
  38058. var vertex_normal;
  38059. if (flat) {
  38060. // in flat mode, recalculate normal as face centroid normal
  38061. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38062. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38063. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38064. }
  38065. else {
  38066. // in smooth mode, recalculate normal from each single vertex position
  38067. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38068. }
  38069. // Vertex normal need correction due to X,Y,Z radius scaling
  38070. vertex_normal.x /= radiusX;
  38071. vertex_normal.y /= radiusY;
  38072. vertex_normal.z /= radiusZ;
  38073. vertex_normal.normalize();
  38074. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38075. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38076. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38077. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38078. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38079. uvs.push(uv_interp.x, uv_interp.y);
  38080. // push each vertex has member of a face
  38081. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38082. indices.push(current_indice);
  38083. current_indice++;
  38084. };
  38085. for (var i2 = 0; i2 < subdivisions; i2++) {
  38086. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38087. // face : (i1,i2) for /\ :
  38088. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38089. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38090. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38091. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38092. if (i1 + i2 + 1 < subdivisions) {
  38093. // face : (i1,i2)' for \/ :
  38094. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38095. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38096. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38097. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38098. }
  38099. }
  38100. }
  38101. }
  38102. // Sides
  38103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38104. // Result
  38105. var vertexData = new VertexData();
  38106. vertexData.indices = indices;
  38107. vertexData.positions = positions;
  38108. vertexData.normals = normals;
  38109. vertexData.uvs = uvs;
  38110. return vertexData;
  38111. };
  38112. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38113. /**
  38114. * Creates the VertexData for a Polyhedron
  38115. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38116. * * type provided types are:
  38117. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38118. * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  38119. * * size the size of the IcoSphere, optional default 1
  38120. * * sizeX allows stretching in the x direction, optional, default size
  38121. * * sizeY allows stretching in the y direction, optional, default size
  38122. * * sizeZ allows stretching in the z direction, optional, default size
  38123. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38124. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38125. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38126. * * flat when true creates a flat shaded mesh, optional, default true
  38127. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38128. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38129. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38130. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38131. * @returns the VertexData of the Polyhedron
  38132. */
  38133. VertexData.CreatePolyhedron = function (options) {
  38134. // provided polyhedron types :
  38135. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38136. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  38137. var polyhedra = [];
  38138. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  38139. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  38140. polyhedra[2] = {
  38141. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  38142. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  38143. };
  38144. polyhedra[3] = {
  38145. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  38146. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  38147. };
  38148. polyhedra[4] = {
  38149. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  38150. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  38151. };
  38152. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  38153. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  38154. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  38155. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  38156. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  38157. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  38158. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  38159. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  38160. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  38161. polyhedra[14] = {
  38162. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  38163. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  38164. };
  38165. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38166. var size = options.size;
  38167. var sizeX = options.sizeX || size || 1;
  38168. var sizeY = options.sizeY || size || 1;
  38169. var sizeZ = options.sizeZ || size || 1;
  38170. var data = options.custom || polyhedra[type];
  38171. var nbfaces = data.face.length;
  38172. var faceUV = options.faceUV || new Array(nbfaces);
  38173. var faceColors = options.faceColors;
  38174. var flat = (options.flat === undefined) ? true : options.flat;
  38175. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38176. var positions = new Array();
  38177. var indices = new Array();
  38178. var normals = new Array();
  38179. var uvs = new Array();
  38180. var colors = new Array();
  38181. var index = 0;
  38182. var faceIdx = 0; // face cursor in the array "indexes"
  38183. var indexes = new Array();
  38184. var i = 0;
  38185. var f = 0;
  38186. var u, v, ang, x, y, tmp;
  38187. // default face colors and UV if undefined
  38188. if (flat) {
  38189. for (f = 0; f < nbfaces; f++) {
  38190. if (faceColors && faceColors[f] === undefined) {
  38191. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38192. }
  38193. if (faceUV && faceUV[f] === undefined) {
  38194. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38195. }
  38196. }
  38197. }
  38198. if (!flat) {
  38199. for (i = 0; i < data.vertex.length; i++) {
  38200. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38201. uvs.push(0, 0);
  38202. }
  38203. for (f = 0; f < nbfaces; f++) {
  38204. for (i = 0; i < data.face[f].length - 2; i++) {
  38205. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38206. }
  38207. }
  38208. }
  38209. else {
  38210. for (f = 0; f < nbfaces; f++) {
  38211. var fl = data.face[f].length; // number of vertices of the current face
  38212. ang = 2 * Math.PI / fl;
  38213. x = 0.5 * Math.tan(ang / 2);
  38214. y = 0.5;
  38215. // positions, uvs, colors
  38216. for (i = 0; i < fl; i++) {
  38217. // positions
  38218. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  38219. indexes.push(index);
  38220. index++;
  38221. // uvs
  38222. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38223. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38224. uvs.push(u, v);
  38225. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38226. y = x * Math.sin(ang) + y * Math.cos(ang);
  38227. x = tmp;
  38228. // colors
  38229. if (faceColors) {
  38230. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38231. }
  38232. }
  38233. // indices from indexes
  38234. for (i = 0; i < fl - 2; i++) {
  38235. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38236. }
  38237. faceIdx += fl;
  38238. }
  38239. }
  38240. VertexData.ComputeNormals(positions, indices, normals);
  38241. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38242. var vertexData = new VertexData();
  38243. vertexData.positions = positions;
  38244. vertexData.indices = indices;
  38245. vertexData.normals = normals;
  38246. vertexData.uvs = uvs;
  38247. if (faceColors && flat) {
  38248. vertexData.colors = colors;
  38249. }
  38250. return vertexData;
  38251. };
  38252. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38253. /**
  38254. * Creates the VertexData for a TorusKnot
  38255. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38256. * * radius the radius of the torus knot, optional, default 2
  38257. * * tube the thickness of the tube, optional, default 0.5
  38258. * * radialSegments the number of sides on each tube segments, optional, default 32
  38259. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38260. * * p the number of windings around the z axis, optional, default 2
  38261. * * q the number of windings around the x axis, optional, default 3
  38262. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38263. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38264. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38265. * @returns the VertexData of the Torus Knot
  38266. */
  38267. VertexData.CreateTorusKnot = function (options) {
  38268. var indices = new Array();
  38269. var positions = new Array();
  38270. var normals = new Array();
  38271. var uvs = new Array();
  38272. var radius = options.radius || 2;
  38273. var tube = options.tube || 0.5;
  38274. var radialSegments = options.radialSegments || 32;
  38275. var tubularSegments = options.tubularSegments || 32;
  38276. var p = options.p || 2;
  38277. var q = options.q || 3;
  38278. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38279. // Helper
  38280. var getPos = function (angle) {
  38281. var cu = Math.cos(angle);
  38282. var su = Math.sin(angle);
  38283. var quOverP = q / p * angle;
  38284. var cs = Math.cos(quOverP);
  38285. var tx = radius * (2 + cs) * 0.5 * cu;
  38286. var ty = radius * (2 + cs) * su * 0.5;
  38287. var tz = radius * Math.sin(quOverP) * 0.5;
  38288. return new BABYLON.Vector3(tx, ty, tz);
  38289. };
  38290. // Vertices
  38291. var i;
  38292. var j;
  38293. for (i = 0; i <= radialSegments; i++) {
  38294. var modI = i % radialSegments;
  38295. var u = modI / radialSegments * 2 * p * Math.PI;
  38296. var p1 = getPos(u);
  38297. var p2 = getPos(u + 0.01);
  38298. var tang = p2.subtract(p1);
  38299. var n = p2.add(p1);
  38300. var bitan = BABYLON.Vector3.Cross(tang, n);
  38301. n = BABYLON.Vector3.Cross(bitan, tang);
  38302. bitan.normalize();
  38303. n.normalize();
  38304. for (j = 0; j < tubularSegments; j++) {
  38305. var modJ = j % tubularSegments;
  38306. var v = modJ / tubularSegments * 2 * Math.PI;
  38307. var cx = -tube * Math.cos(v);
  38308. var cy = tube * Math.sin(v);
  38309. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38310. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38311. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38312. uvs.push(i / radialSegments);
  38313. uvs.push(j / tubularSegments);
  38314. }
  38315. }
  38316. for (i = 0; i < radialSegments; i++) {
  38317. for (j = 0; j < tubularSegments; j++) {
  38318. var jNext = (j + 1) % tubularSegments;
  38319. var a = i * tubularSegments + j;
  38320. var b = (i + 1) * tubularSegments + j;
  38321. var c = (i + 1) * tubularSegments + jNext;
  38322. var d = i * tubularSegments + jNext;
  38323. indices.push(d);
  38324. indices.push(b);
  38325. indices.push(a);
  38326. indices.push(d);
  38327. indices.push(c);
  38328. indices.push(b);
  38329. }
  38330. }
  38331. // Normals
  38332. VertexData.ComputeNormals(positions, indices, normals);
  38333. // Sides
  38334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38335. // Result
  38336. var vertexData = new VertexData();
  38337. vertexData.indices = indices;
  38338. vertexData.positions = positions;
  38339. vertexData.normals = normals;
  38340. vertexData.uvs = uvs;
  38341. return vertexData;
  38342. };
  38343. // Tools
  38344. /**
  38345. * Compute normals for given positions and indices
  38346. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38347. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38348. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38349. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38350. * * facetNormals : optional array of facet normals (vector3)
  38351. * * facetPositions : optional array of facet positions (vector3)
  38352. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38353. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38354. * * bInfo : optional bounding info, required for facetPartitioning computation
  38355. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38356. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38357. * * useRightHandedSystem: optional boolean to for right handed system computation
  38358. * * depthSort : optional boolean to enable the facet depth sort computation
  38359. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38360. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38361. */
  38362. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38363. // temporary scalar variables
  38364. var index = 0; // facet index
  38365. var p1p2x = 0.0; // p1p2 vector x coordinate
  38366. var p1p2y = 0.0; // p1p2 vector y coordinate
  38367. var p1p2z = 0.0; // p1p2 vector z coordinate
  38368. var p3p2x = 0.0; // p3p2 vector x coordinate
  38369. var p3p2y = 0.0; // p3p2 vector y coordinate
  38370. var p3p2z = 0.0; // p3p2 vector z coordinate
  38371. var faceNormalx = 0.0; // facet normal x coordinate
  38372. var faceNormaly = 0.0; // facet normal y coordinate
  38373. var faceNormalz = 0.0; // facet normal z coordinate
  38374. var length = 0.0; // facet normal length before normalization
  38375. var v1x = 0; // vector1 x index in the positions array
  38376. var v1y = 0; // vector1 y index in the positions array
  38377. var v1z = 0; // vector1 z index in the positions array
  38378. var v2x = 0; // vector2 x index in the positions array
  38379. var v2y = 0; // vector2 y index in the positions array
  38380. var v2z = 0; // vector2 z index in the positions array
  38381. var v3x = 0; // vector3 x index in the positions array
  38382. var v3y = 0; // vector3 y index in the positions array
  38383. var v3z = 0; // vector3 z index in the positions array
  38384. var computeFacetNormals = false;
  38385. var computeFacetPositions = false;
  38386. var computeFacetPartitioning = false;
  38387. var computeDepthSort = false;
  38388. var faceNormalSign = 1;
  38389. var ratio = 0;
  38390. var distanceTo = null;
  38391. if (options) {
  38392. computeFacetNormals = (options.facetNormals) ? true : false;
  38393. computeFacetPositions = (options.facetPositions) ? true : false;
  38394. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38395. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38396. ratio = options.ratio || 0;
  38397. computeDepthSort = (options.depthSort) ? true : false;
  38398. distanceTo = (options.distanceTo);
  38399. if (computeDepthSort) {
  38400. if (distanceTo === undefined) {
  38401. distanceTo = BABYLON.Vector3.Zero();
  38402. }
  38403. var depthSortedFacets = options.depthSortedFacets;
  38404. }
  38405. }
  38406. // facetPartitioning reinit if needed
  38407. var xSubRatio = 0;
  38408. var ySubRatio = 0;
  38409. var zSubRatio = 0;
  38410. var subSq = 0;
  38411. if (computeFacetPartitioning && options && options.bbSize) {
  38412. var ox = 0; // X partitioning index for facet position
  38413. var oy = 0; // Y partinioning index for facet position
  38414. var oz = 0; // Z partinioning index for facet position
  38415. var b1x = 0; // X partitioning index for facet v1 vertex
  38416. var b1y = 0; // Y partitioning index for facet v1 vertex
  38417. var b1z = 0; // z partitioning index for facet v1 vertex
  38418. var b2x = 0; // X partitioning index for facet v2 vertex
  38419. var b2y = 0; // Y partitioning index for facet v2 vertex
  38420. var b2z = 0; // Z partitioning index for facet v2 vertex
  38421. var b3x = 0; // X partitioning index for facet v3 vertex
  38422. var b3y = 0; // Y partitioning index for facet v3 vertex
  38423. var b3z = 0; // Z partitioning index for facet v3 vertex
  38424. var block_idx_o = 0; // facet barycenter block index
  38425. var block_idx_v1 = 0; // v1 vertex block index
  38426. var block_idx_v2 = 0; // v2 vertex block index
  38427. var block_idx_v3 = 0; // v3 vertex block index
  38428. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38429. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38430. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38431. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38432. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38433. subSq = options.subDiv.max * options.subDiv.max;
  38434. options.facetPartitioning.length = 0;
  38435. }
  38436. // reset the normals
  38437. for (index = 0; index < positions.length; index++) {
  38438. normals[index] = 0.0;
  38439. }
  38440. // Loop : 1 indice triplet = 1 facet
  38441. var nbFaces = (indices.length / 3) | 0;
  38442. for (index = 0; index < nbFaces; index++) {
  38443. // get the indexes of the coordinates of each vertex of the facet
  38444. v1x = indices[index * 3] * 3;
  38445. v1y = v1x + 1;
  38446. v1z = v1x + 2;
  38447. v2x = indices[index * 3 + 1] * 3;
  38448. v2y = v2x + 1;
  38449. v2z = v2x + 2;
  38450. v3x = indices[index * 3 + 2] * 3;
  38451. v3y = v3x + 1;
  38452. v3z = v3x + 2;
  38453. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38454. p1p2y = positions[v1y] - positions[v2y];
  38455. p1p2z = positions[v1z] - positions[v2z];
  38456. p3p2x = positions[v3x] - positions[v2x];
  38457. p3p2y = positions[v3y] - positions[v2y];
  38458. p3p2z = positions[v3z] - positions[v2z];
  38459. // compute the face normal with the cross product
  38460. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38461. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38462. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38463. // normalize this normal and store it in the array facetData
  38464. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38465. length = (length === 0) ? 1.0 : length;
  38466. faceNormalx /= length;
  38467. faceNormaly /= length;
  38468. faceNormalz /= length;
  38469. if (computeFacetNormals && options) {
  38470. options.facetNormals[index].x = faceNormalx;
  38471. options.facetNormals[index].y = faceNormaly;
  38472. options.facetNormals[index].z = faceNormalz;
  38473. }
  38474. if (computeFacetPositions && options) {
  38475. // compute and the facet barycenter coordinates in the array facetPositions
  38476. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38477. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38478. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38479. }
  38480. if (computeFacetPartitioning && options) {
  38481. // store the facet indexes in arrays in the main facetPartitioning array :
  38482. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38483. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38484. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38485. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38486. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38487. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38488. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38489. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38490. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38491. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38492. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38493. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38494. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38495. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38496. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38497. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38498. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38499. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38500. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38501. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38502. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38503. // push each facet index in each block containing the vertex
  38504. options.facetPartitioning[block_idx_v1].push(index);
  38505. if (block_idx_v2 != block_idx_v1) {
  38506. options.facetPartitioning[block_idx_v2].push(index);
  38507. }
  38508. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38509. options.facetPartitioning[block_idx_v3].push(index);
  38510. }
  38511. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38512. options.facetPartitioning[block_idx_o].push(index);
  38513. }
  38514. }
  38515. if (computeDepthSort && options && options.facetPositions) {
  38516. var dsf = depthSortedFacets[index];
  38517. dsf.ind = index * 3;
  38518. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38519. }
  38520. // compute the normals anyway
  38521. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38522. normals[v1y] += faceNormaly;
  38523. normals[v1z] += faceNormalz;
  38524. normals[v2x] += faceNormalx;
  38525. normals[v2y] += faceNormaly;
  38526. normals[v2z] += faceNormalz;
  38527. normals[v3x] += faceNormalx;
  38528. normals[v3y] += faceNormaly;
  38529. normals[v3z] += faceNormalz;
  38530. }
  38531. // last normalization of each normal
  38532. for (index = 0; index < normals.length / 3; index++) {
  38533. faceNormalx = normals[index * 3];
  38534. faceNormaly = normals[index * 3 + 1];
  38535. faceNormalz = normals[index * 3 + 2];
  38536. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38537. length = (length === 0) ? 1.0 : length;
  38538. faceNormalx /= length;
  38539. faceNormaly /= length;
  38540. faceNormalz /= length;
  38541. normals[index * 3] = faceNormalx;
  38542. normals[index * 3 + 1] = faceNormaly;
  38543. normals[index * 3 + 2] = faceNormalz;
  38544. }
  38545. };
  38546. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38547. var li = indices.length;
  38548. var ln = normals.length;
  38549. var i;
  38550. var n;
  38551. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38552. switch (sideOrientation) {
  38553. case BABYLON.Mesh.FRONTSIDE:
  38554. // nothing changed
  38555. break;
  38556. case BABYLON.Mesh.BACKSIDE:
  38557. var tmp;
  38558. // indices
  38559. for (i = 0; i < li; i += 3) {
  38560. tmp = indices[i];
  38561. indices[i] = indices[i + 2];
  38562. indices[i + 2] = tmp;
  38563. }
  38564. // normals
  38565. for (n = 0; n < ln; n++) {
  38566. normals[n] = -normals[n];
  38567. }
  38568. break;
  38569. case BABYLON.Mesh.DOUBLESIDE:
  38570. // positions
  38571. var lp = positions.length;
  38572. var l = lp / 3;
  38573. for (var p = 0; p < lp; p++) {
  38574. positions[lp + p] = positions[p];
  38575. }
  38576. // indices
  38577. for (i = 0; i < li; i += 3) {
  38578. indices[i + li] = indices[i + 2] + l;
  38579. indices[i + 1 + li] = indices[i + 1] + l;
  38580. indices[i + 2 + li] = indices[i] + l;
  38581. }
  38582. // normals
  38583. for (n = 0; n < ln; n++) {
  38584. normals[ln + n] = -normals[n];
  38585. }
  38586. // uvs
  38587. var lu = uvs.length;
  38588. var u = 0;
  38589. for (u = 0; u < lu; u++) {
  38590. uvs[u + lu] = uvs[u];
  38591. }
  38592. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38593. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38594. u = 0;
  38595. for (i = 0; i < lu / 2; i++) {
  38596. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38597. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38598. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38599. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38600. u += 2;
  38601. }
  38602. break;
  38603. }
  38604. };
  38605. /**
  38606. * Applies VertexData created from the imported parameters to the geometry
  38607. * @param parsedVertexData the parsed data from an imported file
  38608. * @param geometry the geometry to apply the VertexData to
  38609. */
  38610. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38611. var vertexData = new VertexData();
  38612. // positions
  38613. var positions = parsedVertexData.positions;
  38614. if (positions) {
  38615. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38616. }
  38617. // normals
  38618. var normals = parsedVertexData.normals;
  38619. if (normals) {
  38620. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38621. }
  38622. // tangents
  38623. var tangents = parsedVertexData.tangents;
  38624. if (tangents) {
  38625. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38626. }
  38627. // uvs
  38628. var uvs = parsedVertexData.uvs;
  38629. if (uvs) {
  38630. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38631. }
  38632. // uv2s
  38633. var uv2s = parsedVertexData.uv2s;
  38634. if (uv2s) {
  38635. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38636. }
  38637. // uv3s
  38638. var uv3s = parsedVertexData.uv3s;
  38639. if (uv3s) {
  38640. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38641. }
  38642. // uv4s
  38643. var uv4s = parsedVertexData.uv4s;
  38644. if (uv4s) {
  38645. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38646. }
  38647. // uv5s
  38648. var uv5s = parsedVertexData.uv5s;
  38649. if (uv5s) {
  38650. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38651. }
  38652. // uv6s
  38653. var uv6s = parsedVertexData.uv6s;
  38654. if (uv6s) {
  38655. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38656. }
  38657. // colors
  38658. var colors = parsedVertexData.colors;
  38659. if (colors) {
  38660. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38661. }
  38662. // matricesIndices
  38663. var matricesIndices = parsedVertexData.matricesIndices;
  38664. if (matricesIndices) {
  38665. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38666. }
  38667. // matricesWeights
  38668. var matricesWeights = parsedVertexData.matricesWeights;
  38669. if (matricesWeights) {
  38670. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38671. }
  38672. // indices
  38673. var indices = parsedVertexData.indices;
  38674. if (indices) {
  38675. vertexData.indices = indices;
  38676. }
  38677. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38678. };
  38679. return VertexData;
  38680. }());
  38681. BABYLON.VertexData = VertexData;
  38682. })(BABYLON || (BABYLON = {}));
  38683. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38684. var BABYLON;
  38685. (function (BABYLON) {
  38686. /**
  38687. * Class used to store geometry data (vertex buffers + index buffer)
  38688. */
  38689. var Geometry = /** @class */ (function () {
  38690. /**
  38691. * Creates a new geometry
  38692. * @param id defines the unique ID
  38693. * @param scene defines the hosting scene
  38694. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38695. * @param updatable defines if geometry must be updatable (false by default)
  38696. * @param mesh defines the mesh that will be associated with the geometry
  38697. */
  38698. function Geometry(id, scene, vertexData, updatable, mesh) {
  38699. if (updatable === void 0) { updatable = false; }
  38700. if (mesh === void 0) { mesh = null; }
  38701. /**
  38702. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38703. */
  38704. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38705. this._totalVertices = 0;
  38706. this._isDisposed = false;
  38707. this._indexBufferIsUpdatable = false;
  38708. this.id = id;
  38709. this._engine = scene.getEngine();
  38710. this._meshes = [];
  38711. this._scene = scene;
  38712. //Init vertex buffer cache
  38713. this._vertexBuffers = {};
  38714. this._indices = [];
  38715. this._updatable = updatable;
  38716. // vertexData
  38717. if (vertexData) {
  38718. this.setAllVerticesData(vertexData, updatable);
  38719. }
  38720. else {
  38721. this._totalVertices = 0;
  38722. this._indices = [];
  38723. }
  38724. if (this._engine.getCaps().vertexArrayObject) {
  38725. this._vertexArrayObjects = {};
  38726. }
  38727. // applyToMesh
  38728. if (mesh) {
  38729. if (mesh.getClassName() === "LinesMesh") {
  38730. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38731. this._updateExtend();
  38732. }
  38733. this.applyToMesh(mesh);
  38734. mesh.computeWorldMatrix(true);
  38735. }
  38736. }
  38737. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38738. /**
  38739. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  38740. */
  38741. get: function () {
  38742. return this._boundingBias;
  38743. },
  38744. /**
  38745. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  38746. */
  38747. set: function (value) {
  38748. if (this._boundingBias && this._boundingBias.equals(value)) {
  38749. return;
  38750. }
  38751. this._boundingBias = value.clone();
  38752. this._updateBoundingInfo(true, null);
  38753. },
  38754. enumerable: true,
  38755. configurable: true
  38756. });
  38757. /**
  38758. * Static function used to attach a new empty geometry to a mesh
  38759. * @param mesh defines the mesh to attach the geometry to
  38760. * @returns the new {BABYLON.Geometry}
  38761. */
  38762. Geometry.CreateGeometryForMesh = function (mesh) {
  38763. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38764. geometry.applyToMesh(mesh);
  38765. return geometry;
  38766. };
  38767. Object.defineProperty(Geometry.prototype, "extend", {
  38768. /**
  38769. * Gets the current extend of the geometry
  38770. */
  38771. get: function () {
  38772. return this._extend;
  38773. },
  38774. enumerable: true,
  38775. configurable: true
  38776. });
  38777. /**
  38778. * Gets the hosting scene
  38779. * @returns the hosting {BABYLON.Scene}
  38780. */
  38781. Geometry.prototype.getScene = function () {
  38782. return this._scene;
  38783. };
  38784. /**
  38785. * Gets the hosting engine
  38786. * @returns the hosting {BABYLON.Engine}
  38787. */
  38788. Geometry.prototype.getEngine = function () {
  38789. return this._engine;
  38790. };
  38791. /**
  38792. * Defines if the geometry is ready to use
  38793. * @returns true if the geometry is ready to be used
  38794. */
  38795. Geometry.prototype.isReady = function () {
  38796. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38797. };
  38798. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38799. /**
  38800. * Gets a value indicating that the geometry should not be serialized
  38801. */
  38802. get: function () {
  38803. for (var index = 0; index < this._meshes.length; index++) {
  38804. if (!this._meshes[index].doNotSerialize) {
  38805. return false;
  38806. }
  38807. }
  38808. return true;
  38809. },
  38810. enumerable: true,
  38811. configurable: true
  38812. });
  38813. /** @hidden */
  38814. Geometry.prototype._rebuild = function () {
  38815. if (this._vertexArrayObjects) {
  38816. this._vertexArrayObjects = {};
  38817. }
  38818. // Index buffer
  38819. if (this._meshes.length !== 0 && this._indices) {
  38820. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38821. }
  38822. // Vertex buffers
  38823. for (var key in this._vertexBuffers) {
  38824. var vertexBuffer = this._vertexBuffers[key];
  38825. vertexBuffer._rebuild();
  38826. }
  38827. };
  38828. /**
  38829. * Affects all gemetry data in one call
  38830. * @param vertexData defines the geometry data
  38831. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38832. */
  38833. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38834. vertexData.applyToGeometry(this, updatable);
  38835. this.notifyUpdate();
  38836. };
  38837. /**
  38838. * Set specific vertex data
  38839. * @param kind defines the data kind (Position, normal, etc...)
  38840. * @param data defines the vertex data to use
  38841. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38842. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38843. */
  38844. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38845. if (updatable === void 0) { updatable = false; }
  38846. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38847. this.setVerticesBuffer(buffer);
  38848. };
  38849. /**
  38850. * Removes a specific vertex data
  38851. * @param kind defines the data kind (Position, normal, etc...)
  38852. */
  38853. Geometry.prototype.removeVerticesData = function (kind) {
  38854. if (this._vertexBuffers[kind]) {
  38855. this._vertexBuffers[kind].dispose();
  38856. delete this._vertexBuffers[kind];
  38857. }
  38858. };
  38859. /**
  38860. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38861. * @param buffer defines the vertex buffer to use
  38862. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38863. */
  38864. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38865. if (totalVertices === void 0) { totalVertices = null; }
  38866. var kind = buffer.getKind();
  38867. if (this._vertexBuffers[kind]) {
  38868. this._vertexBuffers[kind].dispose();
  38869. }
  38870. this._vertexBuffers[kind] = buffer;
  38871. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38872. var data = buffer.getData();
  38873. if (totalVertices != null) {
  38874. this._totalVertices = totalVertices;
  38875. }
  38876. else {
  38877. if (data != null) {
  38878. this._totalVertices = data.length / (buffer.byteStride / 4);
  38879. }
  38880. }
  38881. this._updateExtend(data);
  38882. this._resetPointsArrayCache();
  38883. var meshes = this._meshes;
  38884. var numOfMeshes = meshes.length;
  38885. for (var index = 0; index < numOfMeshes; index++) {
  38886. var mesh = meshes[index];
  38887. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38888. mesh._createGlobalSubMesh(false);
  38889. mesh.computeWorldMatrix(true);
  38890. }
  38891. }
  38892. this.notifyUpdate(kind);
  38893. if (this._vertexArrayObjects) {
  38894. this._disposeVertexArrayObjects();
  38895. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38896. }
  38897. };
  38898. /**
  38899. * Update a specific vertex buffer
  38900. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38901. * It will do nothing if the buffer is not updatable
  38902. * @param kind defines the data kind (Position, normal, etc...)
  38903. * @param data defines the data to use
  38904. * @param offset defines the offset in the target buffer where to store the data
  38905. * @param useBytes set to true if the offset is in bytes
  38906. */
  38907. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38908. if (useBytes === void 0) { useBytes = false; }
  38909. var vertexBuffer = this.getVertexBuffer(kind);
  38910. if (!vertexBuffer) {
  38911. return;
  38912. }
  38913. vertexBuffer.updateDirectly(data, offset, useBytes);
  38914. this.notifyUpdate(kind);
  38915. };
  38916. /**
  38917. * Update a specific vertex buffer
  38918. * This function will create a new buffer if the current one is not updatable
  38919. * @param kind defines the data kind (Position, normal, etc...)
  38920. * @param data defines the data to use
  38921. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38922. */
  38923. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38924. if (updateExtends === void 0) { updateExtends = false; }
  38925. var vertexBuffer = this.getVertexBuffer(kind);
  38926. if (!vertexBuffer) {
  38927. return;
  38928. }
  38929. vertexBuffer.update(data);
  38930. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38931. this._updateBoundingInfo(updateExtends, data);
  38932. }
  38933. this.notifyUpdate(kind);
  38934. };
  38935. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38936. if (updateExtends) {
  38937. this._updateExtend(data);
  38938. }
  38939. var meshes = this._meshes;
  38940. var numOfMeshes = meshes.length;
  38941. this._resetPointsArrayCache();
  38942. for (var index = 0; index < numOfMeshes; index++) {
  38943. var mesh = meshes[index];
  38944. if (updateExtends) {
  38945. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38946. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38947. var subMesh = mesh.subMeshes[subIndex];
  38948. subMesh.refreshBoundingInfo();
  38949. }
  38950. }
  38951. }
  38952. };
  38953. /** @hidden */
  38954. Geometry.prototype._bind = function (effect, indexToBind) {
  38955. if (!effect) {
  38956. return;
  38957. }
  38958. if (indexToBind === undefined) {
  38959. indexToBind = this._indexBuffer;
  38960. }
  38961. var vbs = this.getVertexBuffers();
  38962. if (!vbs) {
  38963. return;
  38964. }
  38965. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38966. this._engine.bindBuffers(vbs, indexToBind, effect);
  38967. return;
  38968. }
  38969. // Using VAO
  38970. if (!this._vertexArrayObjects[effect.key]) {
  38971. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38972. }
  38973. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38974. };
  38975. /**
  38976. * Gets total number of vertices
  38977. * @returns the total number of vertices
  38978. */
  38979. Geometry.prototype.getTotalVertices = function () {
  38980. if (!this.isReady()) {
  38981. return 0;
  38982. }
  38983. return this._totalVertices;
  38984. };
  38985. /**
  38986. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38987. * @param kind defines the data kind (Position, normal, etc...)
  38988. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38989. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38990. * @returns a float array containing vertex data
  38991. */
  38992. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38993. var vertexBuffer = this.getVertexBuffer(kind);
  38994. if (!vertexBuffer) {
  38995. return null;
  38996. }
  38997. var data = vertexBuffer.getData();
  38998. if (!data) {
  38999. return null;
  39000. }
  39001. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39002. var count = this._totalVertices * vertexBuffer.getSize();
  39003. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39004. var copy_1 = new Array(count);
  39005. vertexBuffer.forEach(count, function (value, index) {
  39006. copy_1[index] = value;
  39007. });
  39008. return copy_1;
  39009. }
  39010. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39011. if (data instanceof Array) {
  39012. var offset = vertexBuffer.byteOffset / 4;
  39013. return BABYLON.Tools.Slice(data, offset, offset + count);
  39014. }
  39015. else if (data instanceof ArrayBuffer) {
  39016. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39017. }
  39018. else {
  39019. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39020. }
  39021. }
  39022. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39023. return BABYLON.Tools.Slice(data);
  39024. }
  39025. return data;
  39026. };
  39027. /**
  39028. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39029. * @param kind defines the data kind (Position, normal, etc...)
  39030. * @returns true if the vertex buffer with the specified kind is updatable
  39031. */
  39032. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39033. var vb = this._vertexBuffers[kind];
  39034. if (!vb) {
  39035. return false;
  39036. }
  39037. return vb.isUpdatable();
  39038. };
  39039. /**
  39040. * Gets a specific vertex buffer
  39041. * @param kind defines the data kind (Position, normal, etc...)
  39042. * @returns a {BABYLON.VertexBuffer}
  39043. */
  39044. Geometry.prototype.getVertexBuffer = function (kind) {
  39045. if (!this.isReady()) {
  39046. return null;
  39047. }
  39048. return this._vertexBuffers[kind];
  39049. };
  39050. /**
  39051. * Returns all vertex buffers
  39052. * @return an object holding all vertex buffers indexed by kind
  39053. */
  39054. Geometry.prototype.getVertexBuffers = function () {
  39055. if (!this.isReady()) {
  39056. return null;
  39057. }
  39058. return this._vertexBuffers;
  39059. };
  39060. /**
  39061. * Gets a boolean indicating if specific vertex buffer is present
  39062. * @param kind defines the data kind (Position, normal, etc...)
  39063. * @returns true if data is present
  39064. */
  39065. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39066. if (!this._vertexBuffers) {
  39067. if (this._delayInfo) {
  39068. return this._delayInfo.indexOf(kind) !== -1;
  39069. }
  39070. return false;
  39071. }
  39072. return this._vertexBuffers[kind] !== undefined;
  39073. };
  39074. /**
  39075. * Gets a list of all attached data kinds (Position, normal, etc...)
  39076. * @returns a list of string containing all kinds
  39077. */
  39078. Geometry.prototype.getVerticesDataKinds = function () {
  39079. var result = [];
  39080. var kind;
  39081. if (!this._vertexBuffers && this._delayInfo) {
  39082. for (kind in this._delayInfo) {
  39083. result.push(kind);
  39084. }
  39085. }
  39086. else {
  39087. for (kind in this._vertexBuffers) {
  39088. result.push(kind);
  39089. }
  39090. }
  39091. return result;
  39092. };
  39093. /**
  39094. * Update index buffer
  39095. * @param indices defines the indices to store in the index buffer
  39096. * @param offset defines the offset in the target buffer where to store the data
  39097. */
  39098. Geometry.prototype.updateIndices = function (indices, offset) {
  39099. if (!this._indexBuffer) {
  39100. return;
  39101. }
  39102. if (!this._indexBufferIsUpdatable) {
  39103. this.setIndices(indices, null, true);
  39104. }
  39105. else {
  39106. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39107. }
  39108. };
  39109. /**
  39110. * Creates a new index buffer
  39111. * @param indices defines the indices to store in the index buffer
  39112. * @param totalVertices defines the total number of vertices (could be null)
  39113. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39114. */
  39115. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39116. if (totalVertices === void 0) { totalVertices = null; }
  39117. if (updatable === void 0) { updatable = false; }
  39118. if (this._indexBuffer) {
  39119. this._engine._releaseBuffer(this._indexBuffer);
  39120. }
  39121. this._disposeVertexArrayObjects();
  39122. this._indices = indices;
  39123. this._indexBufferIsUpdatable = updatable;
  39124. if (this._meshes.length !== 0 && this._indices) {
  39125. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39126. }
  39127. if (totalVertices != undefined) { // including null and undefined
  39128. this._totalVertices = totalVertices;
  39129. }
  39130. var meshes = this._meshes;
  39131. var numOfMeshes = meshes.length;
  39132. for (var index = 0; index < numOfMeshes; index++) {
  39133. meshes[index]._createGlobalSubMesh(true);
  39134. }
  39135. this.notifyUpdate();
  39136. };
  39137. /**
  39138. * Return the total number of indices
  39139. * @returns the total number of indices
  39140. */
  39141. Geometry.prototype.getTotalIndices = function () {
  39142. if (!this.isReady()) {
  39143. return 0;
  39144. }
  39145. return this._indices.length;
  39146. };
  39147. /**
  39148. * Gets the index buffer array
  39149. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39150. * @returns the index buffer array
  39151. */
  39152. Geometry.prototype.getIndices = function (copyWhenShared) {
  39153. if (!this.isReady()) {
  39154. return null;
  39155. }
  39156. var orig = this._indices;
  39157. if (!copyWhenShared || this._meshes.length === 1) {
  39158. return orig;
  39159. }
  39160. else {
  39161. var len = orig.length;
  39162. var copy = [];
  39163. for (var i = 0; i < len; i++) {
  39164. copy.push(orig[i]);
  39165. }
  39166. return copy;
  39167. }
  39168. };
  39169. /**
  39170. * Gets the index buffer
  39171. * @return the index buffer
  39172. */
  39173. Geometry.prototype.getIndexBuffer = function () {
  39174. if (!this.isReady()) {
  39175. return null;
  39176. }
  39177. return this._indexBuffer;
  39178. };
  39179. /** @hidden */
  39180. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39181. if (effect === void 0) { effect = null; }
  39182. if (!effect || !this._vertexArrayObjects) {
  39183. return;
  39184. }
  39185. if (this._vertexArrayObjects[effect.key]) {
  39186. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39187. delete this._vertexArrayObjects[effect.key];
  39188. }
  39189. };
  39190. /**
  39191. * Release the associated resources for a specific mesh
  39192. * @param mesh defines the source mesh
  39193. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39194. */
  39195. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39196. var meshes = this._meshes;
  39197. var index = meshes.indexOf(mesh);
  39198. if (index === -1) {
  39199. return;
  39200. }
  39201. meshes.splice(index, 1);
  39202. mesh._geometry = null;
  39203. if (meshes.length === 0 && shouldDispose) {
  39204. this.dispose();
  39205. }
  39206. };
  39207. /**
  39208. * Apply current geometry to a given mesh
  39209. * @param mesh defines the mesh to apply geometry to
  39210. */
  39211. Geometry.prototype.applyToMesh = function (mesh) {
  39212. if (mesh._geometry === this) {
  39213. return;
  39214. }
  39215. var previousGeometry = mesh._geometry;
  39216. if (previousGeometry) {
  39217. previousGeometry.releaseForMesh(mesh);
  39218. }
  39219. var meshes = this._meshes;
  39220. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39221. mesh._geometry = this;
  39222. this._scene.pushGeometry(this);
  39223. meshes.push(mesh);
  39224. if (this.isReady()) {
  39225. this._applyToMesh(mesh);
  39226. }
  39227. else {
  39228. mesh._boundingInfo = this._boundingInfo;
  39229. }
  39230. };
  39231. Geometry.prototype._updateExtend = function (data) {
  39232. if (data === void 0) { data = null; }
  39233. if (!data) {
  39234. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39235. }
  39236. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39237. };
  39238. Geometry.prototype._applyToMesh = function (mesh) {
  39239. var numOfMeshes = this._meshes.length;
  39240. // vertexBuffers
  39241. for (var kind in this._vertexBuffers) {
  39242. if (numOfMeshes === 1) {
  39243. this._vertexBuffers[kind].create();
  39244. }
  39245. var buffer = this._vertexBuffers[kind].getBuffer();
  39246. if (buffer)
  39247. buffer.references = numOfMeshes;
  39248. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39249. if (!this._extend) {
  39250. this._updateExtend();
  39251. }
  39252. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39253. mesh._createGlobalSubMesh(false);
  39254. //bounding info was just created again, world matrix should be applied again.
  39255. mesh._updateBoundingInfo();
  39256. }
  39257. }
  39258. // indexBuffer
  39259. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39260. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39261. }
  39262. if (this._indexBuffer) {
  39263. this._indexBuffer.references = numOfMeshes;
  39264. }
  39265. };
  39266. Geometry.prototype.notifyUpdate = function (kind) {
  39267. if (this.onGeometryUpdated) {
  39268. this.onGeometryUpdated(this, kind);
  39269. }
  39270. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39271. var mesh = _a[_i];
  39272. mesh._markSubMeshesAsAttributesDirty();
  39273. }
  39274. };
  39275. /**
  39276. * Load the geometry if it was flagged as delay loaded
  39277. * @param scene defines the hosting scene
  39278. * @param onLoaded defines a callback called when the geometry is loaded
  39279. */
  39280. Geometry.prototype.load = function (scene, onLoaded) {
  39281. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39282. return;
  39283. }
  39284. if (this.isReady()) {
  39285. if (onLoaded) {
  39286. onLoaded();
  39287. }
  39288. return;
  39289. }
  39290. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39291. this._queueLoad(scene, onLoaded);
  39292. };
  39293. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39294. var _this = this;
  39295. if (!this.delayLoadingFile) {
  39296. return;
  39297. }
  39298. scene._addPendingData(this);
  39299. scene._loadFile(this.delayLoadingFile, function (data) {
  39300. if (!_this._delayLoadingFunction) {
  39301. return;
  39302. }
  39303. _this._delayLoadingFunction(JSON.parse(data), _this);
  39304. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39305. _this._delayInfo = [];
  39306. scene._removePendingData(_this);
  39307. var meshes = _this._meshes;
  39308. var numOfMeshes = meshes.length;
  39309. for (var index = 0; index < numOfMeshes; index++) {
  39310. _this._applyToMesh(meshes[index]);
  39311. }
  39312. if (onLoaded) {
  39313. onLoaded();
  39314. }
  39315. }, undefined, true);
  39316. };
  39317. /**
  39318. * Invert the geometry to move from a right handed system to a left handed one.
  39319. */
  39320. Geometry.prototype.toLeftHanded = function () {
  39321. // Flip faces
  39322. var tIndices = this.getIndices(false);
  39323. if (tIndices != null && tIndices.length > 0) {
  39324. for (var i = 0; i < tIndices.length; i += 3) {
  39325. var tTemp = tIndices[i + 0];
  39326. tIndices[i + 0] = tIndices[i + 2];
  39327. tIndices[i + 2] = tTemp;
  39328. }
  39329. this.setIndices(tIndices);
  39330. }
  39331. // Negate position.z
  39332. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39333. if (tPositions != null && tPositions.length > 0) {
  39334. for (var i = 0; i < tPositions.length; i += 3) {
  39335. tPositions[i + 2] = -tPositions[i + 2];
  39336. }
  39337. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39338. }
  39339. // Negate normal.z
  39340. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39341. if (tNormals != null && tNormals.length > 0) {
  39342. for (var i = 0; i < tNormals.length; i += 3) {
  39343. tNormals[i + 2] = -tNormals[i + 2];
  39344. }
  39345. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39346. }
  39347. };
  39348. // Cache
  39349. /** @hidden */
  39350. Geometry.prototype._resetPointsArrayCache = function () {
  39351. this._positions = null;
  39352. };
  39353. /** @hidden */
  39354. Geometry.prototype._generatePointsArray = function () {
  39355. if (this._positions)
  39356. return true;
  39357. this._positions = [];
  39358. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39359. if (!data) {
  39360. return false;
  39361. }
  39362. for (var index = 0; index < data.length; index += 3) {
  39363. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39364. }
  39365. return true;
  39366. };
  39367. /**
  39368. * Gets a value indicating if the geometry is disposed
  39369. * @returns true if the geometry was disposed
  39370. */
  39371. Geometry.prototype.isDisposed = function () {
  39372. return this._isDisposed;
  39373. };
  39374. Geometry.prototype._disposeVertexArrayObjects = function () {
  39375. if (this._vertexArrayObjects) {
  39376. for (var kind in this._vertexArrayObjects) {
  39377. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39378. }
  39379. this._vertexArrayObjects = {};
  39380. }
  39381. };
  39382. /**
  39383. * Free all associated resources
  39384. */
  39385. Geometry.prototype.dispose = function () {
  39386. var meshes = this._meshes;
  39387. var numOfMeshes = meshes.length;
  39388. var index;
  39389. for (index = 0; index < numOfMeshes; index++) {
  39390. this.releaseForMesh(meshes[index]);
  39391. }
  39392. this._meshes = [];
  39393. this._disposeVertexArrayObjects();
  39394. for (var kind in this._vertexBuffers) {
  39395. this._vertexBuffers[kind].dispose();
  39396. }
  39397. this._vertexBuffers = {};
  39398. this._totalVertices = 0;
  39399. if (this._indexBuffer) {
  39400. this._engine._releaseBuffer(this._indexBuffer);
  39401. }
  39402. this._indexBuffer = null;
  39403. this._indices = [];
  39404. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39405. this.delayLoadingFile = null;
  39406. this._delayLoadingFunction = null;
  39407. this._delayInfo = [];
  39408. this._boundingInfo = null;
  39409. this._scene.removeGeometry(this);
  39410. this._isDisposed = true;
  39411. };
  39412. /**
  39413. * Clone the current geometry into a new geometry
  39414. * @param id defines the unique ID of the new geometry
  39415. * @returns a new geometry object
  39416. */
  39417. Geometry.prototype.copy = function (id) {
  39418. var vertexData = new BABYLON.VertexData();
  39419. vertexData.indices = [];
  39420. var indices = this.getIndices();
  39421. if (indices) {
  39422. for (var index = 0; index < indices.length; index++) {
  39423. vertexData.indices.push(indices[index]);
  39424. }
  39425. }
  39426. var updatable = false;
  39427. var stopChecking = false;
  39428. var kind;
  39429. for (kind in this._vertexBuffers) {
  39430. // using slice() to make a copy of the array and not just reference it
  39431. var data = this.getVerticesData(kind);
  39432. if (data instanceof Float32Array) {
  39433. vertexData.set(new Float32Array(data), kind);
  39434. }
  39435. else {
  39436. vertexData.set(data.slice(0), kind);
  39437. }
  39438. if (!stopChecking) {
  39439. var vb = this.getVertexBuffer(kind);
  39440. if (vb) {
  39441. updatable = vb.isUpdatable();
  39442. stopChecking = !updatable;
  39443. }
  39444. }
  39445. }
  39446. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39447. geometry.delayLoadState = this.delayLoadState;
  39448. geometry.delayLoadingFile = this.delayLoadingFile;
  39449. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39450. for (kind in this._delayInfo) {
  39451. geometry._delayInfo = geometry._delayInfo || [];
  39452. geometry._delayInfo.push(kind);
  39453. }
  39454. // Bounding info
  39455. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39456. return geometry;
  39457. };
  39458. /**
  39459. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39460. * @return a JSON representation of the current geometry data (without the vertices data)
  39461. */
  39462. Geometry.prototype.serialize = function () {
  39463. var serializationObject = {};
  39464. serializationObject.id = this.id;
  39465. serializationObject.updatable = this._updatable;
  39466. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39467. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39468. }
  39469. return serializationObject;
  39470. };
  39471. Geometry.prototype.toNumberArray = function (origin) {
  39472. if (Array.isArray(origin)) {
  39473. return origin;
  39474. }
  39475. else {
  39476. return Array.prototype.slice.call(origin);
  39477. }
  39478. };
  39479. /**
  39480. * Serialize all vertices data into a JSON oject
  39481. * @returns a JSON representation of the current geometry data
  39482. */
  39483. Geometry.prototype.serializeVerticeData = function () {
  39484. var serializationObject = this.serialize();
  39485. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39486. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39487. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39488. serializationObject.positions._updatable = true;
  39489. }
  39490. }
  39491. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39492. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39493. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39494. serializationObject.normals._updatable = true;
  39495. }
  39496. }
  39497. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39498. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39499. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39500. serializationObject.tangets._updatable = true;
  39501. }
  39502. }
  39503. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39504. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39505. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39506. serializationObject.uvs._updatable = true;
  39507. }
  39508. }
  39509. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39510. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39511. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39512. serializationObject.uv2s._updatable = true;
  39513. }
  39514. }
  39515. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39516. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39517. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39518. serializationObject.uv3s._updatable = true;
  39519. }
  39520. }
  39521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39522. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39523. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39524. serializationObject.uv4s._updatable = true;
  39525. }
  39526. }
  39527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39528. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39529. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39530. serializationObject.uv5s._updatable = true;
  39531. }
  39532. }
  39533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39534. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39535. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39536. serializationObject.uv6s._updatable = true;
  39537. }
  39538. }
  39539. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39540. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39541. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39542. serializationObject.colors._updatable = true;
  39543. }
  39544. }
  39545. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39546. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39547. serializationObject.matricesIndices._isExpanded = true;
  39548. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39549. serializationObject.matricesIndices._updatable = true;
  39550. }
  39551. }
  39552. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39553. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39554. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39555. serializationObject.matricesWeights._updatable = true;
  39556. }
  39557. }
  39558. serializationObject.indices = this.toNumberArray(this.getIndices());
  39559. return serializationObject;
  39560. };
  39561. // Statics
  39562. /**
  39563. * Extracts a clone of a mesh geometry
  39564. * @param mesh defines the source mesh
  39565. * @param id defines the unique ID of the new geometry object
  39566. * @returns the new geometry object
  39567. */
  39568. Geometry.ExtractFromMesh = function (mesh, id) {
  39569. var geometry = mesh._geometry;
  39570. if (!geometry) {
  39571. return null;
  39572. }
  39573. return geometry.copy(id);
  39574. };
  39575. /**
  39576. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39577. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39578. * Be aware Math.random() could cause collisions, but:
  39579. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  39580. * @returns a string containing a new GUID
  39581. */
  39582. Geometry.RandomId = function () {
  39583. return BABYLON.Tools.RandomId();
  39584. };
  39585. /** @hidden */
  39586. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39587. var scene = mesh.getScene();
  39588. // Geometry
  39589. var geometryId = parsedGeometry.geometryId;
  39590. if (geometryId) {
  39591. var geometry = scene.getGeometryByID(geometryId);
  39592. if (geometry) {
  39593. geometry.applyToMesh(mesh);
  39594. }
  39595. }
  39596. else if (parsedGeometry instanceof ArrayBuffer) {
  39597. var binaryInfo = mesh._binaryInfo;
  39598. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39599. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39600. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39601. }
  39602. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39603. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39604. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39605. }
  39606. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39607. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39608. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39609. }
  39610. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39611. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39612. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39613. }
  39614. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39615. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39616. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39617. }
  39618. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39619. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39620. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39621. }
  39622. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39623. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39624. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39625. }
  39626. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39627. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39628. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39629. }
  39630. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39631. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39632. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39633. }
  39634. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39635. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39636. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39637. }
  39638. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39639. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39640. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39641. }
  39642. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39643. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39644. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39645. }
  39646. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39647. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39648. mesh.setIndices(indicesData, null);
  39649. }
  39650. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39651. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39652. mesh.subMeshes = [];
  39653. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39654. var materialIndex = subMeshesData[(i * 5) + 0];
  39655. var verticesStart = subMeshesData[(i * 5) + 1];
  39656. var verticesCount = subMeshesData[(i * 5) + 2];
  39657. var indexStart = subMeshesData[(i * 5) + 3];
  39658. var indexCount = subMeshesData[(i * 5) + 4];
  39659. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39660. }
  39661. }
  39662. }
  39663. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39664. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39665. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39666. if (parsedGeometry.tangents) {
  39667. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39668. }
  39669. if (parsedGeometry.uvs) {
  39670. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39671. }
  39672. if (parsedGeometry.uvs2) {
  39673. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39674. }
  39675. if (parsedGeometry.uvs3) {
  39676. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39677. }
  39678. if (parsedGeometry.uvs4) {
  39679. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39680. }
  39681. if (parsedGeometry.uvs5) {
  39682. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39683. }
  39684. if (parsedGeometry.uvs6) {
  39685. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39686. }
  39687. if (parsedGeometry.colors) {
  39688. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39689. }
  39690. if (parsedGeometry.matricesIndices) {
  39691. if (!parsedGeometry.matricesIndices._isExpanded) {
  39692. var floatIndices = [];
  39693. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39694. var matricesIndex = parsedGeometry.matricesIndices[i];
  39695. floatIndices.push(matricesIndex & 0x000000FF);
  39696. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39697. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39698. floatIndices.push(matricesIndex >> 24);
  39699. }
  39700. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39701. }
  39702. else {
  39703. delete parsedGeometry.matricesIndices._isExpanded;
  39704. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39705. }
  39706. }
  39707. if (parsedGeometry.matricesIndicesExtra) {
  39708. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39709. var floatIndices = [];
  39710. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39711. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39712. floatIndices.push(matricesIndex & 0x000000FF);
  39713. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39714. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39715. floatIndices.push(matricesIndex >> 24);
  39716. }
  39717. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39718. }
  39719. else {
  39720. delete parsedGeometry.matricesIndices._isExpanded;
  39721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39722. }
  39723. }
  39724. if (parsedGeometry.matricesWeights) {
  39725. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39726. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39727. }
  39728. if (parsedGeometry.matricesWeightsExtra) {
  39729. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39730. }
  39731. mesh.setIndices(parsedGeometry.indices, null);
  39732. }
  39733. // SubMeshes
  39734. if (parsedGeometry.subMeshes) {
  39735. mesh.subMeshes = [];
  39736. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39737. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39738. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39739. }
  39740. }
  39741. // Flat shading
  39742. if (mesh._shouldGenerateFlatShading) {
  39743. mesh.convertToFlatShadedMesh();
  39744. delete mesh._shouldGenerateFlatShading;
  39745. }
  39746. // Update
  39747. mesh.computeWorldMatrix(true);
  39748. // Octree
  39749. var sceneOctree = scene.selectionOctree;
  39750. if (sceneOctree !== undefined && sceneOctree !== null) {
  39751. sceneOctree.addMesh(mesh);
  39752. }
  39753. };
  39754. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39755. var epsilon = 1e-3;
  39756. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39757. return;
  39758. }
  39759. var noInfluenceBoneIndex = 0.0;
  39760. if (parsedGeometry.skeletonId > -1) {
  39761. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39762. if (!skeleton) {
  39763. return;
  39764. }
  39765. noInfluenceBoneIndex = skeleton.bones.length;
  39766. }
  39767. else {
  39768. return;
  39769. }
  39770. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39771. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39772. var matricesWeights = parsedGeometry.matricesWeights;
  39773. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39774. var influencers = parsedGeometry.numBoneInfluencer;
  39775. var size = matricesWeights.length;
  39776. for (var i = 0; i < size; i += 4) {
  39777. var weight = 0.0;
  39778. var firstZeroWeight = -1;
  39779. for (var j = 0; j < 4; j++) {
  39780. var w = matricesWeights[i + j];
  39781. weight += w;
  39782. if (w < epsilon && firstZeroWeight < 0) {
  39783. firstZeroWeight = j;
  39784. }
  39785. }
  39786. if (matricesWeightsExtra) {
  39787. for (var j = 0; j < 4; j++) {
  39788. var w = matricesWeightsExtra[i + j];
  39789. weight += w;
  39790. if (w < epsilon && firstZeroWeight < 0) {
  39791. firstZeroWeight = j + 4;
  39792. }
  39793. }
  39794. }
  39795. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39796. firstZeroWeight = influencers - 1;
  39797. }
  39798. if (weight > epsilon) {
  39799. var mweight = 1.0 / weight;
  39800. for (var j = 0; j < 4; j++) {
  39801. matricesWeights[i + j] *= mweight;
  39802. }
  39803. if (matricesWeightsExtra) {
  39804. for (var j = 0; j < 4; j++) {
  39805. matricesWeightsExtra[i + j] *= mweight;
  39806. }
  39807. }
  39808. }
  39809. else {
  39810. if (firstZeroWeight >= 4) {
  39811. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39812. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39813. }
  39814. else {
  39815. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39816. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39817. }
  39818. }
  39819. }
  39820. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39821. if (parsedGeometry.matricesWeightsExtra) {
  39822. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39823. }
  39824. };
  39825. /**
  39826. * Create a new geometry from persisted data (Using .babylon file format)
  39827. * @param parsedVertexData defines the persisted data
  39828. * @param scene defines the hosting scene
  39829. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39830. * @returns the new geometry object
  39831. */
  39832. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39833. if (scene.getGeometryByID(parsedVertexData.id)) {
  39834. return null; // null since geometry could be something else than a box...
  39835. }
  39836. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39837. if (BABYLON.Tags) {
  39838. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39839. }
  39840. if (parsedVertexData.delayLoadingFile) {
  39841. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39842. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39843. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39844. geometry._delayInfo = [];
  39845. if (parsedVertexData.hasUVs) {
  39846. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39847. }
  39848. if (parsedVertexData.hasUVs2) {
  39849. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39850. }
  39851. if (parsedVertexData.hasUVs3) {
  39852. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39853. }
  39854. if (parsedVertexData.hasUVs4) {
  39855. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39856. }
  39857. if (parsedVertexData.hasUVs5) {
  39858. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39859. }
  39860. if (parsedVertexData.hasUVs6) {
  39861. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39862. }
  39863. if (parsedVertexData.hasColors) {
  39864. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39865. }
  39866. if (parsedVertexData.hasMatricesIndices) {
  39867. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39868. }
  39869. if (parsedVertexData.hasMatricesWeights) {
  39870. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39871. }
  39872. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39873. }
  39874. else {
  39875. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39876. }
  39877. scene.pushGeometry(geometry, true);
  39878. return geometry;
  39879. };
  39880. return Geometry;
  39881. }());
  39882. BABYLON.Geometry = Geometry;
  39883. // Primitives
  39884. /// Abstract class
  39885. /**
  39886. * Abstract class used to provide common services for all typed geometries
  39887. * @hidden
  39888. */
  39889. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39890. __extends(_PrimitiveGeometry, _super);
  39891. /**
  39892. * Creates a new typed geometry
  39893. * @param id defines the unique ID of the geometry
  39894. * @param scene defines the hosting scene
  39895. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39896. * @param mesh defines the hosting mesh (can be null)
  39897. */
  39898. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39899. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39900. if (mesh === void 0) { mesh = null; }
  39901. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39902. _this._canBeRegenerated = _canBeRegenerated;
  39903. _this._beingRegenerated = true;
  39904. _this.regenerate();
  39905. _this._beingRegenerated = false;
  39906. return _this;
  39907. }
  39908. /**
  39909. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39910. * @returns true if the geometry can be regenerated
  39911. */
  39912. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39913. return this._canBeRegenerated;
  39914. };
  39915. /**
  39916. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39917. */
  39918. _PrimitiveGeometry.prototype.regenerate = function () {
  39919. if (!this._canBeRegenerated) {
  39920. return;
  39921. }
  39922. this._beingRegenerated = true;
  39923. this.setAllVerticesData(this._regenerateVertexData(), false);
  39924. this._beingRegenerated = false;
  39925. };
  39926. /**
  39927. * Clone the geometry
  39928. * @param id defines the unique ID of the new geometry
  39929. * @returns the new geometry
  39930. */
  39931. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39932. return _super.prototype.copy.call(this, id);
  39933. };
  39934. // overrides
  39935. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39936. if (!this._beingRegenerated) {
  39937. return;
  39938. }
  39939. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39940. };
  39941. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39942. if (!this._beingRegenerated) {
  39943. return;
  39944. }
  39945. _super.prototype.setVerticesData.call(this, kind, data, false);
  39946. };
  39947. // to override
  39948. /** @hidden */
  39949. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39950. throw new Error("Abstract method");
  39951. };
  39952. _PrimitiveGeometry.prototype.copy = function (id) {
  39953. throw new Error("Must be overriden in sub-classes.");
  39954. };
  39955. _PrimitiveGeometry.prototype.serialize = function () {
  39956. var serializationObject = _super.prototype.serialize.call(this);
  39957. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39958. return serializationObject;
  39959. };
  39960. return _PrimitiveGeometry;
  39961. }(Geometry));
  39962. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39963. /**
  39964. * Creates a ribbon geometry
  39965. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39966. */
  39967. var RibbonGeometry = /** @class */ (function (_super) {
  39968. __extends(RibbonGeometry, _super);
  39969. /**
  39970. * Creates a ribbon geometry
  39971. * @param id defines the unique ID of the geometry
  39972. * @param scene defines the hosting scene
  39973. * @param pathArray defines the array of paths to use
  39974. * @param closeArray defines if the last path and the first path must be joined
  39975. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39976. * @param offset defines the offset between points
  39977. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39978. * @param mesh defines the hosting mesh (can be null)
  39979. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39980. */
  39981. function RibbonGeometry(id, scene,
  39982. /**
  39983. * Defines the array of paths to use
  39984. */
  39985. pathArray,
  39986. /**
  39987. * Defines if the last and first points of each path in your pathArray must be joined
  39988. */
  39989. closeArray,
  39990. /**
  39991. * Defines if the last and first points of each path in your pathArray must be joined
  39992. */
  39993. closePath,
  39994. /**
  39995. * Defines the offset between points
  39996. */
  39997. offset, canBeRegenerated, mesh,
  39998. /**
  39999. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40000. */
  40001. side) {
  40002. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40003. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40004. _this.pathArray = pathArray;
  40005. _this.closeArray = closeArray;
  40006. _this.closePath = closePath;
  40007. _this.offset = offset;
  40008. _this.side = side;
  40009. return _this;
  40010. }
  40011. /** @hidden */
  40012. RibbonGeometry.prototype._regenerateVertexData = function () {
  40013. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40014. };
  40015. RibbonGeometry.prototype.copy = function (id) {
  40016. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40017. };
  40018. return RibbonGeometry;
  40019. }(_PrimitiveGeometry));
  40020. BABYLON.RibbonGeometry = RibbonGeometry;
  40021. /**
  40022. * Creates a box geometry
  40023. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40024. */
  40025. var BoxGeometry = /** @class */ (function (_super) {
  40026. __extends(BoxGeometry, _super);
  40027. /**
  40028. * Creates a box geometry
  40029. * @param id defines the unique ID of the geometry
  40030. * @param scene defines the hosting scene
  40031. * @param size defines the zise of the box (width, height and depth are the same)
  40032. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40033. * @param mesh defines the hosting mesh (can be null)
  40034. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40035. */
  40036. function BoxGeometry(id, scene,
  40037. /**
  40038. * Defines the zise of the box (width, height and depth are the same)
  40039. */
  40040. size, canBeRegenerated, mesh,
  40041. /**
  40042. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40043. */
  40044. side) {
  40045. if (mesh === void 0) { mesh = null; }
  40046. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40047. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40048. _this.size = size;
  40049. _this.side = side;
  40050. return _this;
  40051. }
  40052. BoxGeometry.prototype._regenerateVertexData = function () {
  40053. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40054. };
  40055. BoxGeometry.prototype.copy = function (id) {
  40056. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40057. };
  40058. BoxGeometry.prototype.serialize = function () {
  40059. var serializationObject = _super.prototype.serialize.call(this);
  40060. serializationObject.size = this.size;
  40061. return serializationObject;
  40062. };
  40063. BoxGeometry.Parse = function (parsedBox, scene) {
  40064. if (scene.getGeometryByID(parsedBox.id)) {
  40065. return null; // null since geometry could be something else than a box...
  40066. }
  40067. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40068. if (BABYLON.Tags) {
  40069. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40070. }
  40071. scene.pushGeometry(box, true);
  40072. return box;
  40073. };
  40074. return BoxGeometry;
  40075. }(_PrimitiveGeometry));
  40076. BABYLON.BoxGeometry = BoxGeometry;
  40077. /**
  40078. * Creates a sphere geometry
  40079. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40080. */
  40081. var SphereGeometry = /** @class */ (function (_super) {
  40082. __extends(SphereGeometry, _super);
  40083. /**
  40084. * Create a new sphere geometry
  40085. * @param id defines the unique ID of the geometry
  40086. * @param scene defines the hosting scene
  40087. * @param segments defines the number of segments to use to create the sphere
  40088. * @param diameter defines the diameter of the sphere
  40089. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40090. * @param mesh defines the hosting mesh (can be null)
  40091. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40092. */
  40093. function SphereGeometry(id, scene,
  40094. /**
  40095. * Defines the number of segments to use to create the sphere
  40096. */
  40097. segments,
  40098. /**
  40099. * Defines the diameter of the sphere
  40100. */
  40101. diameter, canBeRegenerated, mesh,
  40102. /**
  40103. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40104. */
  40105. side) {
  40106. if (mesh === void 0) { mesh = null; }
  40107. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40108. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40109. _this.segments = segments;
  40110. _this.diameter = diameter;
  40111. _this.side = side;
  40112. return _this;
  40113. }
  40114. SphereGeometry.prototype._regenerateVertexData = function () {
  40115. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40116. };
  40117. SphereGeometry.prototype.copy = function (id) {
  40118. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40119. };
  40120. SphereGeometry.prototype.serialize = function () {
  40121. var serializationObject = _super.prototype.serialize.call(this);
  40122. serializationObject.segments = this.segments;
  40123. serializationObject.diameter = this.diameter;
  40124. return serializationObject;
  40125. };
  40126. SphereGeometry.Parse = function (parsedSphere, scene) {
  40127. if (scene.getGeometryByID(parsedSphere.id)) {
  40128. return null; // null since geometry could be something else than a sphere...
  40129. }
  40130. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40131. if (BABYLON.Tags) {
  40132. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40133. }
  40134. scene.pushGeometry(sphere, true);
  40135. return sphere;
  40136. };
  40137. return SphereGeometry;
  40138. }(_PrimitiveGeometry));
  40139. BABYLON.SphereGeometry = SphereGeometry;
  40140. /**
  40141. * Creates a disc geometry
  40142. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40143. */
  40144. var DiscGeometry = /** @class */ (function (_super) {
  40145. __extends(DiscGeometry, _super);
  40146. /**
  40147. * Creates a new disc geometry
  40148. * @param id defines the unique ID of the geometry
  40149. * @param scene defines the hosting scene
  40150. * @param radius defines the radius of the disc
  40151. * @param tessellation defines the tesselation factor to apply to the disc
  40152. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40153. * @param mesh defines the hosting mesh (can be null)
  40154. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40155. */
  40156. function DiscGeometry(id, scene,
  40157. /**
  40158. * Defines the radius of the disc
  40159. */
  40160. radius,
  40161. /**
  40162. * Defines the tesselation factor to apply to the disc
  40163. */
  40164. tessellation, canBeRegenerated, mesh,
  40165. /**
  40166. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40167. */
  40168. side) {
  40169. if (mesh === void 0) { mesh = null; }
  40170. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40171. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40172. _this.radius = radius;
  40173. _this.tessellation = tessellation;
  40174. _this.side = side;
  40175. return _this;
  40176. }
  40177. DiscGeometry.prototype._regenerateVertexData = function () {
  40178. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40179. };
  40180. DiscGeometry.prototype.copy = function (id) {
  40181. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40182. };
  40183. return DiscGeometry;
  40184. }(_PrimitiveGeometry));
  40185. BABYLON.DiscGeometry = DiscGeometry;
  40186. /**
  40187. * Creates a new cylinder geometry
  40188. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40189. */
  40190. var CylinderGeometry = /** @class */ (function (_super) {
  40191. __extends(CylinderGeometry, _super);
  40192. /**
  40193. * Creates a new cylinder geometry
  40194. * @param id defines the unique ID of the geometry
  40195. * @param scene defines the hosting scene
  40196. * @param height defines the height of the cylinder
  40197. * @param diameterTop defines the diameter of the cylinder's top cap
  40198. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40199. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40200. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40201. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40202. * @param mesh defines the hosting mesh (can be null)
  40203. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40204. */
  40205. function CylinderGeometry(id, scene,
  40206. /**
  40207. * Defines the height of the cylinder
  40208. */
  40209. height,
  40210. /**
  40211. * Defines the diameter of the cylinder's top cap
  40212. */
  40213. diameterTop,
  40214. /**
  40215. * Defines the diameter of the cylinder's bottom cap
  40216. */
  40217. diameterBottom,
  40218. /**
  40219. * Defines the tessellation factor to apply to the cylinder
  40220. */
  40221. tessellation,
  40222. /**
  40223. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40224. */
  40225. subdivisions, canBeRegenerated, mesh,
  40226. /**
  40227. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40228. */
  40229. side) {
  40230. if (subdivisions === void 0) { subdivisions = 1; }
  40231. if (mesh === void 0) { mesh = null; }
  40232. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40233. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40234. _this.height = height;
  40235. _this.diameterTop = diameterTop;
  40236. _this.diameterBottom = diameterBottom;
  40237. _this.tessellation = tessellation;
  40238. _this.subdivisions = subdivisions;
  40239. _this.side = side;
  40240. return _this;
  40241. }
  40242. CylinderGeometry.prototype._regenerateVertexData = function () {
  40243. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40244. };
  40245. CylinderGeometry.prototype.copy = function (id) {
  40246. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40247. };
  40248. CylinderGeometry.prototype.serialize = function () {
  40249. var serializationObject = _super.prototype.serialize.call(this);
  40250. serializationObject.height = this.height;
  40251. serializationObject.diameterTop = this.diameterTop;
  40252. serializationObject.diameterBottom = this.diameterBottom;
  40253. serializationObject.tessellation = this.tessellation;
  40254. return serializationObject;
  40255. };
  40256. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40257. if (scene.getGeometryByID(parsedCylinder.id)) {
  40258. return null; // null since geometry could be something else than a cylinder...
  40259. }
  40260. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40261. if (BABYLON.Tags) {
  40262. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40263. }
  40264. scene.pushGeometry(cylinder, true);
  40265. return cylinder;
  40266. };
  40267. return CylinderGeometry;
  40268. }(_PrimitiveGeometry));
  40269. BABYLON.CylinderGeometry = CylinderGeometry;
  40270. /**
  40271. * Creates a new torus geometry
  40272. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40273. */
  40274. var TorusGeometry = /** @class */ (function (_super) {
  40275. __extends(TorusGeometry, _super);
  40276. /**
  40277. * Creates a new torus geometry
  40278. * @param id defines the unique ID of the geometry
  40279. * @param scene defines the hosting scene
  40280. * @param diameter defines the diameter of the torus
  40281. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40282. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40283. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40284. * @param mesh defines the hosting mesh (can be null)
  40285. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40286. */
  40287. function TorusGeometry(id, scene,
  40288. /**
  40289. * Defines the diameter of the torus
  40290. */
  40291. diameter,
  40292. /**
  40293. * Defines the thickness of the torus (ie. internal diameter)
  40294. */
  40295. thickness,
  40296. /**
  40297. * Defines the tesselation factor to apply to the torus
  40298. */
  40299. tessellation, canBeRegenerated, mesh,
  40300. /**
  40301. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40302. */
  40303. side) {
  40304. if (mesh === void 0) { mesh = null; }
  40305. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40306. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40307. _this.diameter = diameter;
  40308. _this.thickness = thickness;
  40309. _this.tessellation = tessellation;
  40310. _this.side = side;
  40311. return _this;
  40312. }
  40313. TorusGeometry.prototype._regenerateVertexData = function () {
  40314. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40315. };
  40316. TorusGeometry.prototype.copy = function (id) {
  40317. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40318. };
  40319. TorusGeometry.prototype.serialize = function () {
  40320. var serializationObject = _super.prototype.serialize.call(this);
  40321. serializationObject.diameter = this.diameter;
  40322. serializationObject.thickness = this.thickness;
  40323. serializationObject.tessellation = this.tessellation;
  40324. return serializationObject;
  40325. };
  40326. TorusGeometry.Parse = function (parsedTorus, scene) {
  40327. if (scene.getGeometryByID(parsedTorus.id)) {
  40328. return null; // null since geometry could be something else than a torus...
  40329. }
  40330. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40331. if (BABYLON.Tags) {
  40332. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40333. }
  40334. scene.pushGeometry(torus, true);
  40335. return torus;
  40336. };
  40337. return TorusGeometry;
  40338. }(_PrimitiveGeometry));
  40339. BABYLON.TorusGeometry = TorusGeometry;
  40340. /**
  40341. * Creates a new ground geometry
  40342. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40343. */
  40344. var GroundGeometry = /** @class */ (function (_super) {
  40345. __extends(GroundGeometry, _super);
  40346. /**
  40347. * Creates a new ground geometry
  40348. * @param id defines the unique ID of the geometry
  40349. * @param scene defines the hosting scene
  40350. * @param width defines the width of the ground
  40351. * @param height defines the height of the ground
  40352. * @param subdivisions defines the subdivisions to apply to the ground
  40353. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40354. * @param mesh defines the hosting mesh (can be null)
  40355. */
  40356. function GroundGeometry(id, scene,
  40357. /**
  40358. * Defines the width of the ground
  40359. */
  40360. width,
  40361. /**
  40362. * Defines the height of the ground
  40363. */
  40364. height,
  40365. /**
  40366. * Defines the subdivisions to apply to the ground
  40367. */
  40368. subdivisions, canBeRegenerated, mesh) {
  40369. if (mesh === void 0) { mesh = null; }
  40370. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40371. _this.width = width;
  40372. _this.height = height;
  40373. _this.subdivisions = subdivisions;
  40374. return _this;
  40375. }
  40376. GroundGeometry.prototype._regenerateVertexData = function () {
  40377. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40378. };
  40379. GroundGeometry.prototype.copy = function (id) {
  40380. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40381. };
  40382. GroundGeometry.prototype.serialize = function () {
  40383. var serializationObject = _super.prototype.serialize.call(this);
  40384. serializationObject.width = this.width;
  40385. serializationObject.height = this.height;
  40386. serializationObject.subdivisions = this.subdivisions;
  40387. return serializationObject;
  40388. };
  40389. GroundGeometry.Parse = function (parsedGround, scene) {
  40390. if (scene.getGeometryByID(parsedGround.id)) {
  40391. return null; // null since geometry could be something else than a ground...
  40392. }
  40393. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40394. if (BABYLON.Tags) {
  40395. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40396. }
  40397. scene.pushGeometry(ground, true);
  40398. return ground;
  40399. };
  40400. return GroundGeometry;
  40401. }(_PrimitiveGeometry));
  40402. BABYLON.GroundGeometry = GroundGeometry;
  40403. /**
  40404. * Creates a tiled ground geometry
  40405. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40406. */
  40407. var TiledGroundGeometry = /** @class */ (function (_super) {
  40408. __extends(TiledGroundGeometry, _super);
  40409. /**
  40410. * Creates a tiled ground geometry
  40411. * @param id defines the unique ID of the geometry
  40412. * @param scene defines the hosting scene
  40413. * @param xmin defines the minimum value on X axis
  40414. * @param zmin defines the minimum value on Z axis
  40415. * @param xmax defines the maximum value on X axis
  40416. * @param zmax defines the maximum value on Z axis
  40417. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40418. * @param precision defines the precision to use when computing the tiles
  40419. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40420. * @param mesh defines the hosting mesh (can be null)
  40421. */
  40422. function TiledGroundGeometry(id, scene,
  40423. /**
  40424. * Defines the minimum value on X axis
  40425. */
  40426. xmin,
  40427. /**
  40428. * Defines the minimum value on Z axis
  40429. */
  40430. zmin,
  40431. /**
  40432. * Defines the maximum value on X axis
  40433. */
  40434. xmax,
  40435. /**
  40436. * Defines the maximum value on Z axis
  40437. */
  40438. zmax,
  40439. /**
  40440. * Defines the subdivisions to apply to the ground
  40441. */
  40442. subdivisions,
  40443. /**
  40444. * Defines the precision to use when computing the tiles
  40445. */
  40446. precision, canBeRegenerated, mesh) {
  40447. if (mesh === void 0) { mesh = null; }
  40448. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40449. _this.xmin = xmin;
  40450. _this.zmin = zmin;
  40451. _this.xmax = xmax;
  40452. _this.zmax = zmax;
  40453. _this.subdivisions = subdivisions;
  40454. _this.precision = precision;
  40455. return _this;
  40456. }
  40457. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40458. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40459. };
  40460. TiledGroundGeometry.prototype.copy = function (id) {
  40461. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40462. };
  40463. return TiledGroundGeometry;
  40464. }(_PrimitiveGeometry));
  40465. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40466. /**
  40467. * Creates a plane geometry
  40468. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40469. */
  40470. var PlaneGeometry = /** @class */ (function (_super) {
  40471. __extends(PlaneGeometry, _super);
  40472. /**
  40473. * Creates a plane geometry
  40474. * @param id defines the unique ID of the geometry
  40475. * @param scene defines the hosting scene
  40476. * @param size defines the size of the plane (width === height)
  40477. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40478. * @param mesh defines the hosting mesh (can be null)
  40479. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40480. */
  40481. function PlaneGeometry(id, scene,
  40482. /**
  40483. * Defines the size of the plane (width === height)
  40484. */
  40485. size, canBeRegenerated, mesh,
  40486. /**
  40487. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40488. */
  40489. side) {
  40490. if (mesh === void 0) { mesh = null; }
  40491. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40492. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40493. _this.size = size;
  40494. _this.side = side;
  40495. return _this;
  40496. }
  40497. PlaneGeometry.prototype._regenerateVertexData = function () {
  40498. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40499. };
  40500. PlaneGeometry.prototype.copy = function (id) {
  40501. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40502. };
  40503. PlaneGeometry.prototype.serialize = function () {
  40504. var serializationObject = _super.prototype.serialize.call(this);
  40505. serializationObject.size = this.size;
  40506. return serializationObject;
  40507. };
  40508. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40509. if (scene.getGeometryByID(parsedPlane.id)) {
  40510. return null; // null since geometry could be something else than a ground...
  40511. }
  40512. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40513. if (BABYLON.Tags) {
  40514. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40515. }
  40516. scene.pushGeometry(plane, true);
  40517. return plane;
  40518. };
  40519. return PlaneGeometry;
  40520. }(_PrimitiveGeometry));
  40521. BABYLON.PlaneGeometry = PlaneGeometry;
  40522. /**
  40523. * Creates a torus knot geometry
  40524. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40525. */
  40526. var TorusKnotGeometry = /** @class */ (function (_super) {
  40527. __extends(TorusKnotGeometry, _super);
  40528. /**
  40529. * Creates a torus knot geometry
  40530. * @param id defines the unique ID of the geometry
  40531. * @param scene defines the hosting scene
  40532. * @param radius defines the radius of the torus knot
  40533. * @param tube defines the thickness of the torus knot tube
  40534. * @param radialSegments defines the number of radial segments
  40535. * @param tubularSegments defines the number of tubular segments
  40536. * @param p defines the first number of windings
  40537. * @param q defines the second number of windings
  40538. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40539. * @param mesh defines the hosting mesh (can be null)
  40540. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40541. */
  40542. function TorusKnotGeometry(id, scene,
  40543. /**
  40544. * Defines the radius of the torus knot
  40545. */
  40546. radius,
  40547. /**
  40548. * Defines the thickness of the torus knot tube
  40549. */
  40550. tube,
  40551. /**
  40552. * Defines the number of radial segments
  40553. */
  40554. radialSegments,
  40555. /**
  40556. * Defines the number of tubular segments
  40557. */
  40558. tubularSegments,
  40559. /**
  40560. * Defines the first number of windings
  40561. */
  40562. p,
  40563. /**
  40564. * Defines the second number of windings
  40565. */
  40566. q, canBeRegenerated, mesh,
  40567. /**
  40568. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40569. */
  40570. side) {
  40571. if (mesh === void 0) { mesh = null; }
  40572. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40573. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40574. _this.radius = radius;
  40575. _this.tube = tube;
  40576. _this.radialSegments = radialSegments;
  40577. _this.tubularSegments = tubularSegments;
  40578. _this.p = p;
  40579. _this.q = q;
  40580. _this.side = side;
  40581. return _this;
  40582. }
  40583. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40584. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  40585. };
  40586. TorusKnotGeometry.prototype.copy = function (id) {
  40587. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40588. };
  40589. TorusKnotGeometry.prototype.serialize = function () {
  40590. var serializationObject = _super.prototype.serialize.call(this);
  40591. serializationObject.radius = this.radius;
  40592. serializationObject.tube = this.tube;
  40593. serializationObject.radialSegments = this.radialSegments;
  40594. serializationObject.tubularSegments = this.tubularSegments;
  40595. serializationObject.p = this.p;
  40596. serializationObject.q = this.q;
  40597. return serializationObject;
  40598. };
  40599. ;
  40600. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40601. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40602. return null; // null since geometry could be something else than a ground...
  40603. }
  40604. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40605. if (BABYLON.Tags) {
  40606. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40607. }
  40608. scene.pushGeometry(torusKnot, true);
  40609. return torusKnot;
  40610. };
  40611. return TorusKnotGeometry;
  40612. }(_PrimitiveGeometry));
  40613. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40614. //}
  40615. })(BABYLON || (BABYLON = {}));
  40616. //# sourceMappingURL=babylon.geometry.js.map
  40617. var BABYLON;
  40618. (function (BABYLON) {
  40619. /**
  40620. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40621. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40622. */
  40623. var PostProcessManager = /** @class */ (function () {
  40624. /**
  40625. * Creates a new instance PostProcess
  40626. * @param scene The scene that the post process is associated with.
  40627. */
  40628. function PostProcessManager(scene) {
  40629. this._vertexBuffers = {};
  40630. this._scene = scene;
  40631. }
  40632. PostProcessManager.prototype._prepareBuffers = function () {
  40633. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40634. return;
  40635. }
  40636. // VBO
  40637. var vertices = [];
  40638. vertices.push(1, 1);
  40639. vertices.push(-1, 1);
  40640. vertices.push(-1, -1);
  40641. vertices.push(1, -1);
  40642. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40643. this._buildIndexBuffer();
  40644. };
  40645. PostProcessManager.prototype._buildIndexBuffer = function () {
  40646. // Indices
  40647. var indices = [];
  40648. indices.push(0);
  40649. indices.push(1);
  40650. indices.push(2);
  40651. indices.push(0);
  40652. indices.push(2);
  40653. indices.push(3);
  40654. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40655. };
  40656. /**
  40657. * Rebuilds the vertex buffers of the manager.
  40658. */
  40659. PostProcessManager.prototype._rebuild = function () {
  40660. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40661. if (!vb) {
  40662. return;
  40663. }
  40664. vb._rebuild();
  40665. this._buildIndexBuffer();
  40666. };
  40667. // Methods
  40668. /**
  40669. * Prepares a frame to be run through a post process.
  40670. * @param sourceTexture The input texture to the post procesess. (default: null)
  40671. * @param postProcesses An array of post processes to be run. (default: null)
  40672. * @returns True if the post processes were able to be run.
  40673. */
  40674. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40675. if (sourceTexture === void 0) { sourceTexture = null; }
  40676. if (postProcesses === void 0) { postProcesses = null; }
  40677. var camera = this._scene.activeCamera;
  40678. if (!camera) {
  40679. return false;
  40680. }
  40681. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40682. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40683. return false;
  40684. }
  40685. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40686. return true;
  40687. };
  40688. /**
  40689. * Manually render a set of post processes to a texture.
  40690. * @param postProcesses An array of post processes to be run.
  40691. * @param targetTexture The target texture to render to.
  40692. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40693. */
  40694. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40695. if (targetTexture === void 0) { targetTexture = null; }
  40696. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40697. var engine = this._scene.getEngine();
  40698. for (var index = 0; index < postProcesses.length; index++) {
  40699. if (index < postProcesses.length - 1) {
  40700. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40701. }
  40702. else {
  40703. if (targetTexture) {
  40704. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40705. }
  40706. else {
  40707. engine.restoreDefaultFramebuffer();
  40708. }
  40709. }
  40710. var pp = postProcesses[index];
  40711. var effect = pp.apply();
  40712. if (effect) {
  40713. pp.onBeforeRenderObservable.notifyObservers(effect);
  40714. // VBOs
  40715. this._prepareBuffers();
  40716. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40717. // Draw order
  40718. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40719. pp.onAfterRenderObservable.notifyObservers(effect);
  40720. }
  40721. }
  40722. // Restore depth buffer
  40723. engine.setDepthBuffer(true);
  40724. engine.setDepthWrite(true);
  40725. };
  40726. /**
  40727. * Finalize the result of the output of the postprocesses.
  40728. * @param doNotPresent If true the result will not be displayed to the screen.
  40729. * @param targetTexture The target texture to render to.
  40730. * @param faceIndex The index of the face to bind the target texture to.
  40731. * @param postProcesses The array of post processes to render.
  40732. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40733. */
  40734. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40735. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40736. var camera = this._scene.activeCamera;
  40737. if (!camera) {
  40738. return;
  40739. }
  40740. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40741. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40742. return;
  40743. }
  40744. var engine = this._scene.getEngine();
  40745. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40746. var pp = postProcesses[index];
  40747. if (index < len - 1) {
  40748. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40749. }
  40750. else {
  40751. if (targetTexture) {
  40752. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40753. pp._outputTexture = targetTexture;
  40754. }
  40755. else {
  40756. engine.restoreDefaultFramebuffer();
  40757. pp._outputTexture = null;
  40758. }
  40759. }
  40760. if (doNotPresent) {
  40761. break;
  40762. }
  40763. var effect = pp.apply();
  40764. if (effect) {
  40765. pp.onBeforeRenderObservable.notifyObservers(effect);
  40766. // VBOs
  40767. this._prepareBuffers();
  40768. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40769. // Draw order
  40770. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40771. pp.onAfterRenderObservable.notifyObservers(effect);
  40772. }
  40773. }
  40774. // Restore states
  40775. engine.setDepthBuffer(true);
  40776. engine.setDepthWrite(true);
  40777. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40778. };
  40779. /**
  40780. * Disposes of the post process manager.
  40781. */
  40782. PostProcessManager.prototype.dispose = function () {
  40783. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40784. if (buffer) {
  40785. buffer.dispose();
  40786. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40787. }
  40788. if (this._indexBuffer) {
  40789. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40790. this._indexBuffer = null;
  40791. }
  40792. };
  40793. return PostProcessManager;
  40794. }());
  40795. BABYLON.PostProcessManager = PostProcessManager;
  40796. })(BABYLON || (BABYLON = {}));
  40797. //# sourceMappingURL=babylon.postProcessManager.js.map
  40798. var BABYLON;
  40799. (function (BABYLON) {
  40800. /**
  40801. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40802. */
  40803. var PerformanceMonitor = /** @class */ (function () {
  40804. /**
  40805. * constructor
  40806. * @param frameSampleSize The number of samples required to saturate the sliding window
  40807. */
  40808. function PerformanceMonitor(frameSampleSize) {
  40809. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40810. this._enabled = true;
  40811. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40812. }
  40813. /**
  40814. * Samples current frame
  40815. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40816. */
  40817. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40818. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40819. if (!this._enabled)
  40820. return;
  40821. if (this._lastFrameTimeMs != null) {
  40822. var dt = timeMs - this._lastFrameTimeMs;
  40823. this._rollingFrameTime.add(dt);
  40824. }
  40825. this._lastFrameTimeMs = timeMs;
  40826. };
  40827. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40828. /**
  40829. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40830. * @return Average frame time in milliseconds
  40831. */
  40832. get: function () {
  40833. return this._rollingFrameTime.average;
  40834. },
  40835. enumerable: true,
  40836. configurable: true
  40837. });
  40838. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40839. /**
  40840. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40841. * @return Frame time variance in milliseconds squared
  40842. */
  40843. get: function () {
  40844. return this._rollingFrameTime.variance;
  40845. },
  40846. enumerable: true,
  40847. configurable: true
  40848. });
  40849. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40850. /**
  40851. * Returns the frame time of the most recent frame
  40852. * @return Frame time in milliseconds
  40853. */
  40854. get: function () {
  40855. return this._rollingFrameTime.history(0);
  40856. },
  40857. enumerable: true,
  40858. configurable: true
  40859. });
  40860. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40861. /**
  40862. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40863. * @return Framerate in frames per second
  40864. */
  40865. get: function () {
  40866. return 1000.0 / this._rollingFrameTime.average;
  40867. },
  40868. enumerable: true,
  40869. configurable: true
  40870. });
  40871. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40872. /**
  40873. * Returns the average framerate in frames per second using the most recent frame time
  40874. * @return Framerate in frames per second
  40875. */
  40876. get: function () {
  40877. var history = this._rollingFrameTime.history(0);
  40878. if (history === 0) {
  40879. return 0;
  40880. }
  40881. return 1000.0 / history;
  40882. },
  40883. enumerable: true,
  40884. configurable: true
  40885. });
  40886. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40887. /**
  40888. * Returns true if enough samples have been taken to completely fill the sliding window
  40889. * @return true if saturated
  40890. */
  40891. get: function () {
  40892. return this._rollingFrameTime.isSaturated();
  40893. },
  40894. enumerable: true,
  40895. configurable: true
  40896. });
  40897. /**
  40898. * Enables contributions to the sliding window sample set
  40899. */
  40900. PerformanceMonitor.prototype.enable = function () {
  40901. this._enabled = true;
  40902. };
  40903. /**
  40904. * Disables contributions to the sliding window sample set
  40905. * Samples will not be interpolated over the disabled period
  40906. */
  40907. PerformanceMonitor.prototype.disable = function () {
  40908. this._enabled = false;
  40909. //clear last sample to avoid interpolating over the disabled period when next enabled
  40910. this._lastFrameTimeMs = null;
  40911. };
  40912. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40913. /**
  40914. * Returns true if sampling is enabled
  40915. * @return true if enabled
  40916. */
  40917. get: function () {
  40918. return this._enabled;
  40919. },
  40920. enumerable: true,
  40921. configurable: true
  40922. });
  40923. /**
  40924. * Resets performance monitor
  40925. */
  40926. PerformanceMonitor.prototype.reset = function () {
  40927. //clear last sample to avoid interpolating over the disabled period when next enabled
  40928. this._lastFrameTimeMs = null;
  40929. //wipe record
  40930. this._rollingFrameTime.reset();
  40931. };
  40932. return PerformanceMonitor;
  40933. }());
  40934. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40935. /**
  40936. * RollingAverage
  40937. *
  40938. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40939. */
  40940. var RollingAverage = /** @class */ (function () {
  40941. /**
  40942. * constructor
  40943. * @param length The number of samples required to saturate the sliding window
  40944. */
  40945. function RollingAverage(length) {
  40946. this._samples = new Array(length);
  40947. this.reset();
  40948. }
  40949. /**
  40950. * Adds a sample to the sample set
  40951. * @param v The sample value
  40952. */
  40953. RollingAverage.prototype.add = function (v) {
  40954. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40955. var delta;
  40956. //we need to check if we've already wrapped round
  40957. if (this.isSaturated()) {
  40958. //remove bottom of stack from mean
  40959. var bottomValue = this._samples[this._pos];
  40960. delta = bottomValue - this.average;
  40961. this.average -= delta / (this._sampleCount - 1);
  40962. this._m2 -= delta * (bottomValue - this.average);
  40963. }
  40964. else {
  40965. this._sampleCount++;
  40966. }
  40967. //add new value to mean
  40968. delta = v - this.average;
  40969. this.average += delta / (this._sampleCount);
  40970. this._m2 += delta * (v - this.average);
  40971. //set the new variance
  40972. this.variance = this._m2 / (this._sampleCount - 1);
  40973. this._samples[this._pos] = v;
  40974. this._pos++;
  40975. this._pos %= this._samples.length; //positive wrap around
  40976. };
  40977. /**
  40978. * Returns previously added values or null if outside of history or outside the sliding window domain
  40979. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40980. * @return Value previously recorded with add() or null if outside of range
  40981. */
  40982. RollingAverage.prototype.history = function (i) {
  40983. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40984. return 0;
  40985. }
  40986. var i0 = this._wrapPosition(this._pos - 1.0);
  40987. return this._samples[this._wrapPosition(i0 - i)];
  40988. };
  40989. /**
  40990. * Returns true if enough samples have been taken to completely fill the sliding window
  40991. * @return true if sample-set saturated
  40992. */
  40993. RollingAverage.prototype.isSaturated = function () {
  40994. return this._sampleCount >= this._samples.length;
  40995. };
  40996. /**
  40997. * Resets the rolling average (equivalent to 0 samples taken so far)
  40998. */
  40999. RollingAverage.prototype.reset = function () {
  41000. this.average = 0;
  41001. this.variance = 0;
  41002. this._sampleCount = 0;
  41003. this._pos = 0;
  41004. this._m2 = 0;
  41005. };
  41006. /**
  41007. * Wraps a value around the sample range boundaries
  41008. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41009. * @return Wrapped position in sample range
  41010. */
  41011. RollingAverage.prototype._wrapPosition = function (i) {
  41012. var max = this._samples.length;
  41013. return ((i % max) + max) % max;
  41014. };
  41015. return RollingAverage;
  41016. }());
  41017. BABYLON.RollingAverage = RollingAverage;
  41018. })(BABYLON || (BABYLON = {}));
  41019. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41020. var BABYLON;
  41021. (function (BABYLON) {
  41022. /**
  41023. * This groups together the common properties used for image processing either in direct forward pass
  41024. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41025. * or not.
  41026. */
  41027. var ImageProcessingConfiguration = /** @class */ (function () {
  41028. function ImageProcessingConfiguration() {
  41029. /**
  41030. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41031. */
  41032. this.colorCurves = new BABYLON.ColorCurves();
  41033. this._colorCurvesEnabled = false;
  41034. this._colorGradingEnabled = false;
  41035. this._colorGradingWithGreenDepth = true;
  41036. this._colorGradingBGR = true;
  41037. this._exposure = 1.0;
  41038. this._toneMappingEnabled = false;
  41039. this._contrast = 1.0;
  41040. /**
  41041. * Vignette stretch size.
  41042. */
  41043. this.vignetteStretch = 0;
  41044. /**
  41045. * Vignette centre X Offset.
  41046. */
  41047. this.vignetteCentreX = 0;
  41048. /**
  41049. * Vignette centre Y Offset.
  41050. */
  41051. this.vignetteCentreY = 0;
  41052. /**
  41053. * Vignette weight or intensity of the vignette effect.
  41054. */
  41055. this.vignetteWeight = 1.5;
  41056. /**
  41057. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41058. * if vignetteEnabled is set to true.
  41059. */
  41060. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41061. /**
  41062. * Camera field of view used by the Vignette effect.
  41063. */
  41064. this.vignetteCameraFov = 0.5;
  41065. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41066. this._vignetteEnabled = false;
  41067. this._applyByPostProcess = false;
  41068. this._isEnabled = true;
  41069. /**
  41070. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41071. */
  41072. this.onUpdateParameters = new BABYLON.Observable();
  41073. }
  41074. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41075. /**
  41076. * Gets wether the color curves effect is enabled.
  41077. */
  41078. get: function () {
  41079. return this._colorCurvesEnabled;
  41080. },
  41081. /**
  41082. * Sets wether the color curves effect is enabled.
  41083. */
  41084. set: function (value) {
  41085. if (this._colorCurvesEnabled === value) {
  41086. return;
  41087. }
  41088. this._colorCurvesEnabled = value;
  41089. this._updateParameters();
  41090. },
  41091. enumerable: true,
  41092. configurable: true
  41093. });
  41094. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41095. /**
  41096. * Gets wether the color grading effect is enabled.
  41097. */
  41098. get: function () {
  41099. return this._colorGradingEnabled;
  41100. },
  41101. /**
  41102. * Sets wether the color grading effect is enabled.
  41103. */
  41104. set: function (value) {
  41105. if (this._colorGradingEnabled === value) {
  41106. return;
  41107. }
  41108. this._colorGradingEnabled = value;
  41109. this._updateParameters();
  41110. },
  41111. enumerable: true,
  41112. configurable: true
  41113. });
  41114. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41115. /**
  41116. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41117. */
  41118. get: function () {
  41119. return this._colorGradingWithGreenDepth;
  41120. },
  41121. /**
  41122. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41123. */
  41124. set: function (value) {
  41125. if (this._colorGradingWithGreenDepth === value) {
  41126. return;
  41127. }
  41128. this._colorGradingWithGreenDepth = value;
  41129. this._updateParameters();
  41130. },
  41131. enumerable: true,
  41132. configurable: true
  41133. });
  41134. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41135. /**
  41136. * Gets wether the color grading texture contains BGR values.
  41137. */
  41138. get: function () {
  41139. return this._colorGradingBGR;
  41140. },
  41141. /**
  41142. * Sets wether the color grading texture contains BGR values.
  41143. */
  41144. set: function (value) {
  41145. if (this._colorGradingBGR === value) {
  41146. return;
  41147. }
  41148. this._colorGradingBGR = value;
  41149. this._updateParameters();
  41150. },
  41151. enumerable: true,
  41152. configurable: true
  41153. });
  41154. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41155. /**
  41156. * Gets the Exposure used in the effect.
  41157. */
  41158. get: function () {
  41159. return this._exposure;
  41160. },
  41161. /**
  41162. * Sets the Exposure used in the effect.
  41163. */
  41164. set: function (value) {
  41165. if (this._exposure === value) {
  41166. return;
  41167. }
  41168. this._exposure = value;
  41169. this._updateParameters();
  41170. },
  41171. enumerable: true,
  41172. configurable: true
  41173. });
  41174. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41175. /**
  41176. * Gets wether the tone mapping effect is enabled.
  41177. */
  41178. get: function () {
  41179. return this._toneMappingEnabled;
  41180. },
  41181. /**
  41182. * Sets wether the tone mapping effect is enabled.
  41183. */
  41184. set: function (value) {
  41185. if (this._toneMappingEnabled === value) {
  41186. return;
  41187. }
  41188. this._toneMappingEnabled = value;
  41189. this._updateParameters();
  41190. },
  41191. enumerable: true,
  41192. configurable: true
  41193. });
  41194. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41195. /**
  41196. * Gets the contrast used in the effect.
  41197. */
  41198. get: function () {
  41199. return this._contrast;
  41200. },
  41201. /**
  41202. * Sets the contrast used in the effect.
  41203. */
  41204. set: function (value) {
  41205. if (this._contrast === value) {
  41206. return;
  41207. }
  41208. this._contrast = value;
  41209. this._updateParameters();
  41210. },
  41211. enumerable: true,
  41212. configurable: true
  41213. });
  41214. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41215. /**
  41216. * Gets the vignette blend mode allowing different kind of effect.
  41217. */
  41218. get: function () {
  41219. return this._vignetteBlendMode;
  41220. },
  41221. /**
  41222. * Sets the vignette blend mode allowing different kind of effect.
  41223. */
  41224. set: function (value) {
  41225. if (this._vignetteBlendMode === value) {
  41226. return;
  41227. }
  41228. this._vignetteBlendMode = value;
  41229. this._updateParameters();
  41230. },
  41231. enumerable: true,
  41232. configurable: true
  41233. });
  41234. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41235. /**
  41236. * Gets wether the vignette effect is enabled.
  41237. */
  41238. get: function () {
  41239. return this._vignetteEnabled;
  41240. },
  41241. /**
  41242. * Sets wether the vignette effect is enabled.
  41243. */
  41244. set: function (value) {
  41245. if (this._vignetteEnabled === value) {
  41246. return;
  41247. }
  41248. this._vignetteEnabled = value;
  41249. this._updateParameters();
  41250. },
  41251. enumerable: true,
  41252. configurable: true
  41253. });
  41254. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41255. /**
  41256. * Gets wether the image processing is applied through a post process or not.
  41257. */
  41258. get: function () {
  41259. return this._applyByPostProcess;
  41260. },
  41261. /**
  41262. * Sets wether the image processing is applied through a post process or not.
  41263. */
  41264. set: function (value) {
  41265. if (this._applyByPostProcess === value) {
  41266. return;
  41267. }
  41268. this._applyByPostProcess = value;
  41269. this._updateParameters();
  41270. },
  41271. enumerable: true,
  41272. configurable: true
  41273. });
  41274. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41275. /**
  41276. * Gets wether the image processing is enabled or not.
  41277. */
  41278. get: function () {
  41279. return this._isEnabled;
  41280. },
  41281. /**
  41282. * Sets wether the image processing is enabled or not.
  41283. */
  41284. set: function (value) {
  41285. if (this._isEnabled === value) {
  41286. return;
  41287. }
  41288. this._isEnabled = value;
  41289. this._updateParameters();
  41290. },
  41291. enumerable: true,
  41292. configurable: true
  41293. });
  41294. /**
  41295. * Method called each time the image processing information changes requires to recompile the effect.
  41296. */
  41297. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41298. this.onUpdateParameters.notifyObservers(this);
  41299. };
  41300. ImageProcessingConfiguration.prototype.getClassName = function () {
  41301. return "ImageProcessingConfiguration";
  41302. };
  41303. /**
  41304. * Prepare the list of uniforms associated with the Image Processing effects.
  41305. * @param uniformsList The list of uniforms used in the effect
  41306. * @param defines the list of defines currently in use
  41307. */
  41308. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41309. if (defines.EXPOSURE) {
  41310. uniforms.push("exposureLinear");
  41311. }
  41312. if (defines.CONTRAST) {
  41313. uniforms.push("contrast");
  41314. }
  41315. if (defines.COLORGRADING) {
  41316. uniforms.push("colorTransformSettings");
  41317. }
  41318. if (defines.VIGNETTE) {
  41319. uniforms.push("vInverseScreenSize");
  41320. uniforms.push("vignetteSettings1");
  41321. uniforms.push("vignetteSettings2");
  41322. }
  41323. if (defines.COLORCURVES) {
  41324. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41325. }
  41326. };
  41327. /**
  41328. * Prepare the list of samplers associated with the Image Processing effects.
  41329. * @param uniformsList The list of uniforms used in the effect
  41330. * @param defines the list of defines currently in use
  41331. */
  41332. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41333. if (defines.COLORGRADING) {
  41334. samplersList.push("txColorTransform");
  41335. }
  41336. };
  41337. /**
  41338. * Prepare the list of defines associated to the shader.
  41339. * @param defines the list of defines to complete
  41340. */
  41341. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41342. if (forPostProcess === void 0) { forPostProcess = false; }
  41343. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41344. defines.VIGNETTE = false;
  41345. defines.TONEMAPPING = false;
  41346. defines.CONTRAST = false;
  41347. defines.EXPOSURE = false;
  41348. defines.COLORCURVES = false;
  41349. defines.COLORGRADING = false;
  41350. defines.COLORGRADING3D = false;
  41351. defines.IMAGEPROCESSING = false;
  41352. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41353. return;
  41354. }
  41355. defines.VIGNETTE = this.vignetteEnabled;
  41356. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41357. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41358. defines.TONEMAPPING = this.toneMappingEnabled;
  41359. defines.CONTRAST = (this.contrast !== 1.0);
  41360. defines.EXPOSURE = (this.exposure !== 1.0);
  41361. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41362. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41363. if (defines.COLORGRADING) {
  41364. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41365. }
  41366. else {
  41367. defines.COLORGRADING3D = false;
  41368. }
  41369. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41370. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41371. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41372. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41373. };
  41374. /**
  41375. * Returns true if all the image processing information are ready.
  41376. */
  41377. ImageProcessingConfiguration.prototype.isReady = function () {
  41378. // Color Grading texure can not be none blocking.
  41379. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41380. };
  41381. /**
  41382. * Binds the image processing to the shader.
  41383. * @param effect The effect to bind to
  41384. */
  41385. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41386. if (aspectRatio === void 0) { aspectRatio = 1; }
  41387. // Color Curves
  41388. if (this._colorCurvesEnabled && this.colorCurves) {
  41389. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41390. }
  41391. // Vignette
  41392. if (this._vignetteEnabled) {
  41393. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41394. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41395. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41396. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41397. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41398. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41399. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41400. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41401. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41402. var vignettePower = -2.0 * this.vignetteWeight;
  41403. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41404. }
  41405. // Exposure
  41406. effect.setFloat("exposureLinear", this.exposure);
  41407. // Contrast
  41408. effect.setFloat("contrast", this.contrast);
  41409. // Color transform settings
  41410. if (this.colorGradingTexture) {
  41411. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41412. var textureSize = this.colorGradingTexture.getSize().height;
  41413. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41414. 0.5 / textureSize, // textureOffset
  41415. textureSize, // textureSize
  41416. this.colorGradingTexture.level // weight
  41417. );
  41418. }
  41419. };
  41420. /**
  41421. * Clones the current image processing instance.
  41422. * @return The cloned image processing
  41423. */
  41424. ImageProcessingConfiguration.prototype.clone = function () {
  41425. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41426. };
  41427. /**
  41428. * Serializes the current image processing instance to a json representation.
  41429. * @return a JSON representation
  41430. */
  41431. ImageProcessingConfiguration.prototype.serialize = function () {
  41432. return BABYLON.SerializationHelper.Serialize(this);
  41433. };
  41434. /**
  41435. * Parses the image processing from a json representation.
  41436. * @param source the JSON source to parse
  41437. * @return The parsed image processing
  41438. */
  41439. ImageProcessingConfiguration.Parse = function (source) {
  41440. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41441. };
  41442. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41443. /**
  41444. * Used to apply the vignette as a mix with the pixel color.
  41445. */
  41446. get: function () {
  41447. return this._VIGNETTEMODE_MULTIPLY;
  41448. },
  41449. enumerable: true,
  41450. configurable: true
  41451. });
  41452. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41453. /**
  41454. * Used to apply the vignette as a replacement of the pixel color.
  41455. */
  41456. get: function () {
  41457. return this._VIGNETTEMODE_OPAQUE;
  41458. },
  41459. enumerable: true,
  41460. configurable: true
  41461. });
  41462. // Static constants associated to the image processing.
  41463. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41464. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41465. __decorate([
  41466. BABYLON.serializeAsColorCurves()
  41467. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41468. __decorate([
  41469. BABYLON.serialize()
  41470. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41471. __decorate([
  41472. BABYLON.serializeAsTexture()
  41473. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41474. __decorate([
  41475. BABYLON.serialize()
  41476. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41477. __decorate([
  41478. BABYLON.serialize()
  41479. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41480. __decorate([
  41481. BABYLON.serialize()
  41482. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41483. __decorate([
  41484. BABYLON.serialize()
  41485. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41486. __decorate([
  41487. BABYLON.serialize()
  41488. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41489. __decorate([
  41490. BABYLON.serialize()
  41491. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41492. __decorate([
  41493. BABYLON.serialize()
  41494. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41495. __decorate([
  41496. BABYLON.serialize()
  41497. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41498. __decorate([
  41499. BABYLON.serialize()
  41500. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41501. __decorate([
  41502. BABYLON.serialize()
  41503. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41504. __decorate([
  41505. BABYLON.serializeAsColor4()
  41506. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41507. __decorate([
  41508. BABYLON.serialize()
  41509. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41510. __decorate([
  41511. BABYLON.serialize()
  41512. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41513. __decorate([
  41514. BABYLON.serialize()
  41515. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41516. __decorate([
  41517. BABYLON.serialize()
  41518. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41519. __decorate([
  41520. BABYLON.serialize()
  41521. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41522. return ImageProcessingConfiguration;
  41523. }());
  41524. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41525. })(BABYLON || (BABYLON = {}));
  41526. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41527. var BABYLON;
  41528. (function (BABYLON) {
  41529. /**
  41530. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41531. * It can help converting any input color in a desired output one. This can then be used to create effects
  41532. * from sepia, black and white to sixties or futuristic rendering...
  41533. *
  41534. * The only supported format is currently 3dl.
  41535. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41536. */
  41537. var ColorGradingTexture = /** @class */ (function (_super) {
  41538. __extends(ColorGradingTexture, _super);
  41539. /**
  41540. * Instantiates a ColorGradingTexture from the following parameters.
  41541. *
  41542. * @param url The location of the color gradind data (currently only supporting 3dl)
  41543. * @param scene The scene the texture will be used in
  41544. */
  41545. function ColorGradingTexture(url, scene) {
  41546. var _this = _super.call(this, scene) || this;
  41547. if (!url) {
  41548. return _this;
  41549. }
  41550. _this._engine = scene.getEngine();
  41551. _this._textureMatrix = BABYLON.Matrix.Identity();
  41552. _this.name = url;
  41553. _this.url = url;
  41554. _this.hasAlpha = false;
  41555. _this.isCube = false;
  41556. _this.is3D = _this._engine.webGLVersion > 1;
  41557. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41558. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41559. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41560. _this.anisotropicFilteringLevel = 1;
  41561. _this._texture = _this._getFromCache(url, true);
  41562. if (!_this._texture) {
  41563. if (!scene.useDelayedTextureLoading) {
  41564. _this.loadTexture();
  41565. }
  41566. else {
  41567. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41568. }
  41569. }
  41570. return _this;
  41571. }
  41572. /**
  41573. * Returns the texture matrix used in most of the material.
  41574. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41575. */
  41576. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41577. return this._textureMatrix;
  41578. };
  41579. /**
  41580. * Occurs when the file being loaded is a .3dl LUT file.
  41581. */
  41582. ColorGradingTexture.prototype.load3dlTexture = function () {
  41583. var engine = this._engine;
  41584. var texture;
  41585. if (engine.webGLVersion === 1) {
  41586. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41587. }
  41588. else {
  41589. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41590. }
  41591. this._texture = texture;
  41592. var callback = function (text) {
  41593. if (typeof text !== "string") {
  41594. return;
  41595. }
  41596. var data = null;
  41597. var tempData = null;
  41598. var line;
  41599. var lines = text.split('\n');
  41600. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41601. var maxColor = 0;
  41602. for (var i = 0; i < lines.length; i++) {
  41603. line = lines[i];
  41604. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41605. continue;
  41606. if (line.indexOf('#') === 0)
  41607. continue;
  41608. var words = line.split(" ");
  41609. if (size === 0) {
  41610. // Number of space + one
  41611. size = words.length;
  41612. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41613. tempData = new Float32Array(size * size * size * 4);
  41614. continue;
  41615. }
  41616. if (size != 0) {
  41617. var r = Math.max(parseInt(words[0]), 0);
  41618. var g = Math.max(parseInt(words[1]), 0);
  41619. var b = Math.max(parseInt(words[2]), 0);
  41620. maxColor = Math.max(r, maxColor);
  41621. maxColor = Math.max(g, maxColor);
  41622. maxColor = Math.max(b, maxColor);
  41623. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41624. if (tempData) {
  41625. tempData[pixelStorageIndex + 0] = r;
  41626. tempData[pixelStorageIndex + 1] = g;
  41627. tempData[pixelStorageIndex + 2] = b;
  41628. }
  41629. pixelIndexSlice++;
  41630. if (pixelIndexSlice % size == 0) {
  41631. pixelIndexH++;
  41632. pixelIndexSlice = 0;
  41633. if (pixelIndexH % size == 0) {
  41634. pixelIndexW++;
  41635. pixelIndexH = 0;
  41636. }
  41637. }
  41638. }
  41639. }
  41640. if (tempData && data) {
  41641. for (var i = 0; i < tempData.length; i++) {
  41642. if (i > 0 && (i + 1) % 4 === 0) {
  41643. data[i] = 255;
  41644. }
  41645. else {
  41646. var value = tempData[i];
  41647. data[i] = (value / maxColor * 255);
  41648. }
  41649. }
  41650. }
  41651. if (texture.is3D) {
  41652. texture.updateSize(size, size, size);
  41653. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41654. }
  41655. else {
  41656. texture.updateSize(size * size, size);
  41657. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41658. }
  41659. };
  41660. var scene = this.getScene();
  41661. if (scene) {
  41662. scene._loadFile(this.url, callback);
  41663. }
  41664. else {
  41665. this._engine._loadFile(this.url, callback);
  41666. }
  41667. return this._texture;
  41668. };
  41669. /**
  41670. * Starts the loading process of the texture.
  41671. */
  41672. ColorGradingTexture.prototype.loadTexture = function () {
  41673. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41674. this.load3dlTexture();
  41675. }
  41676. };
  41677. /**
  41678. * Clones the color gradind texture.
  41679. */
  41680. ColorGradingTexture.prototype.clone = function () {
  41681. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41682. // Base texture
  41683. newTexture.level = this.level;
  41684. return newTexture;
  41685. };
  41686. /**
  41687. * Called during delayed load for textures.
  41688. */
  41689. ColorGradingTexture.prototype.delayLoad = function () {
  41690. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41691. return;
  41692. }
  41693. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41694. this._texture = this._getFromCache(this.url, true);
  41695. if (!this._texture) {
  41696. this.loadTexture();
  41697. }
  41698. };
  41699. /**
  41700. * Parses a color grading texture serialized by Babylon.
  41701. * @param parsedTexture The texture information being parsedTexture
  41702. * @param scene The scene to load the texture in
  41703. * @param rootUrl The root url of the data assets to load
  41704. * @return A color gradind texture
  41705. */
  41706. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41707. var texture = null;
  41708. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41709. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41710. texture.name = parsedTexture.name;
  41711. texture.level = parsedTexture.level;
  41712. }
  41713. return texture;
  41714. };
  41715. /**
  41716. * Serializes the LUT texture to json format.
  41717. */
  41718. ColorGradingTexture.prototype.serialize = function () {
  41719. if (!this.name) {
  41720. return null;
  41721. }
  41722. var serializationObject = {};
  41723. serializationObject.name = this.name;
  41724. serializationObject.level = this.level;
  41725. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41726. return serializationObject;
  41727. };
  41728. /**
  41729. * Empty line regex stored for GC.
  41730. */
  41731. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41732. return ColorGradingTexture;
  41733. }(BABYLON.BaseTexture));
  41734. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41735. })(BABYLON || (BABYLON = {}));
  41736. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41737. var BABYLON;
  41738. (function (BABYLON) {
  41739. /**
  41740. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41741. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41742. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  41743. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41744. */
  41745. var ColorCurves = /** @class */ (function () {
  41746. function ColorCurves() {
  41747. this._dirty = true;
  41748. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41749. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41750. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41751. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41752. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41753. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41754. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41755. this._globalHue = 30;
  41756. this._globalDensity = 0;
  41757. this._globalSaturation = 0;
  41758. this._globalExposure = 0;
  41759. this._highlightsHue = 30;
  41760. this._highlightsDensity = 0;
  41761. this._highlightsSaturation = 0;
  41762. this._highlightsExposure = 0;
  41763. this._midtonesHue = 30;
  41764. this._midtonesDensity = 0;
  41765. this._midtonesSaturation = 0;
  41766. this._midtonesExposure = 0;
  41767. this._shadowsHue = 30;
  41768. this._shadowsDensity = 0;
  41769. this._shadowsSaturation = 0;
  41770. this._shadowsExposure = 0;
  41771. }
  41772. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41773. /**
  41774. * Gets the global Hue value.
  41775. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41776. */
  41777. get: function () {
  41778. return this._globalHue;
  41779. },
  41780. /**
  41781. * Sets the global Hue value.
  41782. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41783. */
  41784. set: function (value) {
  41785. this._globalHue = value;
  41786. this._dirty = true;
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41792. /**
  41793. * Gets the global Density value.
  41794. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41795. * Values less than zero provide a filter of opposite hue.
  41796. */
  41797. get: function () {
  41798. return this._globalDensity;
  41799. },
  41800. /**
  41801. * Sets the global Density value.
  41802. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41803. * Values less than zero provide a filter of opposite hue.
  41804. */
  41805. set: function (value) {
  41806. this._globalDensity = value;
  41807. this._dirty = true;
  41808. },
  41809. enumerable: true,
  41810. configurable: true
  41811. });
  41812. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41813. /**
  41814. * Gets the global Saturation value.
  41815. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  41816. */
  41817. get: function () {
  41818. return this._globalSaturation;
  41819. },
  41820. /**
  41821. * Sets the global Saturation value.
  41822. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  41823. */
  41824. set: function (value) {
  41825. this._globalSaturation = value;
  41826. this._dirty = true;
  41827. },
  41828. enumerable: true,
  41829. configurable: true
  41830. });
  41831. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41832. /**
  41833. * Gets the highlights Hue value.
  41834. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41835. */
  41836. get: function () {
  41837. return this._highlightsHue;
  41838. },
  41839. /**
  41840. * Sets the highlights Hue value.
  41841. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41842. */
  41843. set: function (value) {
  41844. this._highlightsHue = value;
  41845. this._dirty = true;
  41846. },
  41847. enumerable: true,
  41848. configurable: true
  41849. });
  41850. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41851. /**
  41852. * Gets the highlights Density value.
  41853. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41854. * Values less than zero provide a filter of opposite hue.
  41855. */
  41856. get: function () {
  41857. return this._highlightsDensity;
  41858. },
  41859. /**
  41860. * Sets the highlights Density value.
  41861. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41862. * Values less than zero provide a filter of opposite hue.
  41863. */
  41864. set: function (value) {
  41865. this._highlightsDensity = value;
  41866. this._dirty = true;
  41867. },
  41868. enumerable: true,
  41869. configurable: true
  41870. });
  41871. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41872. /**
  41873. * Gets the highlights Saturation value.
  41874. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  41875. */
  41876. get: function () {
  41877. return this._highlightsSaturation;
  41878. },
  41879. /**
  41880. * Sets the highlights Saturation value.
  41881. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  41882. */
  41883. set: function (value) {
  41884. this._highlightsSaturation = value;
  41885. this._dirty = true;
  41886. },
  41887. enumerable: true,
  41888. configurable: true
  41889. });
  41890. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41891. /**
  41892. * Gets the highlights Exposure value.
  41893. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  41894. */
  41895. get: function () {
  41896. return this._highlightsExposure;
  41897. },
  41898. /**
  41899. * Sets the highlights Exposure value.
  41900. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  41901. */
  41902. set: function (value) {
  41903. this._highlightsExposure = value;
  41904. this._dirty = true;
  41905. },
  41906. enumerable: true,
  41907. configurable: true
  41908. });
  41909. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41910. /**
  41911. * Gets the midtones Hue value.
  41912. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41913. */
  41914. get: function () {
  41915. return this._midtonesHue;
  41916. },
  41917. /**
  41918. * Sets the midtones Hue value.
  41919. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41920. */
  41921. set: function (value) {
  41922. this._midtonesHue = value;
  41923. this._dirty = true;
  41924. },
  41925. enumerable: true,
  41926. configurable: true
  41927. });
  41928. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41929. /**
  41930. * Gets the midtones Density value.
  41931. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41932. * Values less than zero provide a filter of opposite hue.
  41933. */
  41934. get: function () {
  41935. return this._midtonesDensity;
  41936. },
  41937. /**
  41938. * Sets the midtones Density value.
  41939. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41940. * Values less than zero provide a filter of opposite hue.
  41941. */
  41942. set: function (value) {
  41943. this._midtonesDensity = value;
  41944. this._dirty = true;
  41945. },
  41946. enumerable: true,
  41947. configurable: true
  41948. });
  41949. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41950. /**
  41951. * Gets the midtones Saturation value.
  41952. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  41953. */
  41954. get: function () {
  41955. return this._midtonesSaturation;
  41956. },
  41957. /**
  41958. * Sets the midtones Saturation value.
  41959. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  41960. */
  41961. set: function (value) {
  41962. this._midtonesSaturation = value;
  41963. this._dirty = true;
  41964. },
  41965. enumerable: true,
  41966. configurable: true
  41967. });
  41968. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41969. /**
  41970. * Gets the midtones Exposure value.
  41971. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  41972. */
  41973. get: function () {
  41974. return this._midtonesExposure;
  41975. },
  41976. /**
  41977. * Sets the midtones Exposure value.
  41978. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  41979. */
  41980. set: function (value) {
  41981. this._midtonesExposure = value;
  41982. this._dirty = true;
  41983. },
  41984. enumerable: true,
  41985. configurable: true
  41986. });
  41987. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41988. /**
  41989. * Gets the shadows Hue value.
  41990. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41991. */
  41992. get: function () {
  41993. return this._shadowsHue;
  41994. },
  41995. /**
  41996. * Sets the shadows Hue value.
  41997. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41998. */
  41999. set: function (value) {
  42000. this._shadowsHue = value;
  42001. this._dirty = true;
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42007. /**
  42008. * Gets the shadows Density value.
  42009. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  42010. * Values less than zero provide a filter of opposite hue.
  42011. */
  42012. get: function () {
  42013. return this._shadowsDensity;
  42014. },
  42015. /**
  42016. * Sets the shadows Density value.
  42017. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  42018. * Values less than zero provide a filter of opposite hue.
  42019. */
  42020. set: function (value) {
  42021. this._shadowsDensity = value;
  42022. this._dirty = true;
  42023. },
  42024. enumerable: true,
  42025. configurable: true
  42026. });
  42027. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42028. /**
  42029. * Gets the shadows Saturation value.
  42030. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  42031. */
  42032. get: function () {
  42033. return this._shadowsSaturation;
  42034. },
  42035. /**
  42036. * Sets the shadows Saturation value.
  42037. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  42038. */
  42039. set: function (value) {
  42040. this._shadowsSaturation = value;
  42041. this._dirty = true;
  42042. },
  42043. enumerable: true,
  42044. configurable: true
  42045. });
  42046. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42047. /**
  42048. * Gets the shadows Exposure value.
  42049. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  42050. */
  42051. get: function () {
  42052. return this._shadowsExposure;
  42053. },
  42054. /**
  42055. * Sets the shadows Exposure value.
  42056. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  42057. */
  42058. set: function (value) {
  42059. this._shadowsExposure = value;
  42060. this._dirty = true;
  42061. },
  42062. enumerable: true,
  42063. configurable: true
  42064. });
  42065. ColorCurves.prototype.getClassName = function () {
  42066. return "ColorCurves";
  42067. };
  42068. /**
  42069. * Binds the color curves to the shader.
  42070. * @param colorCurves The color curve to bind
  42071. * @param effect The effect to bind to
  42072. */
  42073. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42074. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42075. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42076. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42077. if (colorCurves._dirty) {
  42078. colorCurves._dirty = false;
  42079. // Fill in global info.
  42080. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42081. // Compute highlights info.
  42082. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42083. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42084. // Compute midtones info.
  42085. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42086. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42087. // Compute shadows info.
  42088. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42089. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42090. // Compute deltas (neutral is midtones).
  42091. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42092. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42093. }
  42094. if (effect) {
  42095. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42096. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42097. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42098. }
  42099. };
  42100. /**
  42101. * Prepare the list of uniforms associated with the ColorCurves effects.
  42102. * @param uniformsList The list of uniforms used in the effect
  42103. */
  42104. ColorCurves.PrepareUniforms = function (uniformsList) {
  42105. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42106. };
  42107. /**
  42108. * Returns color grading data based on a hue, density, saturation and exposure value.
  42109. * @param filterHue The hue of the color filter.
  42110. * @param filterDensity The density of the color filter.
  42111. * @param saturation The saturation.
  42112. * @param exposure The exposure.
  42113. * @param result The result data container.
  42114. */
  42115. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42116. if (hue == null) {
  42117. return;
  42118. }
  42119. hue = ColorCurves.clamp(hue, 0, 360);
  42120. density = ColorCurves.clamp(density, -100, 100);
  42121. saturation = ColorCurves.clamp(saturation, -100, 100);
  42122. exposure = ColorCurves.clamp(exposure, -100, 100);
  42123. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42124. // so that the maximum filter density is only 50% control. This provides fine control
  42125. // for small values and reasonable range.
  42126. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42127. density *= 0.5;
  42128. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42129. if (density < 0) {
  42130. density *= -1;
  42131. hue = (hue + 180) % 360;
  42132. }
  42133. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42134. result.scaleToRef(2, result);
  42135. result.a = 1 + 0.01 * saturation;
  42136. };
  42137. /**
  42138. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42139. * @param value The input slider value in range [-100,100].
  42140. * @returns Adjusted value.
  42141. */
  42142. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42143. value /= 100;
  42144. var x = Math.abs(value);
  42145. x = Math.pow(x, 2);
  42146. if (value < 0) {
  42147. x *= -1;
  42148. }
  42149. x *= 100;
  42150. return x;
  42151. };
  42152. /**
  42153. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42154. * @param hue The hue (H) input.
  42155. * @param saturation The saturation (S) input.
  42156. * @param brightness The brightness (B) input.
  42157. * @result An RGBA color represented as Vector4.
  42158. */
  42159. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42160. var h = ColorCurves.clamp(hue, 0, 360);
  42161. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42162. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42163. if (s === 0) {
  42164. result.r = v;
  42165. result.g = v;
  42166. result.b = v;
  42167. }
  42168. else {
  42169. // sector 0 to 5
  42170. h /= 60;
  42171. var i = Math.floor(h);
  42172. // fractional part of h
  42173. var f = h - i;
  42174. var p = v * (1 - s);
  42175. var q = v * (1 - s * f);
  42176. var t = v * (1 - s * (1 - f));
  42177. switch (i) {
  42178. case 0:
  42179. result.r = v;
  42180. result.g = t;
  42181. result.b = p;
  42182. break;
  42183. case 1:
  42184. result.r = q;
  42185. result.g = v;
  42186. result.b = p;
  42187. break;
  42188. case 2:
  42189. result.r = p;
  42190. result.g = v;
  42191. result.b = t;
  42192. break;
  42193. case 3:
  42194. result.r = p;
  42195. result.g = q;
  42196. result.b = v;
  42197. break;
  42198. case 4:
  42199. result.r = t;
  42200. result.g = p;
  42201. result.b = v;
  42202. break;
  42203. default: // case 5:
  42204. result.r = v;
  42205. result.g = p;
  42206. result.b = q;
  42207. break;
  42208. }
  42209. }
  42210. result.a = 1;
  42211. };
  42212. /**
  42213. * Returns a value clamped between min and max
  42214. * @param value The value to clamp
  42215. * @param min The minimum of value
  42216. * @param max The maximum of value
  42217. * @returns The clamped value.
  42218. */
  42219. ColorCurves.clamp = function (value, min, max) {
  42220. return Math.min(Math.max(value, min), max);
  42221. };
  42222. /**
  42223. * Clones the current color curve instance.
  42224. * @return The cloned curves
  42225. */
  42226. ColorCurves.prototype.clone = function () {
  42227. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42228. };
  42229. /**
  42230. * Serializes the current color curve instance to a json representation.
  42231. * @return a JSON representation
  42232. */
  42233. ColorCurves.prototype.serialize = function () {
  42234. return BABYLON.SerializationHelper.Serialize(this);
  42235. };
  42236. /**
  42237. * Parses the color curve from a json representation.
  42238. * @param source the JSON source to parse
  42239. * @return The parsed curves
  42240. */
  42241. ColorCurves.Parse = function (source) {
  42242. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42243. };
  42244. __decorate([
  42245. BABYLON.serialize()
  42246. ], ColorCurves.prototype, "_globalHue", void 0);
  42247. __decorate([
  42248. BABYLON.serialize()
  42249. ], ColorCurves.prototype, "_globalDensity", void 0);
  42250. __decorate([
  42251. BABYLON.serialize()
  42252. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42253. __decorate([
  42254. BABYLON.serialize()
  42255. ], ColorCurves.prototype, "_globalExposure", void 0);
  42256. __decorate([
  42257. BABYLON.serialize()
  42258. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42259. __decorate([
  42260. BABYLON.serialize()
  42261. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42262. __decorate([
  42263. BABYLON.serialize()
  42264. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42265. __decorate([
  42266. BABYLON.serialize()
  42267. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42268. __decorate([
  42269. BABYLON.serialize()
  42270. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42271. __decorate([
  42272. BABYLON.serialize()
  42273. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42274. __decorate([
  42275. BABYLON.serialize()
  42276. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42277. __decorate([
  42278. BABYLON.serialize()
  42279. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42280. return ColorCurves;
  42281. }());
  42282. BABYLON.ColorCurves = ColorCurves;
  42283. })(BABYLON || (BABYLON = {}));
  42284. //# sourceMappingURL=babylon.colorCurves.js.map
  42285. //# sourceMappingURL=babylon.behavior.js.map
  42286. var BABYLON;
  42287. (function (BABYLON) {
  42288. /**
  42289. * "Static Class" containing the most commonly used helper while dealing with material for
  42290. * rendering purpose.
  42291. *
  42292. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42293. *
  42294. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42295. */
  42296. var MaterialHelper = /** @class */ (function () {
  42297. function MaterialHelper() {
  42298. }
  42299. /**
  42300. * Bind the current view position to an effect.
  42301. * @param effect The effect to be bound
  42302. * @param scene The scene the eyes position is used from
  42303. */
  42304. MaterialHelper.BindEyePosition = function (effect, scene) {
  42305. if (scene._forcedViewPosition) {
  42306. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42307. return;
  42308. }
  42309. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42310. };
  42311. /**
  42312. * Helps preparing the defines values about the UVs in used in the effect.
  42313. * UVs are shared as much as we can accross chanels in the shaders.
  42314. * @param texture The texture we are preparing the UVs for
  42315. * @param defines The defines to update
  42316. * @param key The chanel key "diffuse", "specular"... used in the shader
  42317. */
  42318. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42319. defines._needUVs = true;
  42320. defines[key] = true;
  42321. if (texture.getTextureMatrix().isIdentity(true)) {
  42322. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42323. if (texture.coordinatesIndex === 0) {
  42324. defines["MAINUV1"] = true;
  42325. }
  42326. else {
  42327. defines["MAINUV2"] = true;
  42328. }
  42329. }
  42330. else {
  42331. defines[key + "DIRECTUV"] = 0;
  42332. }
  42333. };
  42334. /**
  42335. * Binds a texture matrix value to its corrsponding uniform
  42336. * @param texture The texture to bind the matrix for
  42337. * @param uniformBuffer The uniform buffer receivin the data
  42338. * @param key The chanel key "diffuse", "specular"... used in the shader
  42339. */
  42340. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42341. var matrix = texture.getTextureMatrix();
  42342. if (!matrix.isIdentity(true)) {
  42343. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42344. }
  42345. };
  42346. /**
  42347. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42348. * @param mesh defines the current mesh
  42349. * @param scene defines the current scene
  42350. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42351. * @param pointsCloud defines if point cloud rendering has to be turned on
  42352. * @param fogEnabled defines if fog has to be turned on
  42353. * @param alphaTest defines if alpha testing has to be turned on
  42354. * @param defines defines the current list of defines
  42355. */
  42356. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42357. if (defines._areMiscDirty) {
  42358. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42359. defines["POINTSIZE"] = pointsCloud;
  42360. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42361. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42362. defines["ALPHATEST"] = alphaTest;
  42363. }
  42364. };
  42365. /**
  42366. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42367. * @param scene defines the current scene
  42368. * @param engine defines the current engine
  42369. * @param defines specifies the list of active defines
  42370. * @param useInstances defines if instances have to be turned on
  42371. * @param useClipPlane defines if clip plane have to be turned on
  42372. */
  42373. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42374. if (useClipPlane === void 0) { useClipPlane = null; }
  42375. var changed = false;
  42376. if (useClipPlane == null) {
  42377. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42378. }
  42379. if (defines["CLIPPLANE"] !== useClipPlane) {
  42380. defines["CLIPPLANE"] = useClipPlane;
  42381. changed = true;
  42382. }
  42383. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42384. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42385. changed = true;
  42386. }
  42387. if (defines["INSTANCES"] !== useInstances) {
  42388. defines["INSTANCES"] = useInstances;
  42389. changed = true;
  42390. }
  42391. if (changed) {
  42392. defines.markAsUnprocessed();
  42393. }
  42394. };
  42395. /**
  42396. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42397. * @param mesh The mesh containing the geometry data we will draw
  42398. * @param defines The defines to update
  42399. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42400. * @param useBones Precise whether bones should be used or not (override mesh info)
  42401. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42402. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42403. * @returns false if defines are considered not dirty and have not been checked
  42404. */
  42405. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42406. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42407. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42408. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42409. return false;
  42410. }
  42411. defines._normals = defines._needNormals;
  42412. defines._uvs = defines._needUVs;
  42413. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42414. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42415. defines["TANGENT"] = true;
  42416. }
  42417. if (defines._needUVs) {
  42418. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42419. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42420. }
  42421. else {
  42422. defines["UV1"] = false;
  42423. defines["UV2"] = false;
  42424. }
  42425. if (useVertexColor) {
  42426. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42427. defines["VERTEXCOLOR"] = hasVertexColors;
  42428. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42429. }
  42430. if (useBones) {
  42431. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42432. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42433. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42434. }
  42435. else {
  42436. defines["NUM_BONE_INFLUENCERS"] = 0;
  42437. defines["BonesPerMesh"] = 0;
  42438. }
  42439. }
  42440. if (useMorphTargets) {
  42441. var manager = mesh.morphTargetManager;
  42442. if (manager) {
  42443. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42444. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42445. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42446. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42447. }
  42448. else {
  42449. defines["MORPHTARGETS_TANGENT"] = false;
  42450. defines["MORPHTARGETS_NORMAL"] = false;
  42451. defines["MORPHTARGETS"] = false;
  42452. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42453. }
  42454. }
  42455. return true;
  42456. };
  42457. /**
  42458. * Prepares the defines related to the light information passed in parameter
  42459. * @param scene The scene we are intending to draw
  42460. * @param mesh The mesh the effect is compiling for
  42461. * @param defines The defines to update
  42462. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42463. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42464. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42465. * @returns true if normals will be required for the rest of the effect
  42466. */
  42467. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42468. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42469. if (disableLighting === void 0) { disableLighting = false; }
  42470. if (!defines._areLightsDirty) {
  42471. return defines._needNormals;
  42472. }
  42473. var lightIndex = 0;
  42474. var needNormals = false;
  42475. var needRebuild = false;
  42476. var lightmapMode = false;
  42477. var shadowEnabled = false;
  42478. var specularEnabled = false;
  42479. if (scene.lightsEnabled && !disableLighting) {
  42480. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42481. var light = _a[_i];
  42482. needNormals = true;
  42483. if (defines["LIGHT" + lightIndex] === undefined) {
  42484. needRebuild = true;
  42485. }
  42486. defines["LIGHT" + lightIndex] = true;
  42487. defines["SPOTLIGHT" + lightIndex] = false;
  42488. defines["HEMILIGHT" + lightIndex] = false;
  42489. defines["POINTLIGHT" + lightIndex] = false;
  42490. defines["DIRLIGHT" + lightIndex] = false;
  42491. var type;
  42492. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42493. type = "SPOTLIGHT" + lightIndex;
  42494. var spotLight = light;
  42495. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42496. }
  42497. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42498. type = "HEMILIGHT" + lightIndex;
  42499. }
  42500. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42501. type = "POINTLIGHT" + lightIndex;
  42502. }
  42503. else {
  42504. type = "DIRLIGHT" + lightIndex;
  42505. }
  42506. defines[type] = true;
  42507. // Specular
  42508. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42509. specularEnabled = true;
  42510. }
  42511. // Shadows
  42512. defines["SHADOW" + lightIndex] = false;
  42513. defines["SHADOWPCF" + lightIndex] = false;
  42514. defines["SHADOWPCSS" + lightIndex] = false;
  42515. defines["SHADOWPOISSON" + lightIndex] = false;
  42516. defines["SHADOWESM" + lightIndex] = false;
  42517. defines["SHADOWCUBE" + lightIndex] = false;
  42518. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42519. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42520. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42521. var shadowGenerator = light.getShadowGenerator();
  42522. if (shadowGenerator) {
  42523. shadowEnabled = true;
  42524. shadowGenerator.prepareDefines(defines, lightIndex);
  42525. }
  42526. }
  42527. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42528. lightmapMode = true;
  42529. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42530. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42531. }
  42532. else {
  42533. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42534. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42535. }
  42536. lightIndex++;
  42537. if (lightIndex === maxSimultaneousLights)
  42538. break;
  42539. }
  42540. }
  42541. defines["SPECULARTERM"] = specularEnabled;
  42542. defines["SHADOWS"] = shadowEnabled;
  42543. // Resetting all other lights if any
  42544. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42545. if (defines["LIGHT" + index] !== undefined) {
  42546. defines["LIGHT" + index] = false;
  42547. defines["HEMILIGHT" + lightIndex] = false;
  42548. defines["POINTLIGHT" + lightIndex] = false;
  42549. defines["DIRLIGHT" + lightIndex] = false;
  42550. defines["SPOTLIGHT" + lightIndex] = false;
  42551. defines["SHADOW" + lightIndex] = false;
  42552. }
  42553. }
  42554. var caps = scene.getEngine().getCaps();
  42555. if (defines["SHADOWFLOAT"] === undefined) {
  42556. needRebuild = true;
  42557. }
  42558. defines["SHADOWFLOAT"] = shadowEnabled &&
  42559. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42560. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42561. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42562. if (needRebuild) {
  42563. defines.rebuild();
  42564. }
  42565. return needNormals;
  42566. };
  42567. /**
  42568. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42569. * that won t be acctive due to defines being turned off.
  42570. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42571. * @param samplersList The samplers list
  42572. * @param defines The defines helping in the list generation
  42573. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42574. */
  42575. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42576. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42577. var uniformsList;
  42578. var uniformBuffersList = null;
  42579. if (uniformsListOrOptions.uniformsNames) {
  42580. var options = uniformsListOrOptions;
  42581. uniformsList = options.uniformsNames;
  42582. uniformBuffersList = options.uniformBuffersNames;
  42583. samplersList = options.samplers;
  42584. defines = options.defines;
  42585. maxSimultaneousLights = options.maxSimultaneousLights;
  42586. }
  42587. else {
  42588. uniformsList = uniformsListOrOptions;
  42589. if (!samplersList) {
  42590. samplersList = [];
  42591. }
  42592. }
  42593. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42594. if (!defines["LIGHT" + lightIndex]) {
  42595. break;
  42596. }
  42597. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42598. if (uniformBuffersList) {
  42599. uniformBuffersList.push("Light" + lightIndex);
  42600. }
  42601. samplersList.push("shadowSampler" + lightIndex);
  42602. samplersList.push("depthSampler" + lightIndex);
  42603. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42604. samplersList.push("projectionLightSampler" + lightIndex);
  42605. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42606. }
  42607. }
  42608. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42609. uniformsList.push("morphTargetInfluences");
  42610. }
  42611. };
  42612. /**
  42613. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42614. * @param defines The defines to update while falling back
  42615. * @param fallbacks The authorized effect fallbacks
  42616. * @param maxSimultaneousLights The maximum number of lights allowed
  42617. * @param rank the current rank of the Effect
  42618. * @returns The newly affected rank
  42619. */
  42620. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42621. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42622. if (rank === void 0) { rank = 0; }
  42623. var lightFallbackRank = 0;
  42624. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42625. if (!defines["LIGHT" + lightIndex]) {
  42626. break;
  42627. }
  42628. if (lightIndex > 0) {
  42629. lightFallbackRank = rank + lightIndex;
  42630. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42631. }
  42632. if (!defines["SHADOWS"]) {
  42633. if (defines["SHADOW" + lightIndex]) {
  42634. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42635. }
  42636. if (defines["SHADOWPCF" + lightIndex]) {
  42637. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42638. }
  42639. if (defines["SHADOWPCSS" + lightIndex]) {
  42640. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42641. }
  42642. if (defines["SHADOWPOISSON" + lightIndex]) {
  42643. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42644. }
  42645. if (defines["SHADOWESM" + lightIndex]) {
  42646. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42647. }
  42648. }
  42649. }
  42650. return lightFallbackRank++;
  42651. };
  42652. /**
  42653. * Prepares the list of attributes required for morph targets according to the effect defines.
  42654. * @param attribs The current list of supported attribs
  42655. * @param mesh The mesh to prepare the morph targets attributes for
  42656. * @param defines The current Defines of the effect
  42657. */
  42658. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42659. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42660. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42661. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42662. var manager = mesh.morphTargetManager;
  42663. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42664. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42665. for (var index = 0; index < influencers; index++) {
  42666. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42667. if (normal) {
  42668. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42669. }
  42670. if (tangent) {
  42671. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42672. }
  42673. if (attribs.length > maxAttributesCount) {
  42674. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42675. }
  42676. }
  42677. }
  42678. };
  42679. /**
  42680. * Prepares the list of attributes required for bones according to the effect defines.
  42681. * @param attribs The current list of supported attribs
  42682. * @param mesh The mesh to prepare the bones attributes for
  42683. * @param defines The current Defines of the effect
  42684. * @param fallbacks The current efffect fallback strategy
  42685. */
  42686. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42687. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42688. fallbacks.addCPUSkinningFallback(0, mesh);
  42689. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42690. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42691. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42692. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42693. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42694. }
  42695. }
  42696. };
  42697. /**
  42698. * Prepares the list of attributes required for instances according to the effect defines.
  42699. * @param attribs The current list of supported attribs
  42700. * @param defines The current Defines of the effect
  42701. */
  42702. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42703. if (defines["INSTANCES"]) {
  42704. attribs.push("world0");
  42705. attribs.push("world1");
  42706. attribs.push("world2");
  42707. attribs.push("world3");
  42708. }
  42709. };
  42710. /**
  42711. * Binds the light shadow information to the effect for the given mesh.
  42712. * @param light The light containing the generator
  42713. * @param scene The scene the lights belongs to
  42714. * @param mesh The mesh we are binding the information to render
  42715. * @param lightIndex The light index in the effect used to render the mesh
  42716. * @param effect The effect we are binding the data to
  42717. */
  42718. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42719. if (light.shadowEnabled && mesh.receiveShadows) {
  42720. var shadowGenerator = light.getShadowGenerator();
  42721. if (shadowGenerator) {
  42722. shadowGenerator.bindShadowLight(lightIndex, effect);
  42723. }
  42724. }
  42725. };
  42726. /**
  42727. * Binds the light information to the effect.
  42728. * @param light The light containing the generator
  42729. * @param effect The effect we are binding the data to
  42730. * @param lightIndex The light index in the effect used to render
  42731. */
  42732. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42733. light.transferToEffect(effect, lightIndex + "");
  42734. };
  42735. /**
  42736. * Binds the lights information from the scene to the effect for the given mesh.
  42737. * @param scene The scene the lights belongs to
  42738. * @param mesh The mesh we are binding the information to render
  42739. * @param effect The effect we are binding the data to
  42740. * @param defines The generated defines for the effect
  42741. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42742. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42743. */
  42744. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42745. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42746. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42747. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42748. for (var i = 0; i < len; i++) {
  42749. var light = mesh._lightSources[i];
  42750. var iAsString = i.toString();
  42751. var scaledIntensity = light.getScaledIntensity();
  42752. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42753. MaterialHelper.BindLightProperties(light, effect, i);
  42754. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42755. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42756. if (defines["SPECULARTERM"]) {
  42757. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42758. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42759. }
  42760. // Shadows
  42761. if (scene.shadowsEnabled) {
  42762. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42763. }
  42764. light._uniformBuffer.update();
  42765. }
  42766. };
  42767. /**
  42768. * Binds the fog information from the scene to the effect for the given mesh.
  42769. * @param scene The scene the lights belongs to
  42770. * @param mesh The mesh we are binding the information to render
  42771. * @param effect The effect we are binding the data to
  42772. */
  42773. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42774. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42775. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42776. effect.setColor3("vFogColor", scene.fogColor);
  42777. }
  42778. };
  42779. /**
  42780. * Binds the bones information from the mesh to the effect.
  42781. * @param mesh The mesh we are binding the information to render
  42782. * @param effect The effect we are binding the data to
  42783. */
  42784. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42785. if (!effect || !mesh) {
  42786. return;
  42787. }
  42788. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42789. mesh.computeBonesUsingShaders = false;
  42790. }
  42791. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42792. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42793. if (matrices) {
  42794. effect.setMatrices("mBones", matrices);
  42795. }
  42796. }
  42797. };
  42798. /**
  42799. * Binds the morph targets information from the mesh to the effect.
  42800. * @param abstractMesh The mesh we are binding the information to render
  42801. * @param effect The effect we are binding the data to
  42802. */
  42803. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42804. var manager = abstractMesh.morphTargetManager;
  42805. if (!abstractMesh || !manager) {
  42806. return;
  42807. }
  42808. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42809. };
  42810. /**
  42811. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42812. * @param defines The generated defines used in the effect
  42813. * @param effect The effect we are binding the data to
  42814. * @param scene The scene we are willing to render with logarithmic scale for
  42815. */
  42816. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42817. if (defines["LOGARITHMICDEPTH"]) {
  42818. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42819. }
  42820. };
  42821. /**
  42822. * Binds the clip plane information from the scene to the effect.
  42823. * @param scene The scene the clip plane information are extracted from
  42824. * @param effect The effect we are binding the data to
  42825. */
  42826. MaterialHelper.BindClipPlane = function (effect, scene) {
  42827. if (scene.clipPlane) {
  42828. var clipPlane = scene.clipPlane;
  42829. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42830. }
  42831. };
  42832. return MaterialHelper;
  42833. }());
  42834. BABYLON.MaterialHelper = MaterialHelper;
  42835. })(BABYLON || (BABYLON = {}));
  42836. //# sourceMappingURL=babylon.materialHelper.js.map
  42837. var BABYLON;
  42838. (function (BABYLON) {
  42839. var PushMaterial = /** @class */ (function (_super) {
  42840. __extends(PushMaterial, _super);
  42841. function PushMaterial(name, scene) {
  42842. var _this = _super.call(this, name, scene) || this;
  42843. _this._normalMatrix = new BABYLON.Matrix();
  42844. _this.storeEffectOnSubMeshes = true;
  42845. return _this;
  42846. }
  42847. PushMaterial.prototype.getEffect = function () {
  42848. return this._activeEffect;
  42849. };
  42850. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42851. if (!mesh) {
  42852. return false;
  42853. }
  42854. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42855. return true;
  42856. }
  42857. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42858. };
  42859. /**
  42860. * Binds the given world matrix to the active effect
  42861. *
  42862. * @param world the matrix to bind
  42863. */
  42864. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42865. this._activeEffect.setMatrix("world", world);
  42866. };
  42867. /**
  42868. * Binds the given normal matrix to the active effect
  42869. *
  42870. * @param normalMatrix the matrix to bind
  42871. */
  42872. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42873. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42874. };
  42875. PushMaterial.prototype.bind = function (world, mesh) {
  42876. if (!mesh) {
  42877. return;
  42878. }
  42879. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42880. };
  42881. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42882. if (effect === void 0) { effect = null; }
  42883. _super.prototype._afterBind.call(this, mesh);
  42884. this.getScene()._cachedEffect = effect;
  42885. };
  42886. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42887. if (visibility === void 0) { visibility = 1; }
  42888. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42889. };
  42890. return PushMaterial;
  42891. }(BABYLON.Material));
  42892. BABYLON.PushMaterial = PushMaterial;
  42893. })(BABYLON || (BABYLON = {}));
  42894. //# sourceMappingURL=babylon.pushMaterial.js.map
  42895. var BABYLON;
  42896. (function (BABYLON) {
  42897. /** @hidden */
  42898. var StandardMaterialDefines = /** @class */ (function (_super) {
  42899. __extends(StandardMaterialDefines, _super);
  42900. function StandardMaterialDefines() {
  42901. var _this = _super.call(this) || this;
  42902. _this.MAINUV1 = false;
  42903. _this.MAINUV2 = false;
  42904. _this.DIFFUSE = false;
  42905. _this.DIFFUSEDIRECTUV = 0;
  42906. _this.AMBIENT = false;
  42907. _this.AMBIENTDIRECTUV = 0;
  42908. _this.OPACITY = false;
  42909. _this.OPACITYDIRECTUV = 0;
  42910. _this.OPACITYRGB = false;
  42911. _this.REFLECTION = false;
  42912. _this.EMISSIVE = false;
  42913. _this.EMISSIVEDIRECTUV = 0;
  42914. _this.SPECULAR = false;
  42915. _this.SPECULARDIRECTUV = 0;
  42916. _this.BUMP = false;
  42917. _this.BUMPDIRECTUV = 0;
  42918. _this.PARALLAX = false;
  42919. _this.PARALLAXOCCLUSION = false;
  42920. _this.SPECULAROVERALPHA = false;
  42921. _this.CLIPPLANE = false;
  42922. _this.ALPHATEST = false;
  42923. _this.DEPTHPREPASS = false;
  42924. _this.ALPHAFROMDIFFUSE = false;
  42925. _this.POINTSIZE = false;
  42926. _this.FOG = false;
  42927. _this.SPECULARTERM = false;
  42928. _this.DIFFUSEFRESNEL = false;
  42929. _this.OPACITYFRESNEL = false;
  42930. _this.REFLECTIONFRESNEL = false;
  42931. _this.REFRACTIONFRESNEL = false;
  42932. _this.EMISSIVEFRESNEL = false;
  42933. _this.FRESNEL = false;
  42934. _this.NORMAL = false;
  42935. _this.UV1 = false;
  42936. _this.UV2 = false;
  42937. _this.VERTEXCOLOR = false;
  42938. _this.VERTEXALPHA = false;
  42939. _this.NUM_BONE_INFLUENCERS = 0;
  42940. _this.BonesPerMesh = 0;
  42941. _this.INSTANCES = false;
  42942. _this.GLOSSINESS = false;
  42943. _this.ROUGHNESS = false;
  42944. _this.EMISSIVEASILLUMINATION = false;
  42945. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42946. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42947. _this.LIGHTMAP = false;
  42948. _this.LIGHTMAPDIRECTUV = 0;
  42949. _this.OBJECTSPACE_NORMALMAP = false;
  42950. _this.USELIGHTMAPASSHADOWMAP = false;
  42951. _this.REFLECTIONMAP_3D = false;
  42952. _this.REFLECTIONMAP_SPHERICAL = false;
  42953. _this.REFLECTIONMAP_PLANAR = false;
  42954. _this.REFLECTIONMAP_CUBIC = false;
  42955. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42956. _this.REFLECTIONMAP_PROJECTION = false;
  42957. _this.REFLECTIONMAP_SKYBOX = false;
  42958. _this.REFLECTIONMAP_EXPLICIT = false;
  42959. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42960. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42961. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42962. _this.INVERTCUBICMAP = false;
  42963. _this.LOGARITHMICDEPTH = false;
  42964. _this.REFRACTION = false;
  42965. _this.REFRACTIONMAP_3D = false;
  42966. _this.REFLECTIONOVERALPHA = false;
  42967. _this.TWOSIDEDLIGHTING = false;
  42968. _this.SHADOWFLOAT = false;
  42969. _this.MORPHTARGETS = false;
  42970. _this.MORPHTARGETS_NORMAL = false;
  42971. _this.MORPHTARGETS_TANGENT = false;
  42972. _this.NUM_MORPH_INFLUENCERS = 0;
  42973. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42974. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42975. _this.IMAGEPROCESSING = false;
  42976. _this.VIGNETTE = false;
  42977. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42978. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42979. _this.TONEMAPPING = false;
  42980. _this.CONTRAST = false;
  42981. _this.COLORCURVES = false;
  42982. _this.COLORGRADING = false;
  42983. _this.COLORGRADING3D = false;
  42984. _this.SAMPLER3DGREENDEPTH = false;
  42985. _this.SAMPLER3DBGRMAP = false;
  42986. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42987. /**
  42988. * If the reflection texture on this material is in linear color space
  42989. * @hidden
  42990. */
  42991. _this.IS_REFLECTION_LINEAR = false;
  42992. /**
  42993. * If the refraction texture on this material is in linear color space
  42994. * @hidden
  42995. */
  42996. _this.IS_REFRACTION_LINEAR = false;
  42997. _this.EXPOSURE = false;
  42998. _this.rebuild();
  42999. return _this;
  43000. }
  43001. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43002. var modes = [
  43003. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43004. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43005. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43006. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43007. ];
  43008. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43009. var mode = modes_1[_i];
  43010. this[mode] = (mode === modeToEnable);
  43011. }
  43012. };
  43013. return StandardMaterialDefines;
  43014. }(BABYLON.MaterialDefines));
  43015. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43016. var StandardMaterial = /** @class */ (function (_super) {
  43017. __extends(StandardMaterial, _super);
  43018. function StandardMaterial(name, scene) {
  43019. var _this = _super.call(this, name, scene) || this;
  43020. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43021. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43022. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43023. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43024. _this.specularPower = 64;
  43025. _this._useAlphaFromDiffuseTexture = false;
  43026. _this._useEmissiveAsIllumination = false;
  43027. _this._linkEmissiveWithDiffuse = false;
  43028. _this._useSpecularOverAlpha = false;
  43029. _this._useReflectionOverAlpha = false;
  43030. _this._disableLighting = false;
  43031. _this._useObjectSpaceNormalMap = false;
  43032. _this._useParallax = false;
  43033. _this._useParallaxOcclusion = false;
  43034. _this.parallaxScaleBias = 0.05;
  43035. _this._roughness = 0;
  43036. _this.indexOfRefraction = 0.98;
  43037. _this.invertRefractionY = true;
  43038. /**
  43039. * Defines the alpha limits in alpha test mode
  43040. */
  43041. _this.alphaCutOff = 0.4;
  43042. _this._useLightmapAsShadowmap = false;
  43043. _this._useReflectionFresnelFromSpecular = false;
  43044. _this._useGlossinessFromSpecularMapAlpha = false;
  43045. _this._maxSimultaneousLights = 4;
  43046. /**
  43047. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43048. */
  43049. _this._invertNormalMapX = false;
  43050. /**
  43051. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43052. */
  43053. _this._invertNormalMapY = false;
  43054. /**
  43055. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43056. */
  43057. _this._twoSidedLighting = false;
  43058. _this._renderTargets = new BABYLON.SmartArray(16);
  43059. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43060. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43061. // Setup the default processing configuration to the scene.
  43062. _this._attachImageProcessingConfiguration(null);
  43063. _this.getRenderTargetTextures = function () {
  43064. _this._renderTargets.reset();
  43065. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43066. _this._renderTargets.push(_this._reflectionTexture);
  43067. }
  43068. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43069. _this._renderTargets.push(_this._refractionTexture);
  43070. }
  43071. return _this._renderTargets;
  43072. };
  43073. return _this;
  43074. }
  43075. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43076. /**
  43077. * Gets the image processing configuration used either in this material.
  43078. */
  43079. get: function () {
  43080. return this._imageProcessingConfiguration;
  43081. },
  43082. /**
  43083. * Sets the Default image processing configuration used either in the this material.
  43084. *
  43085. * If sets to null, the scene one is in use.
  43086. */
  43087. set: function (value) {
  43088. this._attachImageProcessingConfiguration(value);
  43089. // Ensure the effect will be rebuilt.
  43090. this._markAllSubMeshesAsTexturesDirty();
  43091. },
  43092. enumerable: true,
  43093. configurable: true
  43094. });
  43095. /**
  43096. * Attaches a new image processing configuration to the Standard Material.
  43097. * @param configuration
  43098. */
  43099. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43100. var _this = this;
  43101. if (configuration === this._imageProcessingConfiguration) {
  43102. return;
  43103. }
  43104. // Detaches observer.
  43105. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43106. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43107. }
  43108. // Pick the scene configuration if needed.
  43109. if (!configuration) {
  43110. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43111. }
  43112. else {
  43113. this._imageProcessingConfiguration = configuration;
  43114. }
  43115. // Attaches observer.
  43116. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43117. _this._markAllSubMeshesAsImageProcessingDirty();
  43118. });
  43119. };
  43120. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43121. /**
  43122. * Gets wether the color curves effect is enabled.
  43123. */
  43124. get: function () {
  43125. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43126. },
  43127. /**
  43128. * Sets wether the color curves effect is enabled.
  43129. */
  43130. set: function (value) {
  43131. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43132. },
  43133. enumerable: true,
  43134. configurable: true
  43135. });
  43136. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43137. /**
  43138. * Gets wether the color grading effect is enabled.
  43139. */
  43140. get: function () {
  43141. return this.imageProcessingConfiguration.colorGradingEnabled;
  43142. },
  43143. /**
  43144. * Gets wether the color grading effect is enabled.
  43145. */
  43146. set: function (value) {
  43147. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43148. },
  43149. enumerable: true,
  43150. configurable: true
  43151. });
  43152. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43153. /**
  43154. * Gets wether tonemapping is enabled or not.
  43155. */
  43156. get: function () {
  43157. return this._imageProcessingConfiguration.toneMappingEnabled;
  43158. },
  43159. /**
  43160. * Sets wether tonemapping is enabled or not
  43161. */
  43162. set: function (value) {
  43163. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43164. },
  43165. enumerable: true,
  43166. configurable: true
  43167. });
  43168. ;
  43169. ;
  43170. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43171. /**
  43172. * The camera exposure used on this material.
  43173. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43174. * This corresponds to a photographic exposure.
  43175. */
  43176. get: function () {
  43177. return this._imageProcessingConfiguration.exposure;
  43178. },
  43179. /**
  43180. * The camera exposure used on this material.
  43181. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43182. * This corresponds to a photographic exposure.
  43183. */
  43184. set: function (value) {
  43185. this._imageProcessingConfiguration.exposure = value;
  43186. },
  43187. enumerable: true,
  43188. configurable: true
  43189. });
  43190. ;
  43191. ;
  43192. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43193. /**
  43194. * Gets The camera contrast used on this material.
  43195. */
  43196. get: function () {
  43197. return this._imageProcessingConfiguration.contrast;
  43198. },
  43199. /**
  43200. * Sets The camera contrast used on this material.
  43201. */
  43202. set: function (value) {
  43203. this._imageProcessingConfiguration.contrast = value;
  43204. },
  43205. enumerable: true,
  43206. configurable: true
  43207. });
  43208. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43209. /**
  43210. * Gets the Color Grading 2D Lookup Texture.
  43211. */
  43212. get: function () {
  43213. return this._imageProcessingConfiguration.colorGradingTexture;
  43214. },
  43215. /**
  43216. * Sets the Color Grading 2D Lookup Texture.
  43217. */
  43218. set: function (value) {
  43219. this._imageProcessingConfiguration.colorGradingTexture = value;
  43220. },
  43221. enumerable: true,
  43222. configurable: true
  43223. });
  43224. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43225. /**
  43226. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43227. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43228. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  43229. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43230. */
  43231. get: function () {
  43232. return this._imageProcessingConfiguration.colorCurves;
  43233. },
  43234. /**
  43235. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43236. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43237. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  43238. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43239. */
  43240. set: function (value) {
  43241. this._imageProcessingConfiguration.colorCurves = value;
  43242. },
  43243. enumerable: true,
  43244. configurable: true
  43245. });
  43246. StandardMaterial.prototype.getClassName = function () {
  43247. return "StandardMaterial";
  43248. };
  43249. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43250. get: function () {
  43251. return this._useLogarithmicDepth;
  43252. },
  43253. set: function (value) {
  43254. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43255. this._markAllSubMeshesAsMiscDirty();
  43256. },
  43257. enumerable: true,
  43258. configurable: true
  43259. });
  43260. StandardMaterial.prototype.needAlphaBlending = function () {
  43261. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43262. };
  43263. StandardMaterial.prototype.needAlphaTesting = function () {
  43264. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43265. };
  43266. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43267. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43268. };
  43269. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43270. return this._diffuseTexture;
  43271. };
  43272. /**
  43273. * Child classes can use it to update shaders
  43274. */
  43275. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43276. if (useInstances === void 0) { useInstances = false; }
  43277. if (subMesh.effect && this.isFrozen) {
  43278. if (this._wasPreviouslyReady && subMesh.effect) {
  43279. return true;
  43280. }
  43281. }
  43282. if (!subMesh._materialDefines) {
  43283. subMesh._materialDefines = new StandardMaterialDefines();
  43284. }
  43285. var scene = this.getScene();
  43286. var defines = subMesh._materialDefines;
  43287. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43288. if (defines._renderId === scene.getRenderId()) {
  43289. return true;
  43290. }
  43291. }
  43292. var engine = scene.getEngine();
  43293. // Lights
  43294. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43295. // Textures
  43296. if (defines._areTexturesDirty) {
  43297. defines._needUVs = false;
  43298. defines.MAINUV1 = false;
  43299. defines.MAINUV2 = false;
  43300. if (scene.texturesEnabled) {
  43301. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43302. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43303. return false;
  43304. }
  43305. else {
  43306. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43307. }
  43308. }
  43309. else {
  43310. defines.DIFFUSE = false;
  43311. }
  43312. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43313. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43314. return false;
  43315. }
  43316. else {
  43317. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43318. }
  43319. }
  43320. else {
  43321. defines.AMBIENT = false;
  43322. }
  43323. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43324. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43325. return false;
  43326. }
  43327. else {
  43328. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43329. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43330. }
  43331. }
  43332. else {
  43333. defines.OPACITY = false;
  43334. }
  43335. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43336. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43337. return false;
  43338. }
  43339. else {
  43340. defines._needNormals = true;
  43341. defines.REFLECTION = true;
  43342. defines.ROUGHNESS = (this._roughness > 0);
  43343. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43344. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43345. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43346. switch (this._reflectionTexture.coordinatesMode) {
  43347. case BABYLON.Texture.EXPLICIT_MODE:
  43348. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43349. break;
  43350. case BABYLON.Texture.PLANAR_MODE:
  43351. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43352. break;
  43353. case BABYLON.Texture.PROJECTION_MODE:
  43354. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43355. break;
  43356. case BABYLON.Texture.SKYBOX_MODE:
  43357. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43358. break;
  43359. case BABYLON.Texture.SPHERICAL_MODE:
  43360. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43361. break;
  43362. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43363. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43364. break;
  43365. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43366. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43367. break;
  43368. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43369. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43370. break;
  43371. case BABYLON.Texture.CUBIC_MODE:
  43372. case BABYLON.Texture.INVCUBIC_MODE:
  43373. default:
  43374. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43375. break;
  43376. }
  43377. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43378. }
  43379. }
  43380. else {
  43381. defines.REFLECTION = false;
  43382. }
  43383. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43384. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43385. return false;
  43386. }
  43387. else {
  43388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43389. }
  43390. }
  43391. else {
  43392. defines.EMISSIVE = false;
  43393. }
  43394. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43395. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43396. return false;
  43397. }
  43398. else {
  43399. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43400. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43401. }
  43402. }
  43403. else {
  43404. defines.LIGHTMAP = false;
  43405. }
  43406. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43407. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43408. return false;
  43409. }
  43410. else {
  43411. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43412. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43413. }
  43414. }
  43415. else {
  43416. defines.SPECULAR = false;
  43417. }
  43418. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43419. // Bump texure can not be not blocking.
  43420. if (!this._bumpTexture.isReady()) {
  43421. return false;
  43422. }
  43423. else {
  43424. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43425. defines.PARALLAX = this._useParallax;
  43426. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43427. }
  43428. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43429. }
  43430. else {
  43431. defines.BUMP = false;
  43432. }
  43433. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43434. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43435. return false;
  43436. }
  43437. else {
  43438. defines._needUVs = true;
  43439. defines.REFRACTION = true;
  43440. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43441. }
  43442. }
  43443. else {
  43444. defines.REFRACTION = false;
  43445. }
  43446. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43447. }
  43448. else {
  43449. defines.DIFFUSE = false;
  43450. defines.AMBIENT = false;
  43451. defines.OPACITY = false;
  43452. defines.REFLECTION = false;
  43453. defines.EMISSIVE = false;
  43454. defines.LIGHTMAP = false;
  43455. defines.BUMP = false;
  43456. defines.REFRACTION = false;
  43457. }
  43458. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43459. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43460. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43461. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43462. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43463. }
  43464. if (defines._areImageProcessingDirty) {
  43465. if (!this._imageProcessingConfiguration.isReady()) {
  43466. return false;
  43467. }
  43468. this._imageProcessingConfiguration.prepareDefines(defines);
  43469. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43470. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43471. }
  43472. if (defines._areFresnelDirty) {
  43473. if (StandardMaterial.FresnelEnabled) {
  43474. // Fresnel
  43475. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43476. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43477. this._reflectionFresnelParameters) {
  43478. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43479. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43480. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43481. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43482. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43483. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43484. defines._needNormals = true;
  43485. defines.FRESNEL = true;
  43486. }
  43487. }
  43488. else {
  43489. defines.FRESNEL = false;
  43490. }
  43491. }
  43492. // Misc.
  43493. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43494. // Attribs
  43495. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43496. // Values that need to be evaluated on every frame
  43497. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43498. // Get correct effect
  43499. if (defines.isDirty) {
  43500. defines.markAsProcessed();
  43501. scene.resetCachedMaterial();
  43502. // Fallbacks
  43503. var fallbacks = new BABYLON.EffectFallbacks();
  43504. if (defines.REFLECTION) {
  43505. fallbacks.addFallback(0, "REFLECTION");
  43506. }
  43507. if (defines.SPECULAR) {
  43508. fallbacks.addFallback(0, "SPECULAR");
  43509. }
  43510. if (defines.BUMP) {
  43511. fallbacks.addFallback(0, "BUMP");
  43512. }
  43513. if (defines.PARALLAX) {
  43514. fallbacks.addFallback(1, "PARALLAX");
  43515. }
  43516. if (defines.PARALLAXOCCLUSION) {
  43517. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43518. }
  43519. if (defines.SPECULAROVERALPHA) {
  43520. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43521. }
  43522. if (defines.FOG) {
  43523. fallbacks.addFallback(1, "FOG");
  43524. }
  43525. if (defines.POINTSIZE) {
  43526. fallbacks.addFallback(0, "POINTSIZE");
  43527. }
  43528. if (defines.LOGARITHMICDEPTH) {
  43529. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43530. }
  43531. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43532. if (defines.SPECULARTERM) {
  43533. fallbacks.addFallback(0, "SPECULARTERM");
  43534. }
  43535. if (defines.DIFFUSEFRESNEL) {
  43536. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43537. }
  43538. if (defines.OPACITYFRESNEL) {
  43539. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43540. }
  43541. if (defines.REFLECTIONFRESNEL) {
  43542. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43543. }
  43544. if (defines.EMISSIVEFRESNEL) {
  43545. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43546. }
  43547. if (defines.FRESNEL) {
  43548. fallbacks.addFallback(4, "FRESNEL");
  43549. }
  43550. //Attributes
  43551. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43552. if (defines.NORMAL) {
  43553. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43554. }
  43555. if (defines.UV1) {
  43556. attribs.push(BABYLON.VertexBuffer.UVKind);
  43557. }
  43558. if (defines.UV2) {
  43559. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43560. }
  43561. if (defines.VERTEXCOLOR) {
  43562. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43563. }
  43564. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43565. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43566. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43567. var shaderName = "default";
  43568. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43569. "vFogInfos", "vFogColor", "pointSize",
  43570. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43571. "mBones",
  43572. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43573. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43574. "vReflectionPosition", "vReflectionSize",
  43575. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43576. ];
  43577. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43578. var uniformBuffers = ["Material", "Scene"];
  43579. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43580. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43581. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43582. uniformsNames: uniforms,
  43583. uniformBuffersNames: uniformBuffers,
  43584. samplers: samplers,
  43585. defines: defines,
  43586. maxSimultaneousLights: this._maxSimultaneousLights
  43587. });
  43588. if (this.customShaderNameResolve) {
  43589. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43590. }
  43591. var join = defines.toString();
  43592. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43593. attributes: attribs,
  43594. uniformsNames: uniforms,
  43595. uniformBuffersNames: uniformBuffers,
  43596. samplers: samplers,
  43597. defines: join,
  43598. fallbacks: fallbacks,
  43599. onCompiled: this.onCompiled,
  43600. onError: this.onError,
  43601. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43602. }, engine), defines);
  43603. this.buildUniformLayout();
  43604. }
  43605. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43606. return false;
  43607. }
  43608. defines._renderId = scene.getRenderId();
  43609. this._wasPreviouslyReady = true;
  43610. return true;
  43611. };
  43612. StandardMaterial.prototype.buildUniformLayout = function () {
  43613. // Order is important !
  43614. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43615. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43616. this._uniformBuffer.addUniform("opacityParts", 4);
  43617. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43618. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43619. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43620. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43621. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43622. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43623. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43624. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43625. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43626. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43627. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43628. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43629. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43630. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43631. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43632. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43633. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43634. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43635. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43636. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43637. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43638. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43639. this._uniformBuffer.addUniform("specularMatrix", 16);
  43640. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43641. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43642. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43643. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43644. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43645. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43646. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43647. this._uniformBuffer.addUniform("pointSize", 1);
  43648. this._uniformBuffer.create();
  43649. };
  43650. StandardMaterial.prototype.unbind = function () {
  43651. if (this._activeEffect) {
  43652. var needFlag = false;
  43653. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43654. this._activeEffect.setTexture("reflection2DSampler", null);
  43655. needFlag = true;
  43656. }
  43657. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43658. this._activeEffect.setTexture("refraction2DSampler", null);
  43659. needFlag = true;
  43660. }
  43661. if (needFlag) {
  43662. this._markAllSubMeshesAsTexturesDirty();
  43663. }
  43664. }
  43665. _super.prototype.unbind.call(this);
  43666. };
  43667. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43668. var scene = this.getScene();
  43669. var defines = subMesh._materialDefines;
  43670. if (!defines) {
  43671. return;
  43672. }
  43673. var effect = subMesh.effect;
  43674. if (!effect) {
  43675. return;
  43676. }
  43677. this._activeEffect = effect;
  43678. // Matrices
  43679. this.bindOnlyWorldMatrix(world);
  43680. // Normal Matrix
  43681. if (defines.OBJECTSPACE_NORMALMAP) {
  43682. world.toNormalMatrix(this._normalMatrix);
  43683. this.bindOnlyNormalMatrix(this._normalMatrix);
  43684. }
  43685. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43686. // Bones
  43687. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43688. if (mustRebind) {
  43689. this._uniformBuffer.bindToEffect(effect, "Material");
  43690. this.bindViewProjection(effect);
  43691. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43692. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43693. // Fresnel
  43694. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43695. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43696. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43697. }
  43698. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43699. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43700. }
  43701. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43702. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43703. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43704. }
  43705. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43706. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43707. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43708. }
  43709. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43710. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43711. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43712. }
  43713. }
  43714. // Textures
  43715. if (scene.texturesEnabled) {
  43716. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43717. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43718. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43719. if (this._diffuseTexture.hasAlpha) {
  43720. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43721. }
  43722. }
  43723. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43724. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43725. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43726. }
  43727. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43728. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43729. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43730. }
  43731. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43732. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43733. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43734. if (this._reflectionTexture.boundingBoxSize) {
  43735. var cubeTexture = this._reflectionTexture;
  43736. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43737. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43738. }
  43739. }
  43740. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43741. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43742. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43743. }
  43744. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43745. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43746. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43747. }
  43748. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43749. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43750. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43751. }
  43752. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43753. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43754. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43755. if (scene._mirroredCameraPosition) {
  43756. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43757. }
  43758. else {
  43759. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43760. }
  43761. }
  43762. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43763. var depth = 1.0;
  43764. if (!this._refractionTexture.isCube) {
  43765. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43766. if (this._refractionTexture.depth) {
  43767. depth = this._refractionTexture.depth;
  43768. }
  43769. }
  43770. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43771. }
  43772. }
  43773. // Point size
  43774. if (this.pointsCloud) {
  43775. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43776. }
  43777. if (defines.SPECULARTERM) {
  43778. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43779. }
  43780. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43781. // Diffuse
  43782. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43783. }
  43784. // Textures
  43785. if (scene.texturesEnabled) {
  43786. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43787. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43788. }
  43789. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43790. effect.setTexture("ambientSampler", this._ambientTexture);
  43791. }
  43792. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43793. effect.setTexture("opacitySampler", this._opacityTexture);
  43794. }
  43795. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43796. if (this._reflectionTexture.isCube) {
  43797. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43798. }
  43799. else {
  43800. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43801. }
  43802. }
  43803. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43804. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43805. }
  43806. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43807. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43808. }
  43809. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43810. effect.setTexture("specularSampler", this._specularTexture);
  43811. }
  43812. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43813. effect.setTexture("bumpSampler", this._bumpTexture);
  43814. }
  43815. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43816. var depth = 1.0;
  43817. if (this._refractionTexture.isCube) {
  43818. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43819. }
  43820. else {
  43821. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43822. }
  43823. }
  43824. }
  43825. // Clip plane
  43826. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43827. // Colors
  43828. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43829. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43830. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43831. }
  43832. if (mustRebind || !this.isFrozen) {
  43833. // Lights
  43834. if (scene.lightsEnabled && !this._disableLighting) {
  43835. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43836. }
  43837. // View
  43838. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43839. this.bindView(effect);
  43840. }
  43841. // Fog
  43842. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43843. // Morph targets
  43844. if (defines.NUM_MORPH_INFLUENCERS) {
  43845. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43846. }
  43847. // Log. depth
  43848. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43849. // image processing
  43850. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43851. this._imageProcessingConfiguration.bind(this._activeEffect);
  43852. }
  43853. }
  43854. this._uniformBuffer.update();
  43855. this._afterBind(mesh, this._activeEffect);
  43856. };
  43857. StandardMaterial.prototype.getAnimatables = function () {
  43858. var results = [];
  43859. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43860. results.push(this._diffuseTexture);
  43861. }
  43862. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43863. results.push(this._ambientTexture);
  43864. }
  43865. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43866. results.push(this._opacityTexture);
  43867. }
  43868. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43869. results.push(this._reflectionTexture);
  43870. }
  43871. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43872. results.push(this._emissiveTexture);
  43873. }
  43874. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43875. results.push(this._specularTexture);
  43876. }
  43877. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43878. results.push(this._bumpTexture);
  43879. }
  43880. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43881. results.push(this._lightmapTexture);
  43882. }
  43883. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43884. results.push(this._refractionTexture);
  43885. }
  43886. return results;
  43887. };
  43888. StandardMaterial.prototype.getActiveTextures = function () {
  43889. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43890. if (this._diffuseTexture) {
  43891. activeTextures.push(this._diffuseTexture);
  43892. }
  43893. if (this._ambientTexture) {
  43894. activeTextures.push(this._ambientTexture);
  43895. }
  43896. if (this._opacityTexture) {
  43897. activeTextures.push(this._opacityTexture);
  43898. }
  43899. if (this._reflectionTexture) {
  43900. activeTextures.push(this._reflectionTexture);
  43901. }
  43902. if (this._emissiveTexture) {
  43903. activeTextures.push(this._emissiveTexture);
  43904. }
  43905. if (this._specularTexture) {
  43906. activeTextures.push(this._specularTexture);
  43907. }
  43908. if (this._bumpTexture) {
  43909. activeTextures.push(this._bumpTexture);
  43910. }
  43911. if (this._lightmapTexture) {
  43912. activeTextures.push(this._lightmapTexture);
  43913. }
  43914. if (this._refractionTexture) {
  43915. activeTextures.push(this._refractionTexture);
  43916. }
  43917. return activeTextures;
  43918. };
  43919. StandardMaterial.prototype.hasTexture = function (texture) {
  43920. if (_super.prototype.hasTexture.call(this, texture)) {
  43921. return true;
  43922. }
  43923. if (this._diffuseTexture === texture) {
  43924. return true;
  43925. }
  43926. if (this._ambientTexture === texture) {
  43927. return true;
  43928. }
  43929. if (this._opacityTexture === texture) {
  43930. return true;
  43931. }
  43932. if (this._reflectionTexture === texture) {
  43933. return true;
  43934. }
  43935. if (this._emissiveTexture === texture) {
  43936. return true;
  43937. }
  43938. if (this._specularTexture === texture) {
  43939. return true;
  43940. }
  43941. if (this._bumpTexture === texture) {
  43942. return true;
  43943. }
  43944. if (this._lightmapTexture === texture) {
  43945. return true;
  43946. }
  43947. if (this._refractionTexture === texture) {
  43948. return true;
  43949. }
  43950. return false;
  43951. };
  43952. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43953. if (forceDisposeTextures) {
  43954. if (this._diffuseTexture) {
  43955. this._diffuseTexture.dispose();
  43956. }
  43957. if (this._ambientTexture) {
  43958. this._ambientTexture.dispose();
  43959. }
  43960. if (this._opacityTexture) {
  43961. this._opacityTexture.dispose();
  43962. }
  43963. if (this._reflectionTexture) {
  43964. this._reflectionTexture.dispose();
  43965. }
  43966. if (this._emissiveTexture) {
  43967. this._emissiveTexture.dispose();
  43968. }
  43969. if (this._specularTexture) {
  43970. this._specularTexture.dispose();
  43971. }
  43972. if (this._bumpTexture) {
  43973. this._bumpTexture.dispose();
  43974. }
  43975. if (this._lightmapTexture) {
  43976. this._lightmapTexture.dispose();
  43977. }
  43978. if (this._refractionTexture) {
  43979. this._refractionTexture.dispose();
  43980. }
  43981. }
  43982. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43983. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43984. }
  43985. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43986. };
  43987. StandardMaterial.prototype.clone = function (name) {
  43988. var _this = this;
  43989. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43990. result.name = name;
  43991. result.id = name;
  43992. return result;
  43993. };
  43994. StandardMaterial.prototype.serialize = function () {
  43995. return BABYLON.SerializationHelper.Serialize(this);
  43996. };
  43997. // Statics
  43998. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43999. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44000. };
  44001. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44002. get: function () {
  44003. return StandardMaterial._DiffuseTextureEnabled;
  44004. },
  44005. set: function (value) {
  44006. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44007. return;
  44008. }
  44009. StandardMaterial._DiffuseTextureEnabled = value;
  44010. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44011. },
  44012. enumerable: true,
  44013. configurable: true
  44014. });
  44015. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44016. get: function () {
  44017. return StandardMaterial._AmbientTextureEnabled;
  44018. },
  44019. set: function (value) {
  44020. if (StandardMaterial._AmbientTextureEnabled === value) {
  44021. return;
  44022. }
  44023. StandardMaterial._AmbientTextureEnabled = value;
  44024. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44025. },
  44026. enumerable: true,
  44027. configurable: true
  44028. });
  44029. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44030. get: function () {
  44031. return StandardMaterial._OpacityTextureEnabled;
  44032. },
  44033. set: function (value) {
  44034. if (StandardMaterial._OpacityTextureEnabled === value) {
  44035. return;
  44036. }
  44037. StandardMaterial._OpacityTextureEnabled = value;
  44038. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44039. },
  44040. enumerable: true,
  44041. configurable: true
  44042. });
  44043. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44044. get: function () {
  44045. return StandardMaterial._ReflectionTextureEnabled;
  44046. },
  44047. set: function (value) {
  44048. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44049. return;
  44050. }
  44051. StandardMaterial._ReflectionTextureEnabled = value;
  44052. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44053. },
  44054. enumerable: true,
  44055. configurable: true
  44056. });
  44057. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44058. get: function () {
  44059. return StandardMaterial._EmissiveTextureEnabled;
  44060. },
  44061. set: function (value) {
  44062. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44063. return;
  44064. }
  44065. StandardMaterial._EmissiveTextureEnabled = value;
  44066. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44067. },
  44068. enumerable: true,
  44069. configurable: true
  44070. });
  44071. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44072. get: function () {
  44073. return StandardMaterial._SpecularTextureEnabled;
  44074. },
  44075. set: function (value) {
  44076. if (StandardMaterial._SpecularTextureEnabled === value) {
  44077. return;
  44078. }
  44079. StandardMaterial._SpecularTextureEnabled = value;
  44080. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44081. },
  44082. enumerable: true,
  44083. configurable: true
  44084. });
  44085. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44086. get: function () {
  44087. return StandardMaterial._BumpTextureEnabled;
  44088. },
  44089. set: function (value) {
  44090. if (StandardMaterial._BumpTextureEnabled === value) {
  44091. return;
  44092. }
  44093. StandardMaterial._BumpTextureEnabled = value;
  44094. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44095. },
  44096. enumerable: true,
  44097. configurable: true
  44098. });
  44099. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44100. get: function () {
  44101. return StandardMaterial._LightmapTextureEnabled;
  44102. },
  44103. set: function (value) {
  44104. if (StandardMaterial._LightmapTextureEnabled === value) {
  44105. return;
  44106. }
  44107. StandardMaterial._LightmapTextureEnabled = value;
  44108. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44109. },
  44110. enumerable: true,
  44111. configurable: true
  44112. });
  44113. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44114. get: function () {
  44115. return StandardMaterial._RefractionTextureEnabled;
  44116. },
  44117. set: function (value) {
  44118. if (StandardMaterial._RefractionTextureEnabled === value) {
  44119. return;
  44120. }
  44121. StandardMaterial._RefractionTextureEnabled = value;
  44122. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44123. },
  44124. enumerable: true,
  44125. configurable: true
  44126. });
  44127. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44128. get: function () {
  44129. return StandardMaterial._ColorGradingTextureEnabled;
  44130. },
  44131. set: function (value) {
  44132. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44133. return;
  44134. }
  44135. StandardMaterial._ColorGradingTextureEnabled = value;
  44136. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44137. },
  44138. enumerable: true,
  44139. configurable: true
  44140. });
  44141. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44142. get: function () {
  44143. return StandardMaterial._FresnelEnabled;
  44144. },
  44145. set: function (value) {
  44146. if (StandardMaterial._FresnelEnabled === value) {
  44147. return;
  44148. }
  44149. StandardMaterial._FresnelEnabled = value;
  44150. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44151. },
  44152. enumerable: true,
  44153. configurable: true
  44154. });
  44155. // Flags used to enable or disable a type of texture for all Standard Materials
  44156. StandardMaterial._DiffuseTextureEnabled = true;
  44157. StandardMaterial._AmbientTextureEnabled = true;
  44158. StandardMaterial._OpacityTextureEnabled = true;
  44159. StandardMaterial._ReflectionTextureEnabled = true;
  44160. StandardMaterial._EmissiveTextureEnabled = true;
  44161. StandardMaterial._SpecularTextureEnabled = true;
  44162. StandardMaterial._BumpTextureEnabled = true;
  44163. StandardMaterial._LightmapTextureEnabled = true;
  44164. StandardMaterial._RefractionTextureEnabled = true;
  44165. StandardMaterial._ColorGradingTextureEnabled = true;
  44166. StandardMaterial._FresnelEnabled = true;
  44167. __decorate([
  44168. BABYLON.serializeAsTexture("diffuseTexture")
  44169. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44170. __decorate([
  44171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44172. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44173. __decorate([
  44174. BABYLON.serializeAsTexture("ambientTexture")
  44175. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44176. __decorate([
  44177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44178. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44179. __decorate([
  44180. BABYLON.serializeAsTexture("opacityTexture")
  44181. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44182. __decorate([
  44183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44184. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44185. __decorate([
  44186. BABYLON.serializeAsTexture("reflectionTexture")
  44187. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44188. __decorate([
  44189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44190. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44191. __decorate([
  44192. BABYLON.serializeAsTexture("emissiveTexture")
  44193. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44194. __decorate([
  44195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44196. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44197. __decorate([
  44198. BABYLON.serializeAsTexture("specularTexture")
  44199. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44200. __decorate([
  44201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44202. ], StandardMaterial.prototype, "specularTexture", void 0);
  44203. __decorate([
  44204. BABYLON.serializeAsTexture("bumpTexture")
  44205. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44206. __decorate([
  44207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44208. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44209. __decorate([
  44210. BABYLON.serializeAsTexture("lightmapTexture")
  44211. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44212. __decorate([
  44213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44214. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44215. __decorate([
  44216. BABYLON.serializeAsTexture("refractionTexture")
  44217. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44218. __decorate([
  44219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44220. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44221. __decorate([
  44222. BABYLON.serializeAsColor3("ambient")
  44223. ], StandardMaterial.prototype, "ambientColor", void 0);
  44224. __decorate([
  44225. BABYLON.serializeAsColor3("diffuse")
  44226. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44227. __decorate([
  44228. BABYLON.serializeAsColor3("specular")
  44229. ], StandardMaterial.prototype, "specularColor", void 0);
  44230. __decorate([
  44231. BABYLON.serializeAsColor3("emissive")
  44232. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44233. __decorate([
  44234. BABYLON.serialize()
  44235. ], StandardMaterial.prototype, "specularPower", void 0);
  44236. __decorate([
  44237. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44238. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44239. __decorate([
  44240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44241. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44242. __decorate([
  44243. BABYLON.serialize("useEmissiveAsIllumination")
  44244. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44245. __decorate([
  44246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44247. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44248. __decorate([
  44249. BABYLON.serialize("linkEmissiveWithDiffuse")
  44250. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44251. __decorate([
  44252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44253. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44254. __decorate([
  44255. BABYLON.serialize("useSpecularOverAlpha")
  44256. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44257. __decorate([
  44258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44259. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44260. __decorate([
  44261. BABYLON.serialize("useReflectionOverAlpha")
  44262. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44263. __decorate([
  44264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44265. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44266. __decorate([
  44267. BABYLON.serialize("disableLighting")
  44268. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44269. __decorate([
  44270. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44271. ], StandardMaterial.prototype, "disableLighting", void 0);
  44272. __decorate([
  44273. BABYLON.serialize("useObjectSpaceNormalMap")
  44274. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44275. __decorate([
  44276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44277. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44278. __decorate([
  44279. BABYLON.serialize("useParallax")
  44280. ], StandardMaterial.prototype, "_useParallax", void 0);
  44281. __decorate([
  44282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44283. ], StandardMaterial.prototype, "useParallax", void 0);
  44284. __decorate([
  44285. BABYLON.serialize("useParallaxOcclusion")
  44286. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44287. __decorate([
  44288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44289. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44290. __decorate([
  44291. BABYLON.serialize()
  44292. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44293. __decorate([
  44294. BABYLON.serialize("roughness")
  44295. ], StandardMaterial.prototype, "_roughness", void 0);
  44296. __decorate([
  44297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44298. ], StandardMaterial.prototype, "roughness", void 0);
  44299. __decorate([
  44300. BABYLON.serialize()
  44301. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44302. __decorate([
  44303. BABYLON.serialize()
  44304. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44305. __decorate([
  44306. BABYLON.serialize()
  44307. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44308. __decorate([
  44309. BABYLON.serialize("useLightmapAsShadowmap")
  44310. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44311. __decorate([
  44312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44313. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44314. __decorate([
  44315. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44316. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44317. __decorate([
  44318. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44319. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44320. __decorate([
  44321. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44322. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44323. __decorate([
  44324. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44325. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44326. __decorate([
  44327. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44328. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44329. __decorate([
  44330. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44331. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44332. __decorate([
  44333. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44334. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44335. __decorate([
  44336. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44337. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44338. __decorate([
  44339. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44340. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44341. __decorate([
  44342. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44343. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44344. __decorate([
  44345. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44346. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44347. __decorate([
  44348. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44349. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44350. __decorate([
  44351. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44352. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44353. __decorate([
  44354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44355. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44356. __decorate([
  44357. BABYLON.serialize("maxSimultaneousLights")
  44358. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44359. __decorate([
  44360. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44361. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44362. __decorate([
  44363. BABYLON.serialize("invertNormalMapX")
  44364. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44365. __decorate([
  44366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44367. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44368. __decorate([
  44369. BABYLON.serialize("invertNormalMapY")
  44370. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44371. __decorate([
  44372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44373. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44374. __decorate([
  44375. BABYLON.serialize("twoSidedLighting")
  44376. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44377. __decorate([
  44378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44379. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44380. __decorate([
  44381. BABYLON.serialize()
  44382. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44383. return StandardMaterial;
  44384. }(BABYLON.PushMaterial));
  44385. BABYLON.StandardMaterial = StandardMaterial;
  44386. })(BABYLON || (BABYLON = {}));
  44387. //# sourceMappingURL=babylon.standardMaterial.js.map
  44388. var BABYLON;
  44389. (function (BABYLON) {
  44390. /**
  44391. * Manages the defines for the PBR Material.
  44392. * @hiddenChildren
  44393. */
  44394. var PBRMaterialDefines = /** @class */ (function (_super) {
  44395. __extends(PBRMaterialDefines, _super);
  44396. /**
  44397. * Initializes the PBR Material defines.
  44398. */
  44399. function PBRMaterialDefines() {
  44400. var _this = _super.call(this) || this;
  44401. _this.PBR = true;
  44402. _this.MAINUV1 = false;
  44403. _this.MAINUV2 = false;
  44404. _this.UV1 = false;
  44405. _this.UV2 = false;
  44406. _this.ALBEDO = false;
  44407. _this.ALBEDODIRECTUV = 0;
  44408. _this.VERTEXCOLOR = false;
  44409. _this.AMBIENT = false;
  44410. _this.AMBIENTDIRECTUV = 0;
  44411. _this.AMBIENTINGRAYSCALE = false;
  44412. _this.OPACITY = false;
  44413. _this.VERTEXALPHA = false;
  44414. _this.OPACITYDIRECTUV = 0;
  44415. _this.OPACITYRGB = false;
  44416. _this.ALPHATEST = false;
  44417. _this.DEPTHPREPASS = false;
  44418. _this.ALPHABLEND = false;
  44419. _this.ALPHAFROMALBEDO = false;
  44420. _this.ALPHATESTVALUE = "0.5";
  44421. _this.SPECULAROVERALPHA = false;
  44422. _this.RADIANCEOVERALPHA = false;
  44423. _this.ALPHAFRESNEL = false;
  44424. _this.LINEARALPHAFRESNEL = false;
  44425. _this.PREMULTIPLYALPHA = false;
  44426. _this.EMISSIVE = false;
  44427. _this.EMISSIVEDIRECTUV = 0;
  44428. _this.REFLECTIVITY = false;
  44429. _this.REFLECTIVITYDIRECTUV = 0;
  44430. _this.SPECULARTERM = false;
  44431. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44432. _this.MICROSURFACEAUTOMATIC = false;
  44433. _this.LODBASEDMICROSFURACE = false;
  44434. _this.MICROSURFACEMAP = false;
  44435. _this.MICROSURFACEMAPDIRECTUV = 0;
  44436. _this.METALLICWORKFLOW = false;
  44437. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44438. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44439. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44440. _this.AOSTOREINMETALMAPRED = false;
  44441. _this.ENVIRONMENTBRDF = false;
  44442. _this.NORMAL = false;
  44443. _this.TANGENT = false;
  44444. _this.BUMP = false;
  44445. _this.BUMPDIRECTUV = 0;
  44446. _this.OBJECTSPACE_NORMALMAP = false;
  44447. _this.PARALLAX = false;
  44448. _this.PARALLAXOCCLUSION = false;
  44449. _this.NORMALXYSCALE = true;
  44450. _this.LIGHTMAP = false;
  44451. _this.LIGHTMAPDIRECTUV = 0;
  44452. _this.USELIGHTMAPASSHADOWMAP = false;
  44453. _this.GAMMALIGHTMAP = false;
  44454. _this.REFLECTION = false;
  44455. _this.REFLECTIONMAP_3D = false;
  44456. _this.REFLECTIONMAP_SPHERICAL = false;
  44457. _this.REFLECTIONMAP_PLANAR = false;
  44458. _this.REFLECTIONMAP_CUBIC = false;
  44459. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44460. _this.REFLECTIONMAP_PROJECTION = false;
  44461. _this.REFLECTIONMAP_SKYBOX = false;
  44462. _this.REFLECTIONMAP_EXPLICIT = false;
  44463. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44464. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44465. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44466. _this.INVERTCUBICMAP = false;
  44467. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44468. _this.USESPHERICALINVERTEX = false;
  44469. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44470. _this.LODINREFLECTIONALPHA = false;
  44471. _this.GAMMAREFLECTION = false;
  44472. _this.RADIANCEOCCLUSION = false;
  44473. _this.HORIZONOCCLUSION = false;
  44474. _this.REFRACTION = false;
  44475. _this.REFRACTIONMAP_3D = false;
  44476. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44477. _this.LODINREFRACTIONALPHA = false;
  44478. _this.GAMMAREFRACTION = false;
  44479. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44480. _this.INSTANCES = false;
  44481. _this.NUM_BONE_INFLUENCERS = 0;
  44482. _this.BonesPerMesh = 0;
  44483. _this.NONUNIFORMSCALING = false;
  44484. _this.MORPHTARGETS = false;
  44485. _this.MORPHTARGETS_NORMAL = false;
  44486. _this.MORPHTARGETS_TANGENT = false;
  44487. _this.NUM_MORPH_INFLUENCERS = 0;
  44488. _this.IMAGEPROCESSING = false;
  44489. _this.VIGNETTE = false;
  44490. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44491. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44492. _this.TONEMAPPING = false;
  44493. _this.CONTRAST = false;
  44494. _this.COLORCURVES = false;
  44495. _this.COLORGRADING = false;
  44496. _this.COLORGRADING3D = false;
  44497. _this.SAMPLER3DGREENDEPTH = false;
  44498. _this.SAMPLER3DBGRMAP = false;
  44499. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44500. _this.EXPOSURE = false;
  44501. _this.USEPHYSICALLIGHTFALLOFF = false;
  44502. _this.TWOSIDEDLIGHTING = false;
  44503. _this.SHADOWFLOAT = false;
  44504. _this.CLIPPLANE = false;
  44505. _this.POINTSIZE = false;
  44506. _this.FOG = false;
  44507. _this.LOGARITHMICDEPTH = false;
  44508. _this.FORCENORMALFORWARD = false;
  44509. _this.SPECULARAA = false;
  44510. _this.UNLIT = false;
  44511. _this.rebuild();
  44512. return _this;
  44513. }
  44514. /**
  44515. * Resets the PBR Material defines.
  44516. */
  44517. PBRMaterialDefines.prototype.reset = function () {
  44518. _super.prototype.reset.call(this);
  44519. this.ALPHATESTVALUE = "0.5";
  44520. this.PBR = true;
  44521. };
  44522. return PBRMaterialDefines;
  44523. }(BABYLON.MaterialDefines));
  44524. /**
  44525. * The Physically based material base class of BJS.
  44526. *
  44527. * This offers the main features of a standard PBR material.
  44528. * For more information, please refer to the documentation :
  44529. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44530. */
  44531. var PBRBaseMaterial = /** @class */ (function (_super) {
  44532. __extends(PBRBaseMaterial, _super);
  44533. /**
  44534. * Instantiates a new PBRMaterial instance.
  44535. *
  44536. * @param name The material name
  44537. * @param scene The scene the material will be use in.
  44538. */
  44539. function PBRBaseMaterial(name, scene) {
  44540. var _this = _super.call(this, name, scene) || this;
  44541. /**
  44542. * Intensity of the direct lights e.g. the four lights available in your scene.
  44543. * This impacts both the direct diffuse and specular highlights.
  44544. */
  44545. _this._directIntensity = 1.0;
  44546. /**
  44547. * Intensity of the emissive part of the material.
  44548. * This helps controlling the emissive effect without modifying the emissive color.
  44549. */
  44550. _this._emissiveIntensity = 1.0;
  44551. /**
  44552. * Intensity of the environment e.g. how much the environment will light the object
  44553. * either through harmonics for rough material or through the refelction for shiny ones.
  44554. */
  44555. _this._environmentIntensity = 1.0;
  44556. /**
  44557. * This is a special control allowing the reduction of the specular highlights coming from the
  44558. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44559. */
  44560. _this._specularIntensity = 1.0;
  44561. /**
  44562. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44563. */
  44564. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44565. /**
  44566. * Debug Control allowing disabling the bump map on this material.
  44567. */
  44568. _this._disableBumpMap = false;
  44569. /**
  44570. * AKA Occlusion Texture Intensity in other nomenclature.
  44571. */
  44572. _this._ambientTextureStrength = 1.0;
  44573. /**
  44574. * The color of a material in ambient lighting.
  44575. */
  44576. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44577. /**
  44578. * AKA Diffuse Color in other nomenclature.
  44579. */
  44580. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44581. /**
  44582. * AKA Specular Color in other nomenclature.
  44583. */
  44584. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44585. /**
  44586. * The color applied when light is reflected from a material.
  44587. */
  44588. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44589. /**
  44590. * The color applied when light is emitted from a material.
  44591. */
  44592. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44593. /**
  44594. * AKA Glossiness in other nomenclature.
  44595. */
  44596. _this._microSurface = 0.9;
  44597. /**
  44598. * source material index of refraction (IOR)' / 'destination material IOR.
  44599. */
  44600. _this._indexOfRefraction = 0.66;
  44601. /**
  44602. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44603. */
  44604. _this._invertRefractionY = false;
  44605. /**
  44606. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44607. * Materials half opaque for instance using refraction could benefit from this control.
  44608. */
  44609. _this._linkRefractionWithTransparency = false;
  44610. /**
  44611. * Specifies that the material will use the light map as a show map.
  44612. */
  44613. _this._useLightmapAsShadowmap = false;
  44614. /**
  44615. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44616. * makes the reflect vector face the model (under horizon).
  44617. */
  44618. _this._useHorizonOcclusion = true;
  44619. /**
  44620. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44621. * too much the area relying on ambient texture to define their ambient occlusion.
  44622. */
  44623. _this._useRadianceOcclusion = true;
  44624. /**
  44625. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44626. */
  44627. _this._useAlphaFromAlbedoTexture = false;
  44628. /**
  44629. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44630. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44631. */
  44632. _this._useSpecularOverAlpha = true;
  44633. /**
  44634. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44635. */
  44636. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44637. /**
  44638. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44639. */
  44640. _this._useRoughnessFromMetallicTextureAlpha = true;
  44641. /**
  44642. * Specifies if the metallic texture contains the roughness information in its green channel.
  44643. */
  44644. _this._useRoughnessFromMetallicTextureGreen = false;
  44645. /**
  44646. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44647. */
  44648. _this._useMetallnessFromMetallicTextureBlue = false;
  44649. /**
  44650. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44651. */
  44652. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44653. /**
  44654. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44655. */
  44656. _this._useAmbientInGrayScale = false;
  44657. /**
  44658. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44659. * The material will try to infer what glossiness each pixel should be.
  44660. */
  44661. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44662. /**
  44663. * BJS is using an harcoded light falloff based on a manually sets up range.
  44664. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44665. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44666. */
  44667. _this._usePhysicalLightFalloff = true;
  44668. /**
  44669. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44670. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44671. */
  44672. _this._useRadianceOverAlpha = true;
  44673. /**
  44674. * Allows using an object space normal map (instead of tangent space).
  44675. */
  44676. _this._useObjectSpaceNormalMap = false;
  44677. /**
  44678. * Allows using the bump map in parallax mode.
  44679. */
  44680. _this._useParallax = false;
  44681. /**
  44682. * Allows using the bump map in parallax occlusion mode.
  44683. */
  44684. _this._useParallaxOcclusion = false;
  44685. /**
  44686. * Controls the scale bias of the parallax mode.
  44687. */
  44688. _this._parallaxScaleBias = 0.05;
  44689. /**
  44690. * If sets to true, disables all the lights affecting the material.
  44691. */
  44692. _this._disableLighting = false;
  44693. /**
  44694. * Number of Simultaneous lights allowed on the material.
  44695. */
  44696. _this._maxSimultaneousLights = 4;
  44697. /**
  44698. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44699. */
  44700. _this._invertNormalMapX = false;
  44701. /**
  44702. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44703. */
  44704. _this._invertNormalMapY = false;
  44705. /**
  44706. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44707. */
  44708. _this._twoSidedLighting = false;
  44709. /**
  44710. * Defines the alpha limits in alpha test mode.
  44711. */
  44712. _this._alphaCutOff = 0.4;
  44713. /**
  44714. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44715. */
  44716. _this._forceAlphaTest = false;
  44717. /**
  44718. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44719. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44720. */
  44721. _this._useAlphaFresnel = false;
  44722. /**
  44723. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44724. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44725. */
  44726. _this._useLinearAlphaFresnel = false;
  44727. /**
  44728. * The transparency mode of the material.
  44729. */
  44730. _this._transparencyMode = null;
  44731. /**
  44732. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44733. * from cos thetav and roughness:
  44734. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44735. */
  44736. _this._environmentBRDFTexture = null;
  44737. /**
  44738. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44739. */
  44740. _this._forceIrradianceInFragment = false;
  44741. /**
  44742. * Force normal to face away from face.
  44743. */
  44744. _this._forceNormalForward = false;
  44745. /**
  44746. * Enables specular anti aliasing in the PBR shader.
  44747. * It will both interacts on the Geometry for analytical and IBL lighting.
  44748. * It also prefilter the roughness map based on the bump values.
  44749. */
  44750. _this._enableSpecularAntiAliasing = false;
  44751. /**
  44752. * Stores the available render targets.
  44753. */
  44754. _this._renderTargets = new BABYLON.SmartArray(16);
  44755. /**
  44756. * Sets the global ambient color for the material used in lighting calculations.
  44757. */
  44758. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44759. /**
  44760. * If set to true, no lighting calculations will be applied.
  44761. */
  44762. _this._unlit = false;
  44763. // Setup the default processing configuration to the scene.
  44764. _this._attachImageProcessingConfiguration(null);
  44765. _this.getRenderTargetTextures = function () {
  44766. _this._renderTargets.reset();
  44767. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44768. _this._renderTargets.push(_this._reflectionTexture);
  44769. }
  44770. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44771. _this._renderTargets.push(_this._refractionTexture);
  44772. }
  44773. return _this._renderTargets;
  44774. };
  44775. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44776. return _this;
  44777. }
  44778. /**
  44779. * Attaches a new image processing configuration to the PBR Material.
  44780. * @param configuration
  44781. */
  44782. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44783. var _this = this;
  44784. if (configuration === this._imageProcessingConfiguration) {
  44785. return;
  44786. }
  44787. // Detaches observer.
  44788. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44789. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44790. }
  44791. // Pick the scene configuration if needed.
  44792. if (!configuration) {
  44793. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44794. }
  44795. else {
  44796. this._imageProcessingConfiguration = configuration;
  44797. }
  44798. // Attaches observer.
  44799. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44800. _this._markAllSubMeshesAsImageProcessingDirty();
  44801. });
  44802. };
  44803. /**
  44804. * Gets the name of the material class.
  44805. */
  44806. PBRBaseMaterial.prototype.getClassName = function () {
  44807. return "PBRBaseMaterial";
  44808. };
  44809. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44810. /**
  44811. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44812. */
  44813. get: function () {
  44814. return this._useLogarithmicDepth;
  44815. },
  44816. /**
  44817. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44818. */
  44819. set: function (value) {
  44820. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44821. },
  44822. enumerable: true,
  44823. configurable: true
  44824. });
  44825. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44826. /**
  44827. * Gets the current transparency mode.
  44828. */
  44829. get: function () {
  44830. return this._transparencyMode;
  44831. },
  44832. /**
  44833. * Sets the transparency mode of the material.
  44834. */
  44835. set: function (value) {
  44836. if (this._transparencyMode === value) {
  44837. return;
  44838. }
  44839. this._transparencyMode = value;
  44840. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44841. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44842. },
  44843. enumerable: true,
  44844. configurable: true
  44845. });
  44846. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44847. /**
  44848. * Returns true if alpha blending should be disabled.
  44849. */
  44850. get: function () {
  44851. return (this._linkRefractionWithTransparency ||
  44852. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44853. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44854. },
  44855. enumerable: true,
  44856. configurable: true
  44857. });
  44858. /**
  44859. * Specifies whether or not this material should be rendered in alpha blend mode.
  44860. */
  44861. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44862. if (this._disableAlphaBlending) {
  44863. return false;
  44864. }
  44865. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44866. };
  44867. /**
  44868. * Specifies if the mesh will require alpha blending.
  44869. * @param mesh - BJS mesh.
  44870. */
  44871. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44872. if (this._disableAlphaBlending) {
  44873. return false;
  44874. }
  44875. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44876. };
  44877. /**
  44878. * Specifies whether or not this material should be rendered in alpha test mode.
  44879. */
  44880. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44881. if (this._forceAlphaTest) {
  44882. return true;
  44883. }
  44884. if (this._linkRefractionWithTransparency) {
  44885. return false;
  44886. }
  44887. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44888. };
  44889. /**
  44890. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44891. */
  44892. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44893. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44894. };
  44895. /**
  44896. * Gets the texture used for the alpha test.
  44897. */
  44898. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44899. return this._albedoTexture;
  44900. };
  44901. /**
  44902. * Specifies that the submesh is ready to be used.
  44903. * @param mesh - BJS mesh.
  44904. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44905. * @param useInstances - Specifies that instances should be used.
  44906. * @returns - boolean indicating that the submesh is ready or not.
  44907. */
  44908. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44909. if (subMesh.effect && this.isFrozen) {
  44910. if (this._wasPreviouslyReady) {
  44911. return true;
  44912. }
  44913. }
  44914. if (!subMesh._materialDefines) {
  44915. subMesh._materialDefines = new PBRMaterialDefines();
  44916. }
  44917. var defines = subMesh._materialDefines;
  44918. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44919. if (defines._renderId === this.getScene().getRenderId()) {
  44920. return true;
  44921. }
  44922. }
  44923. var scene = this.getScene();
  44924. var engine = scene.getEngine();
  44925. if (defines._areTexturesDirty) {
  44926. if (scene.texturesEnabled) {
  44927. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44928. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44929. return false;
  44930. }
  44931. }
  44932. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44933. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44934. return false;
  44935. }
  44936. }
  44937. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44938. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44939. return false;
  44940. }
  44941. }
  44942. var reflectionTexture = this._getReflectionTexture();
  44943. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44944. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44945. return false;
  44946. }
  44947. }
  44948. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44949. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44950. return false;
  44951. }
  44952. }
  44953. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44954. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44955. return false;
  44956. }
  44957. }
  44958. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44959. if (this._metallicTexture) {
  44960. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44961. return false;
  44962. }
  44963. }
  44964. else if (this._reflectivityTexture) {
  44965. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44966. return false;
  44967. }
  44968. }
  44969. if (this._microSurfaceTexture) {
  44970. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44971. return false;
  44972. }
  44973. }
  44974. }
  44975. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44976. // Bump texture cannot be not blocking.
  44977. if (!this._bumpTexture.isReady()) {
  44978. return false;
  44979. }
  44980. }
  44981. var refractionTexture = this._getRefractionTexture();
  44982. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44983. if (!refractionTexture.isReadyOrNotBlocking()) {
  44984. return false;
  44985. }
  44986. }
  44987. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44988. // This is blocking.
  44989. if (!this._environmentBRDFTexture.isReady()) {
  44990. return false;
  44991. }
  44992. }
  44993. }
  44994. }
  44995. if (defines._areImageProcessingDirty) {
  44996. if (!this._imageProcessingConfiguration.isReady()) {
  44997. return false;
  44998. }
  44999. }
  45000. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45001. mesh.createNormals(true);
  45002. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45003. }
  45004. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45005. if (effect) {
  45006. scene.resetCachedMaterial();
  45007. subMesh.setEffect(effect, defines);
  45008. this.buildUniformLayout();
  45009. }
  45010. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45011. return false;
  45012. }
  45013. defines._renderId = scene.getRenderId();
  45014. this._wasPreviouslyReady = true;
  45015. return true;
  45016. };
  45017. /**
  45018. * Specifies if the material uses metallic roughness workflow.
  45019. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45020. */
  45021. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45022. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45023. return true;
  45024. }
  45025. return false;
  45026. };
  45027. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45028. if (onCompiled === void 0) { onCompiled = null; }
  45029. if (onError === void 0) { onError = null; }
  45030. if (useInstances === void 0) { useInstances = null; }
  45031. if (useClipPlane === void 0) { useClipPlane = null; }
  45032. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45033. if (!defines.isDirty) {
  45034. return null;
  45035. }
  45036. defines.markAsProcessed();
  45037. var scene = this.getScene();
  45038. var engine = scene.getEngine();
  45039. // Fallbacks
  45040. var fallbacks = new BABYLON.EffectFallbacks();
  45041. var fallbackRank = 0;
  45042. if (defines.USESPHERICALINVERTEX) {
  45043. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45044. }
  45045. if (defines.FOG) {
  45046. fallbacks.addFallback(fallbackRank, "FOG");
  45047. }
  45048. if (defines.SPECULARAA) {
  45049. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45050. }
  45051. if (defines.POINTSIZE) {
  45052. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45053. }
  45054. if (defines.LOGARITHMICDEPTH) {
  45055. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45056. }
  45057. if (defines.PARALLAX) {
  45058. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45059. }
  45060. if (defines.PARALLAXOCCLUSION) {
  45061. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45062. }
  45063. if (defines.ENVIRONMENTBRDF) {
  45064. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45065. }
  45066. if (defines.TANGENT) {
  45067. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45068. }
  45069. if (defines.BUMP) {
  45070. fallbacks.addFallback(fallbackRank++, "BUMP");
  45071. }
  45072. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45073. if (defines.SPECULARTERM) {
  45074. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45075. }
  45076. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45077. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45078. }
  45079. if (defines.LIGHTMAP) {
  45080. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45081. }
  45082. if (defines.NORMAL) {
  45083. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45084. }
  45085. if (defines.AMBIENT) {
  45086. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45087. }
  45088. if (defines.EMISSIVE) {
  45089. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45090. }
  45091. if (defines.VERTEXCOLOR) {
  45092. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45093. }
  45094. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45095. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45096. }
  45097. if (defines.MORPHTARGETS) {
  45098. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45099. }
  45100. //Attributes
  45101. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45102. if (defines.NORMAL) {
  45103. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45104. }
  45105. if (defines.TANGENT) {
  45106. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45107. }
  45108. if (defines.UV1) {
  45109. attribs.push(BABYLON.VertexBuffer.UVKind);
  45110. }
  45111. if (defines.UV2) {
  45112. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45113. }
  45114. if (defines.VERTEXCOLOR) {
  45115. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45116. }
  45117. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45118. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45119. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45120. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45121. "vFogInfos", "vFogColor", "pointSize",
  45122. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45123. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45124. "mBones",
  45125. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45126. "vLightingIntensity",
  45127. "logarithmicDepthConstant",
  45128. "vSphericalX", "vSphericalY", "vSphericalZ",
  45129. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45130. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45131. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45132. "vTangentSpaceParams"
  45133. ];
  45134. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45135. "bumpSampler", "lightmapSampler", "opacitySampler",
  45136. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45137. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45138. "microSurfaceSampler", "environmentBrdfSampler"];
  45139. var uniformBuffers = ["Material", "Scene"];
  45140. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45141. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45142. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45143. uniformsNames: uniforms,
  45144. uniformBuffersNames: uniformBuffers,
  45145. samplers: samplers,
  45146. defines: defines,
  45147. maxSimultaneousLights: this._maxSimultaneousLights
  45148. });
  45149. var join = defines.toString();
  45150. return engine.createEffect("pbr", {
  45151. attributes: attribs,
  45152. uniformsNames: uniforms,
  45153. uniformBuffersNames: uniformBuffers,
  45154. samplers: samplers,
  45155. defines: join,
  45156. fallbacks: fallbacks,
  45157. onCompiled: onCompiled,
  45158. onError: onError,
  45159. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45160. }, engine);
  45161. };
  45162. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45163. if (useInstances === void 0) { useInstances = null; }
  45164. if (useClipPlane === void 0) { useClipPlane = null; }
  45165. var scene = this.getScene();
  45166. var engine = scene.getEngine();
  45167. // Lights
  45168. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45169. defines._needNormals = true;
  45170. // Textures
  45171. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45172. if (defines._areTexturesDirty) {
  45173. defines._needUVs = false;
  45174. if (scene.texturesEnabled) {
  45175. if (scene.getEngine().getCaps().textureLOD) {
  45176. defines.LODBASEDMICROSFURACE = true;
  45177. }
  45178. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45179. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45180. }
  45181. else {
  45182. defines.ALBEDO = false;
  45183. }
  45184. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45185. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45186. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45187. }
  45188. else {
  45189. defines.AMBIENT = false;
  45190. }
  45191. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45192. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45193. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45194. }
  45195. else {
  45196. defines.OPACITY = false;
  45197. }
  45198. var reflectionTexture = this._getReflectionTexture();
  45199. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45200. defines.REFLECTION = true;
  45201. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45202. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45203. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45204. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45205. defines.INVERTCUBICMAP = true;
  45206. }
  45207. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45208. switch (reflectionTexture.coordinatesMode) {
  45209. case BABYLON.Texture.EXPLICIT_MODE:
  45210. defines.REFLECTIONMAP_EXPLICIT = true;
  45211. break;
  45212. case BABYLON.Texture.PLANAR_MODE:
  45213. defines.REFLECTIONMAP_PLANAR = true;
  45214. break;
  45215. case BABYLON.Texture.PROJECTION_MODE:
  45216. defines.REFLECTIONMAP_PROJECTION = true;
  45217. break;
  45218. case BABYLON.Texture.SKYBOX_MODE:
  45219. defines.REFLECTIONMAP_SKYBOX = true;
  45220. break;
  45221. case BABYLON.Texture.SPHERICAL_MODE:
  45222. defines.REFLECTIONMAP_SPHERICAL = true;
  45223. break;
  45224. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45225. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45226. break;
  45227. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45228. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45229. break;
  45230. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45231. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45232. break;
  45233. case BABYLON.Texture.CUBIC_MODE:
  45234. case BABYLON.Texture.INVCUBIC_MODE:
  45235. default:
  45236. defines.REFLECTIONMAP_CUBIC = true;
  45237. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45238. break;
  45239. }
  45240. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45241. if (reflectionTexture.sphericalPolynomial) {
  45242. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45243. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45244. defines.USESPHERICALINVERTEX = false;
  45245. }
  45246. else {
  45247. defines.USESPHERICALINVERTEX = true;
  45248. }
  45249. }
  45250. }
  45251. }
  45252. else {
  45253. defines.REFLECTION = false;
  45254. defines.REFLECTIONMAP_3D = false;
  45255. defines.REFLECTIONMAP_SPHERICAL = false;
  45256. defines.REFLECTIONMAP_PLANAR = false;
  45257. defines.REFLECTIONMAP_CUBIC = false;
  45258. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45259. defines.REFLECTIONMAP_PROJECTION = false;
  45260. defines.REFLECTIONMAP_SKYBOX = false;
  45261. defines.REFLECTIONMAP_EXPLICIT = false;
  45262. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45263. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45264. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45265. defines.INVERTCUBICMAP = false;
  45266. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45267. defines.USESPHERICALINVERTEX = false;
  45268. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45269. defines.LODINREFLECTIONALPHA = false;
  45270. defines.GAMMAREFLECTION = false;
  45271. }
  45272. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45273. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45274. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45275. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45276. }
  45277. else {
  45278. defines.LIGHTMAP = false;
  45279. }
  45280. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45281. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45282. }
  45283. else {
  45284. defines.EMISSIVE = false;
  45285. }
  45286. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45287. if (this._metallicTexture) {
  45288. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45289. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45290. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45291. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45292. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45293. }
  45294. else if (this._reflectivityTexture) {
  45295. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45296. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45297. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45298. }
  45299. else {
  45300. defines.REFLECTIVITY = false;
  45301. }
  45302. if (this._microSurfaceTexture) {
  45303. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45304. }
  45305. else {
  45306. defines.MICROSURFACEMAP = false;
  45307. }
  45308. }
  45309. else {
  45310. defines.REFLECTIVITY = false;
  45311. defines.MICROSURFACEMAP = false;
  45312. }
  45313. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45314. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45315. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45316. defines.PARALLAX = true;
  45317. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45318. }
  45319. else {
  45320. defines.PARALLAX = false;
  45321. }
  45322. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45323. }
  45324. else {
  45325. defines.BUMP = false;
  45326. }
  45327. var refractionTexture = this._getRefractionTexture();
  45328. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45329. defines.REFRACTION = true;
  45330. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45331. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45332. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45333. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45334. if (this._linkRefractionWithTransparency) {
  45335. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45336. }
  45337. }
  45338. else {
  45339. defines.REFRACTION = false;
  45340. }
  45341. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45342. defines.ENVIRONMENTBRDF = true;
  45343. }
  45344. else {
  45345. defines.ENVIRONMENTBRDF = false;
  45346. }
  45347. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45348. defines.ALPHAFROMALBEDO = true;
  45349. }
  45350. else {
  45351. defines.ALPHAFROMALBEDO = false;
  45352. }
  45353. }
  45354. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45355. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45356. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45357. if (!this.backFaceCulling && this._twoSidedLighting) {
  45358. defines.TWOSIDEDLIGHTING = true;
  45359. }
  45360. else {
  45361. defines.TWOSIDEDLIGHTING = false;
  45362. }
  45363. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45364. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45365. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45366. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45367. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45368. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45369. }
  45370. if (defines._areImageProcessingDirty) {
  45371. this._imageProcessingConfiguration.prepareDefines(defines);
  45372. }
  45373. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45374. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45375. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45376. // Misc.
  45377. if (defines._areMiscDirty) {
  45378. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45379. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45380. }
  45381. // Values that need to be evaluated on every frame
  45382. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45383. // Attribs
  45384. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45385. };
  45386. /**
  45387. * Force shader compilation
  45388. */
  45389. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45390. var _this = this;
  45391. var localOptions = __assign({ clipPlane: false }, options);
  45392. var defines = new PBRMaterialDefines();
  45393. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45394. if (effect.isReady()) {
  45395. if (onCompiled) {
  45396. onCompiled(this);
  45397. }
  45398. }
  45399. else {
  45400. effect.onCompileObservable.add(function () {
  45401. if (onCompiled) {
  45402. onCompiled(_this);
  45403. }
  45404. });
  45405. }
  45406. };
  45407. /**
  45408. * Initializes the uniform buffer layout for the shader.
  45409. */
  45410. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45411. // Order is important !
  45412. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45413. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45414. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45415. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45416. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45417. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45418. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45419. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45420. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45421. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45422. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45423. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45424. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45425. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45426. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45427. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45428. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45429. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45430. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45431. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45432. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45433. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45434. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45435. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45436. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45437. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45438. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45439. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45440. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45441. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45442. this._uniformBuffer.addUniform("pointSize", 1);
  45443. this._uniformBuffer.create();
  45444. };
  45445. /**
  45446. * Unbinds the textures.
  45447. */
  45448. PBRBaseMaterial.prototype.unbind = function () {
  45449. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45450. this._uniformBuffer.setTexture("reflectionSampler", null);
  45451. }
  45452. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45453. this._uniformBuffer.setTexture("refractionSampler", null);
  45454. }
  45455. _super.prototype.unbind.call(this);
  45456. };
  45457. /**
  45458. * Binds the submesh data.
  45459. * @param world - The world matrix.
  45460. * @param mesh - The BJS mesh.
  45461. * @param subMesh - A submesh of the BJS mesh.
  45462. */
  45463. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45464. var scene = this.getScene();
  45465. var defines = subMesh._materialDefines;
  45466. if (!defines) {
  45467. return;
  45468. }
  45469. var effect = subMesh.effect;
  45470. if (!effect) {
  45471. return;
  45472. }
  45473. this._activeEffect = effect;
  45474. // Matrices
  45475. this.bindOnlyWorldMatrix(world);
  45476. // Normal Matrix
  45477. if (defines.OBJECTSPACE_NORMALMAP) {
  45478. world.toNormalMatrix(this._normalMatrix);
  45479. this.bindOnlyNormalMatrix(this._normalMatrix);
  45480. }
  45481. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45482. // Bones
  45483. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45484. var reflectionTexture = null;
  45485. if (mustRebind) {
  45486. this._uniformBuffer.bindToEffect(effect, "Material");
  45487. this.bindViewProjection(effect);
  45488. reflectionTexture = this._getReflectionTexture();
  45489. var refractionTexture = this._getRefractionTexture();
  45490. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45491. // Texture uniforms
  45492. if (scene.texturesEnabled) {
  45493. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45494. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45495. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45496. }
  45497. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45498. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45499. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45500. }
  45501. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45502. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45503. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45504. }
  45505. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45506. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45507. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45508. if (reflectionTexture.boundingBoxSize) {
  45509. var cubeTexture = reflectionTexture;
  45510. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45511. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45512. }
  45513. var polynomials = reflectionTexture.sphericalPolynomial;
  45514. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45515. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45516. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45517. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45518. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45519. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45520. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45521. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45522. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45523. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45524. }
  45525. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45526. }
  45527. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45528. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45529. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45530. }
  45531. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45532. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45533. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45534. }
  45535. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45536. if (this._metallicTexture) {
  45537. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45538. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45539. }
  45540. else if (this._reflectivityTexture) {
  45541. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45542. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45543. }
  45544. if (this._microSurfaceTexture) {
  45545. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45546. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45547. }
  45548. }
  45549. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45550. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45551. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45552. if (scene._mirroredCameraPosition) {
  45553. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45554. }
  45555. else {
  45556. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45557. }
  45558. }
  45559. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45560. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45561. var depth = 1.0;
  45562. if (!refractionTexture.isCube) {
  45563. if (refractionTexture.depth) {
  45564. depth = refractionTexture.depth;
  45565. }
  45566. }
  45567. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45568. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45569. }
  45570. }
  45571. // Point size
  45572. if (this.pointsCloud) {
  45573. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45574. }
  45575. // Colors
  45576. if (defines.METALLICWORKFLOW) {
  45577. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45578. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45579. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45580. }
  45581. else {
  45582. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45583. }
  45584. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45585. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45586. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45587. // Misc
  45588. this._lightingInfos.x = this._directIntensity;
  45589. this._lightingInfos.y = this._emissiveIntensity;
  45590. this._lightingInfos.z = this._environmentIntensity;
  45591. this._lightingInfos.w = this._specularIntensity;
  45592. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45593. }
  45594. // Textures
  45595. if (scene.texturesEnabled) {
  45596. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45597. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45598. }
  45599. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45600. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45601. }
  45602. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45603. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45604. }
  45605. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45606. if (defines.LODBASEDMICROSFURACE) {
  45607. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45608. }
  45609. else {
  45610. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45611. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45612. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45613. }
  45614. }
  45615. if (defines.ENVIRONMENTBRDF) {
  45616. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45617. }
  45618. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45619. if (defines.LODBASEDMICROSFURACE) {
  45620. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45621. }
  45622. else {
  45623. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45624. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45625. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45626. }
  45627. }
  45628. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45629. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45630. }
  45631. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45632. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45633. }
  45634. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45635. if (this._metallicTexture) {
  45636. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45637. }
  45638. else if (this._reflectivityTexture) {
  45639. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45640. }
  45641. if (this._microSurfaceTexture) {
  45642. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45643. }
  45644. }
  45645. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45646. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45647. }
  45648. }
  45649. // Clip plane
  45650. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45651. // Colors
  45652. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45653. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45654. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45655. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45656. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45657. }
  45658. if (mustRebind || !this.isFrozen) {
  45659. // Lights
  45660. if (scene.lightsEnabled && !this._disableLighting) {
  45661. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45662. }
  45663. // View
  45664. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45665. this.bindView(effect);
  45666. }
  45667. // Fog
  45668. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45669. // Morph targets
  45670. if (defines.NUM_MORPH_INFLUENCERS) {
  45671. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45672. }
  45673. // image processing
  45674. this._imageProcessingConfiguration.bind(this._activeEffect);
  45675. // Log. depth
  45676. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45677. }
  45678. this._uniformBuffer.update();
  45679. this._afterBind(mesh, this._activeEffect);
  45680. };
  45681. /**
  45682. * Returns the animatable textures.
  45683. * @returns - Array of animatable textures.
  45684. */
  45685. PBRBaseMaterial.prototype.getAnimatables = function () {
  45686. var results = [];
  45687. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45688. results.push(this._albedoTexture);
  45689. }
  45690. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45691. results.push(this._ambientTexture);
  45692. }
  45693. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45694. results.push(this._opacityTexture);
  45695. }
  45696. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45697. results.push(this._reflectionTexture);
  45698. }
  45699. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45700. results.push(this._emissiveTexture);
  45701. }
  45702. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45703. results.push(this._metallicTexture);
  45704. }
  45705. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45706. results.push(this._reflectivityTexture);
  45707. }
  45708. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45709. results.push(this._bumpTexture);
  45710. }
  45711. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45712. results.push(this._lightmapTexture);
  45713. }
  45714. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45715. results.push(this._refractionTexture);
  45716. }
  45717. return results;
  45718. };
  45719. /**
  45720. * Returns the texture used for reflections.
  45721. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45722. */
  45723. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45724. if (this._reflectionTexture) {
  45725. return this._reflectionTexture;
  45726. }
  45727. return this.getScene().environmentTexture;
  45728. };
  45729. /**
  45730. * Returns the texture used for refraction or null if none is used.
  45731. * @returns - Refection texture if present. If no refraction texture and refraction
  45732. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45733. */
  45734. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45735. if (this._refractionTexture) {
  45736. return this._refractionTexture;
  45737. }
  45738. if (this._linkRefractionWithTransparency) {
  45739. return this.getScene().environmentTexture;
  45740. }
  45741. return null;
  45742. };
  45743. /**
  45744. * Disposes the resources of the material.
  45745. * @param forceDisposeEffect - Forces the disposal of effects.
  45746. * @param forceDisposeTextures - Forces the disposal of all textures.
  45747. */
  45748. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45749. if (forceDisposeTextures) {
  45750. if (this._albedoTexture) {
  45751. this._albedoTexture.dispose();
  45752. }
  45753. if (this._ambientTexture) {
  45754. this._ambientTexture.dispose();
  45755. }
  45756. if (this._opacityTexture) {
  45757. this._opacityTexture.dispose();
  45758. }
  45759. if (this._reflectionTexture) {
  45760. this._reflectionTexture.dispose();
  45761. }
  45762. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45763. this._environmentBRDFTexture.dispose();
  45764. }
  45765. if (this._emissiveTexture) {
  45766. this._emissiveTexture.dispose();
  45767. }
  45768. if (this._metallicTexture) {
  45769. this._metallicTexture.dispose();
  45770. }
  45771. if (this._reflectivityTexture) {
  45772. this._reflectivityTexture.dispose();
  45773. }
  45774. if (this._bumpTexture) {
  45775. this._bumpTexture.dispose();
  45776. }
  45777. if (this._lightmapTexture) {
  45778. this._lightmapTexture.dispose();
  45779. }
  45780. if (this._refractionTexture) {
  45781. this._refractionTexture.dispose();
  45782. }
  45783. }
  45784. this._renderTargets.dispose();
  45785. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45786. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45787. }
  45788. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45789. };
  45790. /**
  45791. * Stores the reflectivity values based on metallic roughness workflow.
  45792. */
  45793. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45794. __decorate([
  45795. BABYLON.serializeAsImageProcessingConfiguration()
  45796. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45797. __decorate([
  45798. BABYLON.serialize()
  45799. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45800. __decorate([
  45801. BABYLON.serialize()
  45802. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45803. return PBRBaseMaterial;
  45804. }(BABYLON.PushMaterial));
  45805. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45806. })(BABYLON || (BABYLON = {}));
  45807. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45808. var BABYLON;
  45809. (function (BABYLON) {
  45810. /**
  45811. * The Physically based simple base material of BJS.
  45812. *
  45813. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45814. * It is used as the base class for both the specGloss and metalRough conventions.
  45815. */
  45816. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45817. __extends(PBRBaseSimpleMaterial, _super);
  45818. /**
  45819. * Instantiates a new PBRMaterial instance.
  45820. *
  45821. * @param name The material name
  45822. * @param scene The scene the material will be use in.
  45823. */
  45824. function PBRBaseSimpleMaterial(name, scene) {
  45825. var _this = _super.call(this, name, scene) || this;
  45826. /**
  45827. * Number of Simultaneous lights allowed on the material.
  45828. */
  45829. _this.maxSimultaneousLights = 4;
  45830. /**
  45831. * If sets to true, disables all the lights affecting the material.
  45832. */
  45833. _this.disableLighting = false;
  45834. /**
  45835. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45836. */
  45837. _this.invertNormalMapX = false;
  45838. /**
  45839. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45840. */
  45841. _this.invertNormalMapY = false;
  45842. /**
  45843. * Emissivie color used to self-illuminate the model.
  45844. */
  45845. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45846. /**
  45847. * Occlusion Channel Strenght.
  45848. */
  45849. _this.occlusionStrength = 1.0;
  45850. _this.useLightmapAsShadowmap = false;
  45851. _this._useAlphaFromAlbedoTexture = true;
  45852. _this._useAmbientInGrayScale = true;
  45853. return _this;
  45854. }
  45855. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45856. /**
  45857. * Gets the current double sided mode.
  45858. */
  45859. get: function () {
  45860. return this._twoSidedLighting;
  45861. },
  45862. /**
  45863. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45864. */
  45865. set: function (value) {
  45866. if (this._twoSidedLighting === value) {
  45867. return;
  45868. }
  45869. this._twoSidedLighting = value;
  45870. this.backFaceCulling = !value;
  45871. this._markAllSubMeshesAsTexturesDirty();
  45872. },
  45873. enumerable: true,
  45874. configurable: true
  45875. });
  45876. /**
  45877. * Return the active textures of the material.
  45878. */
  45879. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45880. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45881. if (this.environmentTexture) {
  45882. activeTextures.push(this.environmentTexture);
  45883. }
  45884. if (this.normalTexture) {
  45885. activeTextures.push(this.normalTexture);
  45886. }
  45887. if (this.emissiveTexture) {
  45888. activeTextures.push(this.emissiveTexture);
  45889. }
  45890. if (this.occlusionTexture) {
  45891. activeTextures.push(this.occlusionTexture);
  45892. }
  45893. if (this.lightmapTexture) {
  45894. activeTextures.push(this.lightmapTexture);
  45895. }
  45896. return activeTextures;
  45897. };
  45898. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45899. if (_super.prototype.hasTexture.call(this, texture)) {
  45900. return true;
  45901. }
  45902. if (this.lightmapTexture === texture) {
  45903. return true;
  45904. }
  45905. return false;
  45906. };
  45907. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45908. return "PBRBaseSimpleMaterial";
  45909. };
  45910. __decorate([
  45911. BABYLON.serialize(),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45913. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45914. __decorate([
  45915. BABYLON.serialize(),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45917. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45918. __decorate([
  45919. BABYLON.serializeAsTexture(),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45921. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45922. __decorate([
  45923. BABYLON.serialize(),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45925. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45926. __decorate([
  45927. BABYLON.serialize(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45929. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45930. __decorate([
  45931. BABYLON.serializeAsTexture(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45933. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45934. __decorate([
  45935. BABYLON.serializeAsColor3("emissive"),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45937. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45938. __decorate([
  45939. BABYLON.serializeAsTexture(),
  45940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45941. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45942. __decorate([
  45943. BABYLON.serialize(),
  45944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45945. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45946. __decorate([
  45947. BABYLON.serializeAsTexture(),
  45948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45949. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45950. __decorate([
  45951. BABYLON.serialize(),
  45952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45953. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45954. __decorate([
  45955. BABYLON.serialize()
  45956. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45957. __decorate([
  45958. BABYLON.serializeAsTexture(),
  45959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45960. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45961. __decorate([
  45962. BABYLON.serialize(),
  45963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45964. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45965. return PBRBaseSimpleMaterial;
  45966. }(BABYLON.PBRBaseMaterial));
  45967. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45968. })(BABYLON || (BABYLON = {}));
  45969. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45970. var BABYLON;
  45971. (function (BABYLON) {
  45972. /**
  45973. * The Physically based material of BJS.
  45974. *
  45975. * This offers the main features of a standard PBR material.
  45976. * For more information, please refer to the documentation :
  45977. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45978. */
  45979. var PBRMaterial = /** @class */ (function (_super) {
  45980. __extends(PBRMaterial, _super);
  45981. /**
  45982. * Instantiates a new PBRMaterial instance.
  45983. *
  45984. * @param name The material name
  45985. * @param scene The scene the material will be use in.
  45986. */
  45987. function PBRMaterial(name, scene) {
  45988. var _this = _super.call(this, name, scene) || this;
  45989. /**
  45990. * Intensity of the direct lights e.g. the four lights available in your scene.
  45991. * This impacts both the direct diffuse and specular highlights.
  45992. */
  45993. _this.directIntensity = 1.0;
  45994. /**
  45995. * Intensity of the emissive part of the material.
  45996. * This helps controlling the emissive effect without modifying the emissive color.
  45997. */
  45998. _this.emissiveIntensity = 1.0;
  45999. /**
  46000. * Intensity of the environment e.g. how much the environment will light the object
  46001. * either through harmonics for rough material or through the refelction for shiny ones.
  46002. */
  46003. _this.environmentIntensity = 1.0;
  46004. /**
  46005. * This is a special control allowing the reduction of the specular highlights coming from the
  46006. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46007. */
  46008. _this.specularIntensity = 1.0;
  46009. /**
  46010. * Debug Control allowing disabling the bump map on this material.
  46011. */
  46012. _this.disableBumpMap = false;
  46013. /**
  46014. * AKA Occlusion Texture Intensity in other nomenclature.
  46015. */
  46016. _this.ambientTextureStrength = 1.0;
  46017. /**
  46018. * The color of a material in ambient lighting.
  46019. */
  46020. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46021. /**
  46022. * AKA Diffuse Color in other nomenclature.
  46023. */
  46024. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46025. /**
  46026. * AKA Specular Color in other nomenclature.
  46027. */
  46028. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46029. /**
  46030. * The color reflected from the material.
  46031. */
  46032. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46033. /**
  46034. * The color emitted from the material.
  46035. */
  46036. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46037. /**
  46038. * AKA Glossiness in other nomenclature.
  46039. */
  46040. _this.microSurface = 1.0;
  46041. /**
  46042. * source material index of refraction (IOR)' / 'destination material IOR.
  46043. */
  46044. _this.indexOfRefraction = 0.66;
  46045. /**
  46046. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46047. */
  46048. _this.invertRefractionY = false;
  46049. /**
  46050. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46051. * Materials half opaque for instance using refraction could benefit from this control.
  46052. */
  46053. _this.linkRefractionWithTransparency = false;
  46054. _this.useLightmapAsShadowmap = false;
  46055. /**
  46056. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46057. */
  46058. _this.useAlphaFromAlbedoTexture = false;
  46059. /**
  46060. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46061. */
  46062. _this.forceAlphaTest = false;
  46063. /**
  46064. * Defines the alpha limits in alpha test mode.
  46065. */
  46066. _this.alphaCutOff = 0.4;
  46067. /**
  46068. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46069. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46070. */
  46071. _this.useSpecularOverAlpha = true;
  46072. /**
  46073. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46074. */
  46075. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46076. /**
  46077. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46078. */
  46079. _this.useRoughnessFromMetallicTextureAlpha = true;
  46080. /**
  46081. * Specifies if the metallic texture contains the roughness information in its green channel.
  46082. */
  46083. _this.useRoughnessFromMetallicTextureGreen = false;
  46084. /**
  46085. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46086. */
  46087. _this.useMetallnessFromMetallicTextureBlue = false;
  46088. /**
  46089. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46090. */
  46091. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46092. /**
  46093. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46094. */
  46095. _this.useAmbientInGrayScale = false;
  46096. /**
  46097. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46098. * The material will try to infer what glossiness each pixel should be.
  46099. */
  46100. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46101. /**
  46102. * BJS is using an harcoded light falloff based on a manually sets up range.
  46103. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46104. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46105. */
  46106. _this.usePhysicalLightFalloff = true;
  46107. /**
  46108. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46109. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46110. */
  46111. _this.useRadianceOverAlpha = true;
  46112. /**
  46113. * Allows using an object space normal map (instead of tangent space).
  46114. */
  46115. _this.useObjectSpaceNormalMap = false;
  46116. /**
  46117. * Allows using the bump map in parallax mode.
  46118. */
  46119. _this.useParallax = false;
  46120. /**
  46121. * Allows using the bump map in parallax occlusion mode.
  46122. */
  46123. _this.useParallaxOcclusion = false;
  46124. /**
  46125. * Controls the scale bias of the parallax mode.
  46126. */
  46127. _this.parallaxScaleBias = 0.05;
  46128. /**
  46129. * If sets to true, disables all the lights affecting the material.
  46130. */
  46131. _this.disableLighting = false;
  46132. /**
  46133. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46134. */
  46135. _this.forceIrradianceInFragment = false;
  46136. /**
  46137. * Number of Simultaneous lights allowed on the material.
  46138. */
  46139. _this.maxSimultaneousLights = 4;
  46140. /**
  46141. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46142. */
  46143. _this.invertNormalMapX = false;
  46144. /**
  46145. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46146. */
  46147. _this.invertNormalMapY = false;
  46148. /**
  46149. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46150. */
  46151. _this.twoSidedLighting = false;
  46152. /**
  46153. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46154. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46155. */
  46156. _this.useAlphaFresnel = false;
  46157. /**
  46158. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46159. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46160. */
  46161. _this.useLinearAlphaFresnel = false;
  46162. /**
  46163. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46164. * And/Or occlude the blended part.
  46165. */
  46166. _this.environmentBRDFTexture = null;
  46167. /**
  46168. * Force normal to face away from face.
  46169. */
  46170. _this.forceNormalForward = false;
  46171. /**
  46172. * Enables specular anti aliasing in the PBR shader.
  46173. * It will both interacts on the Geometry for analytical and IBL lighting.
  46174. * It also prefilter the roughness map based on the bump values.
  46175. */
  46176. _this.enableSpecularAntiAliasing = false;
  46177. /**
  46178. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46179. * makes the reflect vector face the model (under horizon).
  46180. */
  46181. _this.useHorizonOcclusion = true;
  46182. /**
  46183. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46184. * too much the area relying on ambient texture to define their ambient occlusion.
  46185. */
  46186. _this.useRadianceOcclusion = true;
  46187. /**
  46188. * If set to true, no lighting calculations will be applied.
  46189. */
  46190. _this.unlit = false;
  46191. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46192. return _this;
  46193. }
  46194. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46195. /**
  46196. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46197. */
  46198. get: function () {
  46199. return this._PBRMATERIAL_OPAQUE;
  46200. },
  46201. enumerable: true,
  46202. configurable: true
  46203. });
  46204. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46205. /**
  46206. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46207. */
  46208. get: function () {
  46209. return this._PBRMATERIAL_ALPHATEST;
  46210. },
  46211. enumerable: true,
  46212. configurable: true
  46213. });
  46214. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46215. /**
  46216. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46217. */
  46218. get: function () {
  46219. return this._PBRMATERIAL_ALPHABLEND;
  46220. },
  46221. enumerable: true,
  46222. configurable: true
  46223. });
  46224. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46225. /**
  46226. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46227. * They are also discarded below the alpha cutoff threshold to improve performances.
  46228. */
  46229. get: function () {
  46230. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46231. },
  46232. enumerable: true,
  46233. configurable: true
  46234. });
  46235. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46236. /**
  46237. * Gets the image processing configuration used either in this material.
  46238. */
  46239. get: function () {
  46240. return this._imageProcessingConfiguration;
  46241. },
  46242. /**
  46243. * Sets the Default image processing configuration used either in the this material.
  46244. *
  46245. * If sets to null, the scene one is in use.
  46246. */
  46247. set: function (value) {
  46248. this._attachImageProcessingConfiguration(value);
  46249. // Ensure the effect will be rebuilt.
  46250. this._markAllSubMeshesAsTexturesDirty();
  46251. },
  46252. enumerable: true,
  46253. configurable: true
  46254. });
  46255. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46256. /**
  46257. * Gets wether the color curves effect is enabled.
  46258. */
  46259. get: function () {
  46260. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46261. },
  46262. /**
  46263. * Sets wether the color curves effect is enabled.
  46264. */
  46265. set: function (value) {
  46266. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46267. },
  46268. enumerable: true,
  46269. configurable: true
  46270. });
  46271. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46272. /**
  46273. * Gets wether the color grading effect is enabled.
  46274. */
  46275. get: function () {
  46276. return this.imageProcessingConfiguration.colorGradingEnabled;
  46277. },
  46278. /**
  46279. * Gets wether the color grading effect is enabled.
  46280. */
  46281. set: function (value) {
  46282. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46283. },
  46284. enumerable: true,
  46285. configurable: true
  46286. });
  46287. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46288. /**
  46289. * Gets wether tonemapping is enabled or not.
  46290. */
  46291. get: function () {
  46292. return this._imageProcessingConfiguration.toneMappingEnabled;
  46293. },
  46294. /**
  46295. * Sets wether tonemapping is enabled or not
  46296. */
  46297. set: function (value) {
  46298. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46299. },
  46300. enumerable: true,
  46301. configurable: true
  46302. });
  46303. ;
  46304. ;
  46305. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46306. /**
  46307. * The camera exposure used on this material.
  46308. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46309. * This corresponds to a photographic exposure.
  46310. */
  46311. get: function () {
  46312. return this._imageProcessingConfiguration.exposure;
  46313. },
  46314. /**
  46315. * The camera exposure used on this material.
  46316. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46317. * This corresponds to a photographic exposure.
  46318. */
  46319. set: function (value) {
  46320. this._imageProcessingConfiguration.exposure = value;
  46321. },
  46322. enumerable: true,
  46323. configurable: true
  46324. });
  46325. ;
  46326. ;
  46327. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46328. /**
  46329. * Gets The camera contrast used on this material.
  46330. */
  46331. get: function () {
  46332. return this._imageProcessingConfiguration.contrast;
  46333. },
  46334. /**
  46335. * Sets The camera contrast used on this material.
  46336. */
  46337. set: function (value) {
  46338. this._imageProcessingConfiguration.contrast = value;
  46339. },
  46340. enumerable: true,
  46341. configurable: true
  46342. });
  46343. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46344. /**
  46345. * Gets the Color Grading 2D Lookup Texture.
  46346. */
  46347. get: function () {
  46348. return this._imageProcessingConfiguration.colorGradingTexture;
  46349. },
  46350. /**
  46351. * Sets the Color Grading 2D Lookup Texture.
  46352. */
  46353. set: function (value) {
  46354. this._imageProcessingConfiguration.colorGradingTexture = value;
  46355. },
  46356. enumerable: true,
  46357. configurable: true
  46358. });
  46359. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46360. /**
  46361. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46362. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46363. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  46364. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46365. */
  46366. get: function () {
  46367. return this._imageProcessingConfiguration.colorCurves;
  46368. },
  46369. /**
  46370. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46371. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46372. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  46373. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46374. */
  46375. set: function (value) {
  46376. this._imageProcessingConfiguration.colorCurves = value;
  46377. },
  46378. enumerable: true,
  46379. configurable: true
  46380. });
  46381. /**
  46382. * Returns the name of this material class.
  46383. */
  46384. PBRMaterial.prototype.getClassName = function () {
  46385. return "PBRMaterial";
  46386. };
  46387. /**
  46388. * Returns an array of the actively used textures.
  46389. * @returns - Array of BaseTextures
  46390. */
  46391. PBRMaterial.prototype.getActiveTextures = function () {
  46392. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46393. if (this._albedoTexture) {
  46394. activeTextures.push(this._albedoTexture);
  46395. }
  46396. if (this._ambientTexture) {
  46397. activeTextures.push(this._ambientTexture);
  46398. }
  46399. if (this._opacityTexture) {
  46400. activeTextures.push(this._opacityTexture);
  46401. }
  46402. if (this._reflectionTexture) {
  46403. activeTextures.push(this._reflectionTexture);
  46404. }
  46405. if (this._emissiveTexture) {
  46406. activeTextures.push(this._emissiveTexture);
  46407. }
  46408. if (this._reflectivityTexture) {
  46409. activeTextures.push(this._reflectivityTexture);
  46410. }
  46411. if (this._metallicTexture) {
  46412. activeTextures.push(this._metallicTexture);
  46413. }
  46414. if (this._microSurfaceTexture) {
  46415. activeTextures.push(this._microSurfaceTexture);
  46416. }
  46417. if (this._bumpTexture) {
  46418. activeTextures.push(this._bumpTexture);
  46419. }
  46420. if (this._lightmapTexture) {
  46421. activeTextures.push(this._lightmapTexture);
  46422. }
  46423. if (this._refractionTexture) {
  46424. activeTextures.push(this._refractionTexture);
  46425. }
  46426. return activeTextures;
  46427. };
  46428. /**
  46429. * Checks to see if a texture is used in the material.
  46430. * @param texture - Base texture to use.
  46431. * @returns - Boolean specifying if a texture is used in the material.
  46432. */
  46433. PBRMaterial.prototype.hasTexture = function (texture) {
  46434. if (_super.prototype.hasTexture.call(this, texture)) {
  46435. return true;
  46436. }
  46437. if (this._albedoTexture === texture) {
  46438. return true;
  46439. }
  46440. if (this._ambientTexture === texture) {
  46441. return true;
  46442. }
  46443. if (this._opacityTexture === texture) {
  46444. return true;
  46445. }
  46446. if (this._reflectionTexture === texture) {
  46447. return true;
  46448. }
  46449. if (this._reflectivityTexture === texture) {
  46450. return true;
  46451. }
  46452. if (this._metallicTexture === texture) {
  46453. return true;
  46454. }
  46455. if (this._microSurfaceTexture === texture) {
  46456. return true;
  46457. }
  46458. if (this._bumpTexture === texture) {
  46459. return true;
  46460. }
  46461. if (this._lightmapTexture === texture) {
  46462. return true;
  46463. }
  46464. if (this._refractionTexture === texture) {
  46465. return true;
  46466. }
  46467. return false;
  46468. };
  46469. /**
  46470. * Makes a duplicate of the current material.
  46471. * @param name - name to use for the new material.
  46472. */
  46473. PBRMaterial.prototype.clone = function (name) {
  46474. var _this = this;
  46475. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46476. clone.id = name;
  46477. clone.name = name;
  46478. return clone;
  46479. };
  46480. /**
  46481. * Serializes this PBR Material.
  46482. * @returns - An object with the serialized material.
  46483. */
  46484. PBRMaterial.prototype.serialize = function () {
  46485. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46486. serializationObject.customType = "BABYLON.PBRMaterial";
  46487. return serializationObject;
  46488. };
  46489. // Statics
  46490. /**
  46491. * Parses a PBR Material from a serialized object.
  46492. * @param source - Serialized object.
  46493. * @param scene - BJS scene instance.
  46494. * @param rootUrl - url for the scene object
  46495. * @returns - PBRMaterial
  46496. */
  46497. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46498. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46499. };
  46500. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46501. /**
  46502. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46503. */
  46504. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46505. /**
  46506. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46507. */
  46508. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46509. /**
  46510. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46511. * They are also discarded below the alpha cutoff threshold to improve performances.
  46512. */
  46513. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46514. __decorate([
  46515. BABYLON.serialize(),
  46516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46517. ], PBRMaterial.prototype, "directIntensity", void 0);
  46518. __decorate([
  46519. BABYLON.serialize(),
  46520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46521. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46522. __decorate([
  46523. BABYLON.serialize(),
  46524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46525. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46526. __decorate([
  46527. BABYLON.serialize(),
  46528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46529. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46530. __decorate([
  46531. BABYLON.serialize(),
  46532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46533. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46534. __decorate([
  46535. BABYLON.serializeAsTexture(),
  46536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46537. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46538. __decorate([
  46539. BABYLON.serializeAsTexture(),
  46540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46541. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46542. __decorate([
  46543. BABYLON.serialize(),
  46544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46545. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46546. __decorate([
  46547. BABYLON.serializeAsTexture(),
  46548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46549. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46550. __decorate([
  46551. BABYLON.serializeAsTexture(),
  46552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46553. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46554. __decorate([
  46555. BABYLON.serializeAsTexture(),
  46556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46557. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46558. __decorate([
  46559. BABYLON.serializeAsTexture(),
  46560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46561. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46562. __decorate([
  46563. BABYLON.serializeAsTexture(),
  46564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46565. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46566. __decorate([
  46567. BABYLON.serialize(),
  46568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46569. ], PBRMaterial.prototype, "metallic", void 0);
  46570. __decorate([
  46571. BABYLON.serialize(),
  46572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46573. ], PBRMaterial.prototype, "roughness", void 0);
  46574. __decorate([
  46575. BABYLON.serializeAsTexture(),
  46576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46577. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46578. __decorate([
  46579. BABYLON.serializeAsTexture(),
  46580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46581. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46582. __decorate([
  46583. BABYLON.serializeAsTexture(),
  46584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46585. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46586. __decorate([
  46587. BABYLON.serializeAsTexture(),
  46588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46589. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46590. __decorate([
  46591. BABYLON.serializeAsColor3("ambient"),
  46592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46593. ], PBRMaterial.prototype, "ambientColor", void 0);
  46594. __decorate([
  46595. BABYLON.serializeAsColor3("albedo"),
  46596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46597. ], PBRMaterial.prototype, "albedoColor", void 0);
  46598. __decorate([
  46599. BABYLON.serializeAsColor3("reflectivity"),
  46600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46601. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46602. __decorate([
  46603. BABYLON.serializeAsColor3("reflection"),
  46604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46605. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46606. __decorate([
  46607. BABYLON.serializeAsColor3("emissive"),
  46608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46609. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46610. __decorate([
  46611. BABYLON.serialize(),
  46612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46613. ], PBRMaterial.prototype, "microSurface", void 0);
  46614. __decorate([
  46615. BABYLON.serialize(),
  46616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46617. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46618. __decorate([
  46619. BABYLON.serialize(),
  46620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46621. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46622. __decorate([
  46623. BABYLON.serialize(),
  46624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46625. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46626. __decorate([
  46627. BABYLON.serialize(),
  46628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46629. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46630. __decorate([
  46631. BABYLON.serialize(),
  46632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46633. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46634. __decorate([
  46635. BABYLON.serialize(),
  46636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46637. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46638. __decorate([
  46639. BABYLON.serialize(),
  46640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46641. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46642. __decorate([
  46643. BABYLON.serialize(),
  46644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46645. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46646. __decorate([
  46647. BABYLON.serialize(),
  46648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46649. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46650. __decorate([
  46651. BABYLON.serialize(),
  46652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46653. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46654. __decorate([
  46655. BABYLON.serialize(),
  46656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46657. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46658. __decorate([
  46659. BABYLON.serialize(),
  46660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46661. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46662. __decorate([
  46663. BABYLON.serialize(),
  46664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46665. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46666. __decorate([
  46667. BABYLON.serialize(),
  46668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46669. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46670. __decorate([
  46671. BABYLON.serialize(),
  46672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46673. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46674. __decorate([
  46675. BABYLON.serialize(),
  46676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46677. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46678. __decorate([
  46679. BABYLON.serialize(),
  46680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46681. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46682. __decorate([
  46683. BABYLON.serialize(),
  46684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46685. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46686. __decorate([
  46687. BABYLON.serialize(),
  46688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46689. ], PBRMaterial.prototype, "useParallax", void 0);
  46690. __decorate([
  46691. BABYLON.serialize(),
  46692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46693. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46694. __decorate([
  46695. BABYLON.serialize(),
  46696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46697. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46698. __decorate([
  46699. BABYLON.serialize(),
  46700. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46701. ], PBRMaterial.prototype, "disableLighting", void 0);
  46702. __decorate([
  46703. BABYLON.serialize(),
  46704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46705. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46706. __decorate([
  46707. BABYLON.serialize(),
  46708. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46709. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46710. __decorate([
  46711. BABYLON.serialize(),
  46712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46713. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46714. __decorate([
  46715. BABYLON.serialize(),
  46716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46717. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46718. __decorate([
  46719. BABYLON.serialize(),
  46720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46721. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46722. __decorate([
  46723. BABYLON.serialize(),
  46724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46725. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46726. __decorate([
  46727. BABYLON.serialize(),
  46728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46729. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46730. __decorate([
  46731. BABYLON.serializeAsTexture(),
  46732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46733. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46734. __decorate([
  46735. BABYLON.serialize(),
  46736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46737. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46738. __decorate([
  46739. BABYLON.serialize(),
  46740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46741. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46742. __decorate([
  46743. BABYLON.serialize(),
  46744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46745. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46746. __decorate([
  46747. BABYLON.serialize(),
  46748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46749. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46750. __decorate([
  46751. BABYLON.serialize(),
  46752. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46753. ], PBRMaterial.prototype, "unlit", void 0);
  46754. return PBRMaterial;
  46755. }(BABYLON.PBRBaseMaterial));
  46756. BABYLON.PBRMaterial = PBRMaterial;
  46757. })(BABYLON || (BABYLON = {}));
  46758. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46759. var BABYLON;
  46760. (function (BABYLON) {
  46761. /**
  46762. * The PBR material of BJS following the metal roughness convention.
  46763. *
  46764. * This fits to the PBR convention in the GLTF definition:
  46765. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46766. */
  46767. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46768. __extends(PBRMetallicRoughnessMaterial, _super);
  46769. /**
  46770. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46771. *
  46772. * @param name The material name
  46773. * @param scene The scene the material will be use in.
  46774. */
  46775. function PBRMetallicRoughnessMaterial(name, scene) {
  46776. var _this = _super.call(this, name, scene) || this;
  46777. _this._useRoughnessFromMetallicTextureAlpha = false;
  46778. _this._useRoughnessFromMetallicTextureGreen = true;
  46779. _this._useMetallnessFromMetallicTextureBlue = true;
  46780. _this.metallic = 1.0;
  46781. _this.roughness = 1.0;
  46782. return _this;
  46783. }
  46784. /**
  46785. * Return the currrent class name of the material.
  46786. */
  46787. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46788. return "PBRMetallicRoughnessMaterial";
  46789. };
  46790. /**
  46791. * Return the active textures of the material.
  46792. */
  46793. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46794. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46795. if (this.baseTexture) {
  46796. activeTextures.push(this.baseTexture);
  46797. }
  46798. if (this.metallicRoughnessTexture) {
  46799. activeTextures.push(this.metallicRoughnessTexture);
  46800. }
  46801. return activeTextures;
  46802. };
  46803. /**
  46804. * Checks to see if a texture is used in the material.
  46805. * @param texture - Base texture to use.
  46806. * @returns - Boolean specifying if a texture is used in the material.
  46807. */
  46808. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46809. if (_super.prototype.hasTexture.call(this, texture)) {
  46810. return true;
  46811. }
  46812. if (this.baseTexture === texture) {
  46813. return true;
  46814. }
  46815. if (this.metallicRoughnessTexture === texture) {
  46816. return true;
  46817. }
  46818. return false;
  46819. };
  46820. /**
  46821. * Makes a duplicate of the current material.
  46822. * @param name - name to use for the new material.
  46823. */
  46824. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46825. var _this = this;
  46826. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46827. clone.id = name;
  46828. clone.name = name;
  46829. return clone;
  46830. };
  46831. /**
  46832. * Serialize the material to a parsable JSON object.
  46833. */
  46834. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46835. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46836. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46837. return serializationObject;
  46838. };
  46839. /**
  46840. * Parses a JSON object correponding to the serialize function.
  46841. */
  46842. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46843. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46844. };
  46845. __decorate([
  46846. BABYLON.serializeAsColor3(),
  46847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46848. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46849. __decorate([
  46850. BABYLON.serializeAsTexture(),
  46851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46852. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46853. __decorate([
  46854. BABYLON.serialize(),
  46855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46856. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46857. __decorate([
  46858. BABYLON.serialize(),
  46859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46860. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46861. __decorate([
  46862. BABYLON.serializeAsTexture(),
  46863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46864. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46865. return PBRMetallicRoughnessMaterial;
  46866. }(BABYLON.PBRBaseSimpleMaterial));
  46867. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46868. })(BABYLON || (BABYLON = {}));
  46869. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46870. var BABYLON;
  46871. (function (BABYLON) {
  46872. /**
  46873. * The PBR material of BJS following the specular glossiness convention.
  46874. *
  46875. * This fits to the PBR convention in the GLTF definition:
  46876. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46877. */
  46878. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46879. __extends(PBRSpecularGlossinessMaterial, _super);
  46880. /**
  46881. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46882. *
  46883. * @param name The material name
  46884. * @param scene The scene the material will be use in.
  46885. */
  46886. function PBRSpecularGlossinessMaterial(name, scene) {
  46887. var _this = _super.call(this, name, scene) || this;
  46888. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46889. return _this;
  46890. }
  46891. /**
  46892. * Return the currrent class name of the material.
  46893. */
  46894. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46895. return "PBRSpecularGlossinessMaterial";
  46896. };
  46897. /**
  46898. * Return the active textures of the material.
  46899. */
  46900. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46901. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46902. if (this.diffuseTexture) {
  46903. activeTextures.push(this.diffuseTexture);
  46904. }
  46905. if (this.specularGlossinessTexture) {
  46906. activeTextures.push(this.specularGlossinessTexture);
  46907. }
  46908. return activeTextures;
  46909. };
  46910. /**
  46911. * Checks to see if a texture is used in the material.
  46912. * @param texture - Base texture to use.
  46913. * @returns - Boolean specifying if a texture is used in the material.
  46914. */
  46915. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46916. if (_super.prototype.hasTexture.call(this, texture)) {
  46917. return true;
  46918. }
  46919. if (this.diffuseTexture === texture) {
  46920. return true;
  46921. }
  46922. if (this.specularGlossinessTexture === texture) {
  46923. return true;
  46924. }
  46925. return false;
  46926. };
  46927. /**
  46928. * Makes a duplicate of the current material.
  46929. * @param name - name to use for the new material.
  46930. */
  46931. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46932. var _this = this;
  46933. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46934. clone.id = name;
  46935. clone.name = name;
  46936. return clone;
  46937. };
  46938. /**
  46939. * Serialize the material to a parsable JSON object.
  46940. */
  46941. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46942. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46943. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46944. return serializationObject;
  46945. };
  46946. /**
  46947. * Parses a JSON object correponding to the serialize function.
  46948. */
  46949. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46950. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46951. };
  46952. __decorate([
  46953. BABYLON.serializeAsColor3("diffuse"),
  46954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46955. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46956. __decorate([
  46957. BABYLON.serializeAsTexture(),
  46958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46959. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46960. __decorate([
  46961. BABYLON.serializeAsColor3("specular"),
  46962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46963. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46964. __decorate([
  46965. BABYLON.serialize(),
  46966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46967. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46968. __decorate([
  46969. BABYLON.serializeAsTexture(),
  46970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46971. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46972. return PBRSpecularGlossinessMaterial;
  46973. }(BABYLON.PBRBaseSimpleMaterial));
  46974. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46975. })(BABYLON || (BABYLON = {}));
  46976. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46977. var BABYLON;
  46978. (function (BABYLON) {
  46979. BABYLON.CameraInputTypes = {};
  46980. var CameraInputsManager = /** @class */ (function () {
  46981. function CameraInputsManager(camera) {
  46982. this.attached = {};
  46983. this.camera = camera;
  46984. this.checkInputs = function () { };
  46985. }
  46986. /**
  46987. * Add an input method to a camera.
  46988. * builtin inputs example: camera.inputs.addGamepad();
  46989. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46990. * @param input camera input method
  46991. */
  46992. CameraInputsManager.prototype.add = function (input) {
  46993. var type = input.getSimpleName();
  46994. if (this.attached[type]) {
  46995. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46996. return;
  46997. }
  46998. this.attached[type] = input;
  46999. input.camera = this.camera;
  47000. //for checkInputs, we are dynamically creating a function
  47001. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47002. if (input.checkInputs) {
  47003. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47004. }
  47005. if (this.attachedElement) {
  47006. input.attachControl(this.attachedElement);
  47007. }
  47008. };
  47009. /**
  47010. * Remove a specific input method from a camera
  47011. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47012. * @param inputToRemove camera input method
  47013. */
  47014. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47015. for (var cam in this.attached) {
  47016. var input = this.attached[cam];
  47017. if (input === inputToRemove) {
  47018. input.detachControl(this.attachedElement);
  47019. input.camera = null;
  47020. delete this.attached[cam];
  47021. this.rebuildInputCheck();
  47022. }
  47023. }
  47024. };
  47025. CameraInputsManager.prototype.removeByType = function (inputType) {
  47026. for (var cam in this.attached) {
  47027. var input = this.attached[cam];
  47028. if (input.getClassName() === inputType) {
  47029. input.detachControl(this.attachedElement);
  47030. input.camera = null;
  47031. delete this.attached[cam];
  47032. this.rebuildInputCheck();
  47033. }
  47034. }
  47035. };
  47036. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47037. var current = this.checkInputs;
  47038. return function () {
  47039. current();
  47040. fn();
  47041. };
  47042. };
  47043. CameraInputsManager.prototype.attachInput = function (input) {
  47044. if (this.attachedElement) {
  47045. input.attachControl(this.attachedElement, this.noPreventDefault);
  47046. }
  47047. };
  47048. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47049. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47050. if (this.attachedElement) {
  47051. return;
  47052. }
  47053. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47054. this.attachedElement = element;
  47055. this.noPreventDefault = noPreventDefault;
  47056. for (var cam in this.attached) {
  47057. this.attached[cam].attachControl(element, noPreventDefault);
  47058. }
  47059. };
  47060. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47061. if (disconnect === void 0) { disconnect = false; }
  47062. if (this.attachedElement !== element) {
  47063. return;
  47064. }
  47065. for (var cam in this.attached) {
  47066. this.attached[cam].detachControl(element);
  47067. if (disconnect) {
  47068. this.attached[cam].camera = null;
  47069. }
  47070. }
  47071. this.attachedElement = null;
  47072. };
  47073. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47074. this.checkInputs = function () { };
  47075. for (var cam in this.attached) {
  47076. var input = this.attached[cam];
  47077. if (input.checkInputs) {
  47078. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47079. }
  47080. }
  47081. };
  47082. /**
  47083. * Remove all attached input methods from a camera
  47084. */
  47085. CameraInputsManager.prototype.clear = function () {
  47086. if (this.attachedElement) {
  47087. this.detachElement(this.attachedElement, true);
  47088. }
  47089. this.attached = {};
  47090. this.attachedElement = null;
  47091. this.checkInputs = function () { };
  47092. };
  47093. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47094. var inputs = {};
  47095. for (var cam in this.attached) {
  47096. var input = this.attached[cam];
  47097. var res = BABYLON.SerializationHelper.Serialize(input);
  47098. inputs[input.getClassName()] = res;
  47099. }
  47100. serializedCamera.inputsmgr = inputs;
  47101. };
  47102. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47103. var parsedInputs = parsedCamera.inputsmgr;
  47104. if (parsedInputs) {
  47105. this.clear();
  47106. for (var n in parsedInputs) {
  47107. var construct = BABYLON.CameraInputTypes[n];
  47108. if (construct) {
  47109. var parsedinput = parsedInputs[n];
  47110. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47111. this.add(input);
  47112. }
  47113. }
  47114. }
  47115. else {
  47116. //2016-03-08 this part is for managing backward compatibility
  47117. for (var n in this.attached) {
  47118. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47119. if (construct) {
  47120. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47121. this.remove(this.attached[n]);
  47122. this.add(input);
  47123. }
  47124. }
  47125. }
  47126. };
  47127. return CameraInputsManager;
  47128. }());
  47129. BABYLON.CameraInputsManager = CameraInputsManager;
  47130. })(BABYLON || (BABYLON = {}));
  47131. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47132. var BABYLON;
  47133. (function (BABYLON) {
  47134. var TargetCamera = /** @class */ (function (_super) {
  47135. __extends(TargetCamera, _super);
  47136. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47137. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47138. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47139. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47140. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47141. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47142. _this.speed = 2.0;
  47143. _this.noRotationConstraint = false;
  47144. _this.lockedTarget = null;
  47145. _this._currentTarget = BABYLON.Vector3.Zero();
  47146. _this._viewMatrix = BABYLON.Matrix.Zero();
  47147. _this._camMatrix = BABYLON.Matrix.Zero();
  47148. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47149. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47150. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47151. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47152. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47153. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47154. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47155. return _this;
  47156. }
  47157. TargetCamera.prototype.getFrontPosition = function (distance) {
  47158. this.getWorldMatrix();
  47159. var direction = this.getTarget().subtract(this.position);
  47160. direction.normalize();
  47161. direction.scaleInPlace(distance);
  47162. return this.globalPosition.add(direction);
  47163. };
  47164. TargetCamera.prototype._getLockedTargetPosition = function () {
  47165. if (!this.lockedTarget) {
  47166. return null;
  47167. }
  47168. if (this.lockedTarget.absolutePosition) {
  47169. this.lockedTarget.computeWorldMatrix();
  47170. }
  47171. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47172. };
  47173. TargetCamera.prototype.storeState = function () {
  47174. this._storedPosition = this.position.clone();
  47175. this._storedRotation = this.rotation.clone();
  47176. if (this.rotationQuaternion) {
  47177. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47178. }
  47179. return _super.prototype.storeState.call(this);
  47180. };
  47181. /**
  47182. * Restored camera state. You must call storeState() first
  47183. */
  47184. TargetCamera.prototype._restoreStateValues = function () {
  47185. if (!_super.prototype._restoreStateValues.call(this)) {
  47186. return false;
  47187. }
  47188. this.position = this._storedPosition.clone();
  47189. this.rotation = this._storedRotation.clone();
  47190. if (this.rotationQuaternion) {
  47191. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47192. }
  47193. this.cameraDirection.copyFromFloats(0, 0, 0);
  47194. this.cameraRotation.copyFromFloats(0, 0);
  47195. return true;
  47196. };
  47197. // Cache
  47198. TargetCamera.prototype._initCache = function () {
  47199. _super.prototype._initCache.call(this);
  47200. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47201. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47202. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47203. };
  47204. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47205. if (!ignoreParentClass) {
  47206. _super.prototype._updateCache.call(this);
  47207. }
  47208. var lockedTargetPosition = this._getLockedTargetPosition();
  47209. if (!lockedTargetPosition) {
  47210. this._cache.lockedTarget = null;
  47211. }
  47212. else {
  47213. if (!this._cache.lockedTarget) {
  47214. this._cache.lockedTarget = lockedTargetPosition.clone();
  47215. }
  47216. else {
  47217. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47218. }
  47219. }
  47220. this._cache.rotation.copyFrom(this.rotation);
  47221. if (this.rotationQuaternion)
  47222. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47223. };
  47224. // Synchronized
  47225. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47226. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47227. return false;
  47228. }
  47229. var lockedTargetPosition = this._getLockedTargetPosition();
  47230. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47231. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47232. };
  47233. // Methods
  47234. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47235. var engine = this.getEngine();
  47236. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47237. };
  47238. // Target
  47239. TargetCamera.prototype.setTarget = function (target) {
  47240. this.upVector.normalize();
  47241. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47242. this._camMatrix.invert();
  47243. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47244. var vDir = target.subtract(this.position);
  47245. if (vDir.x >= 0.0) {
  47246. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47247. }
  47248. else {
  47249. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47250. }
  47251. this.rotation.z = 0;
  47252. if (isNaN(this.rotation.x)) {
  47253. this.rotation.x = 0;
  47254. }
  47255. if (isNaN(this.rotation.y)) {
  47256. this.rotation.y = 0;
  47257. }
  47258. if (isNaN(this.rotation.z)) {
  47259. this.rotation.z = 0;
  47260. }
  47261. if (this.rotationQuaternion) {
  47262. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47263. }
  47264. };
  47265. /**
  47266. * Return the current target position of the camera. This value is expressed in local space.
  47267. */
  47268. TargetCamera.prototype.getTarget = function () {
  47269. return this._currentTarget;
  47270. };
  47271. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47272. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47273. };
  47274. TargetCamera.prototype._updatePosition = function () {
  47275. if (this.parent) {
  47276. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47277. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47278. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47279. return;
  47280. }
  47281. this.position.addInPlace(this.cameraDirection);
  47282. };
  47283. TargetCamera.prototype._checkInputs = function () {
  47284. var needToMove = this._decideIfNeedsToMove();
  47285. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47286. // Move
  47287. if (needToMove) {
  47288. this._updatePosition();
  47289. }
  47290. // Rotate
  47291. if (needToRotate) {
  47292. this.rotation.x += this.cameraRotation.x;
  47293. this.rotation.y += this.cameraRotation.y;
  47294. //rotate, if quaternion is set and rotation was used
  47295. if (this.rotationQuaternion) {
  47296. var len = this.rotation.lengthSquared();
  47297. if (len) {
  47298. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47299. }
  47300. }
  47301. if (!this.noRotationConstraint) {
  47302. var limit = (Math.PI / 2) * 0.95;
  47303. if (this.rotation.x > limit)
  47304. this.rotation.x = limit;
  47305. if (this.rotation.x < -limit)
  47306. this.rotation.x = -limit;
  47307. }
  47308. }
  47309. // Inertia
  47310. if (needToMove) {
  47311. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47312. this.cameraDirection.x = 0;
  47313. }
  47314. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47315. this.cameraDirection.y = 0;
  47316. }
  47317. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47318. this.cameraDirection.z = 0;
  47319. }
  47320. this.cameraDirection.scaleInPlace(this.inertia);
  47321. }
  47322. if (needToRotate) {
  47323. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47324. this.cameraRotation.x = 0;
  47325. }
  47326. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47327. this.cameraRotation.y = 0;
  47328. }
  47329. this.cameraRotation.scaleInPlace(this.inertia);
  47330. }
  47331. _super.prototype._checkInputs.call(this);
  47332. };
  47333. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47334. if (this.rotationQuaternion) {
  47335. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47336. }
  47337. else {
  47338. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47339. }
  47340. //update the up vector!
  47341. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47342. };
  47343. TargetCamera.prototype._getViewMatrix = function () {
  47344. if (this.lockedTarget) {
  47345. this.setTarget(this._getLockedTargetPosition());
  47346. }
  47347. // Compute
  47348. this._updateCameraRotationMatrix();
  47349. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47350. // Computing target and final matrix
  47351. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47352. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47353. return this._viewMatrix;
  47354. };
  47355. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47356. if (this.parent) {
  47357. var parentWorldMatrix = this.parent.getWorldMatrix();
  47358. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47359. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47360. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47361. this._markSyncedWithParent();
  47362. }
  47363. else {
  47364. this._globalPosition.copyFrom(this.position);
  47365. this._globalCurrentTarget.copyFrom(target);
  47366. this._globalCurrentUpVector.copyFrom(up);
  47367. }
  47368. if (this.getScene().useRightHandedSystem) {
  47369. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47370. }
  47371. else {
  47372. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47373. }
  47374. };
  47375. /**
  47376. * @override
  47377. * Override Camera.createRigCamera
  47378. */
  47379. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47380. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47381. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47382. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47383. if (!this.rotationQuaternion) {
  47384. this.rotationQuaternion = new BABYLON.Quaternion();
  47385. }
  47386. rigCamera._cameraRigParams = {};
  47387. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47388. }
  47389. return rigCamera;
  47390. }
  47391. return null;
  47392. };
  47393. /**
  47394. * @override
  47395. * Override Camera._updateRigCameras
  47396. */
  47397. TargetCamera.prototype._updateRigCameras = function () {
  47398. var camLeft = this._rigCameras[0];
  47399. var camRight = this._rigCameras[1];
  47400. switch (this.cameraRigMode) {
  47401. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47402. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47403. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47404. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47405. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47406. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47407. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47408. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47409. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47410. camLeft.setTarget(this.getTarget());
  47411. camRight.setTarget(this.getTarget());
  47412. break;
  47413. case BABYLON.Camera.RIG_MODE_VR:
  47414. if (camLeft.rotationQuaternion) {
  47415. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47416. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47417. }
  47418. else {
  47419. camLeft.rotation.copyFrom(this.rotation);
  47420. camRight.rotation.copyFrom(this.rotation);
  47421. }
  47422. camLeft.position.copyFrom(this.position);
  47423. camRight.position.copyFrom(this.position);
  47424. break;
  47425. }
  47426. _super.prototype._updateRigCameras.call(this);
  47427. };
  47428. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47429. if (!this._rigCamTransformMatrix) {
  47430. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47431. }
  47432. var target = this.getTarget();
  47433. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47434. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47435. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47436. };
  47437. TargetCamera.prototype.getClassName = function () {
  47438. return "TargetCamera";
  47439. };
  47440. __decorate([
  47441. BABYLON.serializeAsVector3()
  47442. ], TargetCamera.prototype, "rotation", void 0);
  47443. __decorate([
  47444. BABYLON.serialize()
  47445. ], TargetCamera.prototype, "speed", void 0);
  47446. __decorate([
  47447. BABYLON.serializeAsMeshReference("lockedTargetId")
  47448. ], TargetCamera.prototype, "lockedTarget", void 0);
  47449. return TargetCamera;
  47450. }(BABYLON.Camera));
  47451. BABYLON.TargetCamera = TargetCamera;
  47452. })(BABYLON || (BABYLON = {}));
  47453. //# sourceMappingURL=babylon.targetCamera.js.map
  47454. var BABYLON;
  47455. (function (BABYLON) {
  47456. var FreeCameraMouseInput = /** @class */ (function () {
  47457. function FreeCameraMouseInput(touchEnabled) {
  47458. if (touchEnabled === void 0) { touchEnabled = true; }
  47459. this.touchEnabled = touchEnabled;
  47460. this.buttons = [0, 1, 2];
  47461. this.angularSensibility = 2000.0;
  47462. this.previousPosition = null;
  47463. }
  47464. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47465. var _this = this;
  47466. var engine = this.camera.getEngine();
  47467. if (!this._pointerInput) {
  47468. this._pointerInput = function (p, s) {
  47469. var evt = p.event;
  47470. if (engine.isInVRExclusivePointerMode) {
  47471. return;
  47472. }
  47473. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47474. return;
  47475. }
  47476. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47477. return;
  47478. }
  47479. var srcElement = (evt.srcElement || evt.target);
  47480. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47481. try {
  47482. srcElement.setPointerCapture(evt.pointerId);
  47483. }
  47484. catch (e) {
  47485. //Nothing to do with the error. Execution will continue.
  47486. }
  47487. _this.previousPosition = {
  47488. x: evt.clientX,
  47489. y: evt.clientY
  47490. };
  47491. if (!noPreventDefault) {
  47492. evt.preventDefault();
  47493. element.focus();
  47494. }
  47495. }
  47496. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47497. try {
  47498. srcElement.releasePointerCapture(evt.pointerId);
  47499. }
  47500. catch (e) {
  47501. //Nothing to do with the error.
  47502. }
  47503. _this.previousPosition = null;
  47504. if (!noPreventDefault) {
  47505. evt.preventDefault();
  47506. }
  47507. }
  47508. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47509. if (!_this.previousPosition || engine.isPointerLock) {
  47510. return;
  47511. }
  47512. var offsetX = evt.clientX - _this.previousPosition.x;
  47513. if (_this.camera.getScene().useRightHandedSystem)
  47514. offsetX *= -1;
  47515. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47516. offsetX *= -1;
  47517. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47518. var offsetY = evt.clientY - _this.previousPosition.y;
  47519. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47520. _this.previousPosition = {
  47521. x: evt.clientX,
  47522. y: evt.clientY
  47523. };
  47524. if (!noPreventDefault) {
  47525. evt.preventDefault();
  47526. }
  47527. }
  47528. };
  47529. }
  47530. this._onMouseMove = function (evt) {
  47531. if (!engine.isPointerLock) {
  47532. return;
  47533. }
  47534. if (engine.isInVRExclusivePointerMode) {
  47535. return;
  47536. }
  47537. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47538. if (_this.camera.getScene().useRightHandedSystem)
  47539. offsetX *= -1;
  47540. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47541. offsetX *= -1;
  47542. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47543. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47544. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47545. _this.previousPosition = null;
  47546. if (!noPreventDefault) {
  47547. evt.preventDefault();
  47548. }
  47549. };
  47550. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47551. element.addEventListener("mousemove", this._onMouseMove, false);
  47552. };
  47553. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47554. if (this._observer && element) {
  47555. this.camera.getScene().onPointerObservable.remove(this._observer);
  47556. if (this._onMouseMove) {
  47557. element.removeEventListener("mousemove", this._onMouseMove);
  47558. }
  47559. this._observer = null;
  47560. this._onMouseMove = null;
  47561. this.previousPosition = null;
  47562. }
  47563. };
  47564. FreeCameraMouseInput.prototype.getClassName = function () {
  47565. return "FreeCameraMouseInput";
  47566. };
  47567. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47568. return "mouse";
  47569. };
  47570. __decorate([
  47571. BABYLON.serialize()
  47572. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47573. __decorate([
  47574. BABYLON.serialize()
  47575. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47576. return FreeCameraMouseInput;
  47577. }());
  47578. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47579. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47580. })(BABYLON || (BABYLON = {}));
  47581. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47582. var BABYLON;
  47583. (function (BABYLON) {
  47584. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47585. function FreeCameraKeyboardMoveInput() {
  47586. this._keys = new Array();
  47587. this.keysUp = [38];
  47588. this.keysDown = [40];
  47589. this.keysLeft = [37];
  47590. this.keysRight = [39];
  47591. }
  47592. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47593. var _this = this;
  47594. if (this._onCanvasBlurObserver) {
  47595. return;
  47596. }
  47597. this._scene = this.camera.getScene();
  47598. this._engine = this._scene.getEngine();
  47599. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47600. _this._keys = [];
  47601. });
  47602. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47603. var evt = info.event;
  47604. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47605. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47606. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47607. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47608. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47609. var index = _this._keys.indexOf(evt.keyCode);
  47610. if (index === -1) {
  47611. _this._keys.push(evt.keyCode);
  47612. }
  47613. if (!noPreventDefault) {
  47614. evt.preventDefault();
  47615. }
  47616. }
  47617. }
  47618. else {
  47619. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47620. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47621. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47622. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47623. var index = _this._keys.indexOf(evt.keyCode);
  47624. if (index >= 0) {
  47625. _this._keys.splice(index, 1);
  47626. }
  47627. if (!noPreventDefault) {
  47628. evt.preventDefault();
  47629. }
  47630. }
  47631. }
  47632. });
  47633. };
  47634. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47635. if (this._scene) {
  47636. if (this._onKeyboardObserver) {
  47637. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47638. }
  47639. if (this._onCanvasBlurObserver) {
  47640. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47641. }
  47642. this._onKeyboardObserver = null;
  47643. this._onCanvasBlurObserver = null;
  47644. }
  47645. this._keys = [];
  47646. };
  47647. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47648. if (this._onKeyboardObserver) {
  47649. var camera = this.camera;
  47650. // Keyboard
  47651. for (var index = 0; index < this._keys.length; index++) {
  47652. var keyCode = this._keys[index];
  47653. var speed = camera._computeLocalCameraSpeed();
  47654. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47655. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47656. }
  47657. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47658. camera._localDirection.copyFromFloats(0, 0, speed);
  47659. }
  47660. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47661. camera._localDirection.copyFromFloats(speed, 0, 0);
  47662. }
  47663. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47664. camera._localDirection.copyFromFloats(0, 0, -speed);
  47665. }
  47666. if (camera.getScene().useRightHandedSystem) {
  47667. camera._localDirection.z *= -1;
  47668. }
  47669. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47670. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47671. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47672. }
  47673. }
  47674. };
  47675. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47676. return "FreeCameraKeyboardMoveInput";
  47677. };
  47678. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47679. this._keys = [];
  47680. };
  47681. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47682. return "keyboard";
  47683. };
  47684. __decorate([
  47685. BABYLON.serialize()
  47686. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47687. __decorate([
  47688. BABYLON.serialize()
  47689. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47690. __decorate([
  47691. BABYLON.serialize()
  47692. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47693. __decorate([
  47694. BABYLON.serialize()
  47695. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47696. return FreeCameraKeyboardMoveInput;
  47697. }());
  47698. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47699. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47700. })(BABYLON || (BABYLON = {}));
  47701. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47702. var BABYLON;
  47703. (function (BABYLON) {
  47704. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47705. __extends(FreeCameraInputsManager, _super);
  47706. function FreeCameraInputsManager(camera) {
  47707. return _super.call(this, camera) || this;
  47708. }
  47709. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47710. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47711. return this;
  47712. };
  47713. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47714. if (touchEnabled === void 0) { touchEnabled = true; }
  47715. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47716. return this;
  47717. };
  47718. FreeCameraInputsManager.prototype.addGamepad = function () {
  47719. this.add(new BABYLON.FreeCameraGamepadInput());
  47720. return this;
  47721. };
  47722. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47723. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47724. return this;
  47725. };
  47726. FreeCameraInputsManager.prototype.addTouch = function () {
  47727. this.add(new BABYLON.FreeCameraTouchInput());
  47728. return this;
  47729. };
  47730. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47731. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47732. return this;
  47733. };
  47734. return FreeCameraInputsManager;
  47735. }(BABYLON.CameraInputsManager));
  47736. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47737. })(BABYLON || (BABYLON = {}));
  47738. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47739. var BABYLON;
  47740. (function (BABYLON) {
  47741. var FreeCamera = /** @class */ (function (_super) {
  47742. __extends(FreeCamera, _super);
  47743. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47744. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47745. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47746. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47747. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47748. _this.checkCollisions = false;
  47749. _this.applyGravity = false;
  47750. _this._needMoveForGravity = false;
  47751. _this._oldPosition = BABYLON.Vector3.Zero();
  47752. _this._diffPosition = BABYLON.Vector3.Zero();
  47753. _this._newPosition = BABYLON.Vector3.Zero();
  47754. // Collisions
  47755. _this._collisionMask = -1;
  47756. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47757. if (collidedMesh === void 0) { collidedMesh = null; }
  47758. //TODO move this to the collision coordinator!
  47759. if (_this.getScene().workerCollisions)
  47760. newPosition.multiplyInPlace(_this._collider._radius);
  47761. var updatePosition = function (newPos) {
  47762. _this._newPosition.copyFrom(newPos);
  47763. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47764. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47765. _this.position.addInPlace(_this._diffPosition);
  47766. if (_this.onCollide && collidedMesh) {
  47767. _this.onCollide(collidedMesh);
  47768. }
  47769. }
  47770. };
  47771. updatePosition(newPosition);
  47772. };
  47773. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47774. _this.inputs.addKeyboard().addMouse();
  47775. return _this;
  47776. }
  47777. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47778. //-- begin properties for backward compatibility for inputs
  47779. /**
  47780. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47781. * Higher values reduce sensitivity.
  47782. */
  47783. get: function () {
  47784. var mouse = this.inputs.attached["mouse"];
  47785. if (mouse)
  47786. return mouse.angularSensibility;
  47787. return 0;
  47788. },
  47789. /**
  47790. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47791. * Higher values reduce sensitivity.
  47792. */
  47793. set: function (value) {
  47794. var mouse = this.inputs.attached["mouse"];
  47795. if (mouse)
  47796. mouse.angularSensibility = value;
  47797. },
  47798. enumerable: true,
  47799. configurable: true
  47800. });
  47801. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47802. get: function () {
  47803. var keyboard = this.inputs.attached["keyboard"];
  47804. if (keyboard)
  47805. return keyboard.keysUp;
  47806. return [];
  47807. },
  47808. set: function (value) {
  47809. var keyboard = this.inputs.attached["keyboard"];
  47810. if (keyboard)
  47811. keyboard.keysUp = value;
  47812. },
  47813. enumerable: true,
  47814. configurable: true
  47815. });
  47816. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47817. get: function () {
  47818. var keyboard = this.inputs.attached["keyboard"];
  47819. if (keyboard)
  47820. return keyboard.keysDown;
  47821. return [];
  47822. },
  47823. set: function (value) {
  47824. var keyboard = this.inputs.attached["keyboard"];
  47825. if (keyboard)
  47826. keyboard.keysDown = value;
  47827. },
  47828. enumerable: true,
  47829. configurable: true
  47830. });
  47831. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47832. get: function () {
  47833. var keyboard = this.inputs.attached["keyboard"];
  47834. if (keyboard)
  47835. return keyboard.keysLeft;
  47836. return [];
  47837. },
  47838. set: function (value) {
  47839. var keyboard = this.inputs.attached["keyboard"];
  47840. if (keyboard)
  47841. keyboard.keysLeft = value;
  47842. },
  47843. enumerable: true,
  47844. configurable: true
  47845. });
  47846. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47847. get: function () {
  47848. var keyboard = this.inputs.attached["keyboard"];
  47849. if (keyboard)
  47850. return keyboard.keysRight;
  47851. return [];
  47852. },
  47853. set: function (value) {
  47854. var keyboard = this.inputs.attached["keyboard"];
  47855. if (keyboard)
  47856. keyboard.keysRight = value;
  47857. },
  47858. enumerable: true,
  47859. configurable: true
  47860. });
  47861. // Controls
  47862. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47863. this.inputs.attachElement(element, noPreventDefault);
  47864. };
  47865. FreeCamera.prototype.detachControl = function (element) {
  47866. this.inputs.detachElement(element);
  47867. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47868. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47869. };
  47870. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47871. get: function () {
  47872. return this._collisionMask;
  47873. },
  47874. set: function (mask) {
  47875. this._collisionMask = !isNaN(mask) ? mask : -1;
  47876. },
  47877. enumerable: true,
  47878. configurable: true
  47879. });
  47880. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47881. var globalPosition;
  47882. if (this.parent) {
  47883. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47884. }
  47885. else {
  47886. globalPosition = this.position;
  47887. }
  47888. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47889. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47890. if (!this._collider) {
  47891. this._collider = new BABYLON.Collider();
  47892. }
  47893. this._collider._radius = this.ellipsoid;
  47894. this._collider.collisionMask = this._collisionMask;
  47895. //no need for clone, as long as gravity is not on.
  47896. var actualDisplacement = displacement;
  47897. //add gravity to the direction to prevent the dual-collision checking
  47898. if (this.applyGravity) {
  47899. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47900. actualDisplacement = displacement.add(this.getScene().gravity);
  47901. }
  47902. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47903. };
  47904. FreeCamera.prototype._checkInputs = function () {
  47905. if (!this._localDirection) {
  47906. this._localDirection = BABYLON.Vector3.Zero();
  47907. this._transformedDirection = BABYLON.Vector3.Zero();
  47908. }
  47909. this.inputs.checkInputs();
  47910. _super.prototype._checkInputs.call(this);
  47911. };
  47912. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47913. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47914. };
  47915. FreeCamera.prototype._updatePosition = function () {
  47916. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47917. this._collideWithWorld(this.cameraDirection);
  47918. }
  47919. else {
  47920. _super.prototype._updatePosition.call(this);
  47921. }
  47922. };
  47923. FreeCamera.prototype.dispose = function () {
  47924. this.inputs.clear();
  47925. _super.prototype.dispose.call(this);
  47926. };
  47927. FreeCamera.prototype.getClassName = function () {
  47928. return "FreeCamera";
  47929. };
  47930. __decorate([
  47931. BABYLON.serializeAsVector3()
  47932. ], FreeCamera.prototype, "ellipsoid", void 0);
  47933. __decorate([
  47934. BABYLON.serializeAsVector3()
  47935. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47936. __decorate([
  47937. BABYLON.serialize()
  47938. ], FreeCamera.prototype, "checkCollisions", void 0);
  47939. __decorate([
  47940. BABYLON.serialize()
  47941. ], FreeCamera.prototype, "applyGravity", void 0);
  47942. return FreeCamera;
  47943. }(BABYLON.TargetCamera));
  47944. BABYLON.FreeCamera = FreeCamera;
  47945. })(BABYLON || (BABYLON = {}));
  47946. //# sourceMappingURL=babylon.freeCamera.js.map
  47947. var BABYLON;
  47948. (function (BABYLON) {
  47949. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47950. function ArcRotateCameraKeyboardMoveInput() {
  47951. this._keys = new Array();
  47952. this.keysUp = [38];
  47953. this.keysDown = [40];
  47954. this.keysLeft = [37];
  47955. this.keysRight = [39];
  47956. this.keysReset = [220];
  47957. this.panningSensibility = 50.0;
  47958. this.zoomingSensibility = 25.0;
  47959. this.useAltToZoom = true;
  47960. }
  47961. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47962. var _this = this;
  47963. if (this._onCanvasBlurObserver) {
  47964. return;
  47965. }
  47966. this._scene = this.camera.getScene();
  47967. this._engine = this._scene.getEngine();
  47968. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47969. _this._keys = [];
  47970. });
  47971. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47972. var evt = info.event;
  47973. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47974. _this._ctrlPressed = evt.ctrlKey;
  47975. _this._altPressed = evt.altKey;
  47976. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47977. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47978. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47979. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47980. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47981. var index = _this._keys.indexOf(evt.keyCode);
  47982. if (index === -1) {
  47983. _this._keys.push(evt.keyCode);
  47984. }
  47985. if (evt.preventDefault) {
  47986. if (!noPreventDefault) {
  47987. evt.preventDefault();
  47988. }
  47989. }
  47990. }
  47991. }
  47992. else {
  47993. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47994. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47995. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47996. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47997. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47998. var index = _this._keys.indexOf(evt.keyCode);
  47999. if (index >= 0) {
  48000. _this._keys.splice(index, 1);
  48001. }
  48002. if (evt.preventDefault) {
  48003. if (!noPreventDefault) {
  48004. evt.preventDefault();
  48005. }
  48006. }
  48007. }
  48008. }
  48009. });
  48010. };
  48011. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48012. if (this._scene) {
  48013. if (this._onKeyboardObserver) {
  48014. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48015. }
  48016. if (this._onCanvasBlurObserver) {
  48017. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48018. }
  48019. this._onKeyboardObserver = null;
  48020. this._onCanvasBlurObserver = null;
  48021. }
  48022. this._keys = [];
  48023. };
  48024. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48025. if (this._onKeyboardObserver) {
  48026. var camera = this.camera;
  48027. for (var index = 0; index < this._keys.length; index++) {
  48028. var keyCode = this._keys[index];
  48029. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48030. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48031. camera.inertialPanningX -= 1 / this.panningSensibility;
  48032. }
  48033. else {
  48034. camera.inertialAlphaOffset -= 0.01;
  48035. }
  48036. }
  48037. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48038. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48039. camera.inertialPanningY += 1 / this.panningSensibility;
  48040. }
  48041. else if (this._altPressed && this.useAltToZoom) {
  48042. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48043. }
  48044. else {
  48045. camera.inertialBetaOffset -= 0.01;
  48046. }
  48047. }
  48048. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48049. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48050. camera.inertialPanningX += 1 / this.panningSensibility;
  48051. }
  48052. else {
  48053. camera.inertialAlphaOffset += 0.01;
  48054. }
  48055. }
  48056. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48057. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48058. camera.inertialPanningY -= 1 / this.panningSensibility;
  48059. }
  48060. else if (this._altPressed && this.useAltToZoom) {
  48061. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48062. }
  48063. else {
  48064. camera.inertialBetaOffset += 0.01;
  48065. }
  48066. }
  48067. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48068. camera.restoreState();
  48069. }
  48070. }
  48071. }
  48072. };
  48073. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48074. return "ArcRotateCameraKeyboardMoveInput";
  48075. };
  48076. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48077. return "keyboard";
  48078. };
  48079. __decorate([
  48080. BABYLON.serialize()
  48081. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48082. __decorate([
  48083. BABYLON.serialize()
  48084. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48085. __decorate([
  48086. BABYLON.serialize()
  48087. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48088. __decorate([
  48089. BABYLON.serialize()
  48090. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48091. __decorate([
  48092. BABYLON.serialize()
  48093. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48094. __decorate([
  48095. BABYLON.serialize()
  48096. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48097. __decorate([
  48098. BABYLON.serialize()
  48099. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48100. __decorate([
  48101. BABYLON.serialize()
  48102. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48103. return ArcRotateCameraKeyboardMoveInput;
  48104. }());
  48105. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48106. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48107. })(BABYLON || (BABYLON = {}));
  48108. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48109. var BABYLON;
  48110. (function (BABYLON) {
  48111. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48112. function ArcRotateCameraMouseWheelInput() {
  48113. this.wheelPrecision = 3.0;
  48114. /**
  48115. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48116. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48117. */
  48118. this.wheelDeltaPercentage = 0;
  48119. }
  48120. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48121. var _this = this;
  48122. this._wheel = function (p, s) {
  48123. //sanity check - this should be a PointerWheel event.
  48124. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48125. return;
  48126. var event = p.event;
  48127. var delta = 0;
  48128. if (event.wheelDelta) {
  48129. if (_this.wheelDeltaPercentage) {
  48130. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48131. if (event.wheelDelta > 0) {
  48132. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48133. }
  48134. else {
  48135. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48136. }
  48137. }
  48138. else {
  48139. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48140. }
  48141. }
  48142. else if (event.detail) {
  48143. delta = -event.detail / _this.wheelPrecision;
  48144. }
  48145. if (delta)
  48146. _this.camera.inertialRadiusOffset += delta;
  48147. if (event.preventDefault) {
  48148. if (!noPreventDefault) {
  48149. event.preventDefault();
  48150. }
  48151. }
  48152. };
  48153. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48154. };
  48155. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48156. if (this._observer && element) {
  48157. this.camera.getScene().onPointerObservable.remove(this._observer);
  48158. this._observer = null;
  48159. this._wheel = null;
  48160. }
  48161. };
  48162. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48163. return "ArcRotateCameraMouseWheelInput";
  48164. };
  48165. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48166. return "mousewheel";
  48167. };
  48168. __decorate([
  48169. BABYLON.serialize()
  48170. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48171. __decorate([
  48172. BABYLON.serialize()
  48173. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48174. return ArcRotateCameraMouseWheelInput;
  48175. }());
  48176. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48177. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48178. })(BABYLON || (BABYLON = {}));
  48179. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48180. var BABYLON;
  48181. (function (BABYLON) {
  48182. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48183. function ArcRotateCameraPointersInput() {
  48184. this.buttons = [0, 1, 2];
  48185. this.angularSensibilityX = 1000.0;
  48186. this.angularSensibilityY = 1000.0;
  48187. this.pinchPrecision = 12.0;
  48188. /**
  48189. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48190. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48191. */
  48192. this.pinchDeltaPercentage = 0;
  48193. this.panningSensibility = 1000.0;
  48194. this.multiTouchPanning = true;
  48195. this.multiTouchPanAndZoom = true;
  48196. this._isPanClick = false;
  48197. this.pinchInwards = true;
  48198. }
  48199. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48200. var _this = this;
  48201. var engine = this.camera.getEngine();
  48202. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48203. var pointA = null;
  48204. var pointB = null;
  48205. var previousPinchSquaredDistance = 0;
  48206. var initialDistance = 0;
  48207. var twoFingerActivityCount = 0;
  48208. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48209. this._pointerInput = function (p, s) {
  48210. var evt = p.event;
  48211. var isTouch = p.event.pointerType === "touch";
  48212. if (engine.isInVRExclusivePointerMode) {
  48213. return;
  48214. }
  48215. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48216. return;
  48217. }
  48218. var srcElement = (evt.srcElement || evt.target);
  48219. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48220. try {
  48221. srcElement.setPointerCapture(evt.pointerId);
  48222. }
  48223. catch (e) {
  48224. //Nothing to do with the error. Execution will continue.
  48225. }
  48226. // Manage panning with pan button click
  48227. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48228. // manage pointers
  48229. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48230. if (pointA === null) {
  48231. pointA = cacheSoloPointer;
  48232. }
  48233. else if (pointB === null) {
  48234. pointB = cacheSoloPointer;
  48235. }
  48236. if (!noPreventDefault) {
  48237. evt.preventDefault();
  48238. element.focus();
  48239. }
  48240. }
  48241. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48242. _this.camera.restoreState();
  48243. }
  48244. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48245. try {
  48246. srcElement.releasePointerCapture(evt.pointerId);
  48247. }
  48248. catch (e) {
  48249. //Nothing to do with the error.
  48250. }
  48251. cacheSoloPointer = null;
  48252. previousPinchSquaredDistance = 0;
  48253. previousMultiTouchPanPosition.isPaning = false;
  48254. previousMultiTouchPanPosition.isPinching = false;
  48255. twoFingerActivityCount = 0;
  48256. initialDistance = 0;
  48257. if (!isTouch) {
  48258. pointB = null; // Mouse and pen are mono pointer
  48259. }
  48260. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48261. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48262. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48263. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48264. if (engine._badOS) {
  48265. pointA = pointB = null;
  48266. }
  48267. else {
  48268. //only remove the impacted pointer in case of multitouch allowing on most
  48269. //platforms switching from rotate to zoom and pan seamlessly.
  48270. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48271. pointA = pointB;
  48272. pointB = null;
  48273. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48274. }
  48275. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48276. pointB = null;
  48277. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48278. }
  48279. else {
  48280. pointA = pointB = null;
  48281. }
  48282. }
  48283. if (!noPreventDefault) {
  48284. evt.preventDefault();
  48285. }
  48286. }
  48287. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48288. if (!noPreventDefault) {
  48289. evt.preventDefault();
  48290. }
  48291. // One button down
  48292. if (pointA && pointB === null && cacheSoloPointer) {
  48293. if (_this.panningSensibility !== 0 &&
  48294. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48295. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48296. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48297. }
  48298. else {
  48299. var offsetX = evt.clientX - cacheSoloPointer.x;
  48300. var offsetY = evt.clientY - cacheSoloPointer.y;
  48301. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48302. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48303. }
  48304. cacheSoloPointer.x = evt.clientX;
  48305. cacheSoloPointer.y = evt.clientY;
  48306. }
  48307. // Two buttons down: pinch/pan
  48308. else if (pointA && pointB) {
  48309. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48310. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48311. ed.x = evt.clientX;
  48312. ed.y = evt.clientY;
  48313. var direction = _this.pinchInwards ? 1 : -1;
  48314. var distX = pointA.x - pointB.x;
  48315. var distY = pointA.y - pointB.y;
  48316. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48317. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48318. if (previousPinchSquaredDistance === 0) {
  48319. initialDistance = pinchDistance;
  48320. previousPinchSquaredDistance = pinchSquaredDistance;
  48321. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48322. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48323. return;
  48324. }
  48325. if (_this.multiTouchPanAndZoom) {
  48326. if (_this.pinchDeltaPercentage) {
  48327. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48328. }
  48329. else {
  48330. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48331. (_this.pinchPrecision *
  48332. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48333. direction);
  48334. }
  48335. if (_this.panningSensibility !== 0) {
  48336. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48337. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48338. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48339. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48340. previousMultiTouchPanPosition.x = pointersCenterX;
  48341. previousMultiTouchPanPosition.y = pointersCenterY;
  48342. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48343. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48344. }
  48345. }
  48346. else {
  48347. twoFingerActivityCount++;
  48348. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48349. if (_this.pinchDeltaPercentage) {
  48350. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48351. }
  48352. else {
  48353. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48354. (_this.pinchPrecision *
  48355. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48356. direction);
  48357. }
  48358. previousMultiTouchPanPosition.isPaning = false;
  48359. previousMultiTouchPanPosition.isPinching = true;
  48360. }
  48361. else {
  48362. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48363. if (!previousMultiTouchPanPosition.isPaning) {
  48364. previousMultiTouchPanPosition.isPaning = true;
  48365. previousMultiTouchPanPosition.isPinching = false;
  48366. previousMultiTouchPanPosition.x = ed.x;
  48367. previousMultiTouchPanPosition.y = ed.y;
  48368. return;
  48369. }
  48370. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48371. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48372. }
  48373. }
  48374. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48375. previousMultiTouchPanPosition.x = ed.x;
  48376. previousMultiTouchPanPosition.y = ed.y;
  48377. }
  48378. }
  48379. previousPinchSquaredDistance = pinchSquaredDistance;
  48380. }
  48381. }
  48382. };
  48383. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48384. this._onContextMenu = function (evt) {
  48385. evt.preventDefault();
  48386. };
  48387. if (!this.camera._useCtrlForPanning) {
  48388. element.addEventListener("contextmenu", this._onContextMenu, false);
  48389. }
  48390. this._onLostFocus = function () {
  48391. //this._keys = [];
  48392. pointA = pointB = null;
  48393. previousPinchSquaredDistance = 0;
  48394. previousMultiTouchPanPosition.isPaning = false;
  48395. previousMultiTouchPanPosition.isPinching = false;
  48396. twoFingerActivityCount = 0;
  48397. cacheSoloPointer = null;
  48398. initialDistance = 0;
  48399. };
  48400. this._onMouseMove = function (evt) {
  48401. if (!engine.isPointerLock) {
  48402. return;
  48403. }
  48404. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48405. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48406. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48407. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48408. if (!noPreventDefault) {
  48409. evt.preventDefault();
  48410. }
  48411. };
  48412. this._onGestureStart = function (e) {
  48413. if (window.MSGesture === undefined) {
  48414. return;
  48415. }
  48416. if (!_this._MSGestureHandler) {
  48417. _this._MSGestureHandler = new MSGesture();
  48418. _this._MSGestureHandler.target = element;
  48419. }
  48420. _this._MSGestureHandler.addPointer(e.pointerId);
  48421. };
  48422. this._onGesture = function (e) {
  48423. _this.camera.radius *= e.scale;
  48424. if (e.preventDefault) {
  48425. if (!noPreventDefault) {
  48426. e.stopPropagation();
  48427. e.preventDefault();
  48428. }
  48429. }
  48430. };
  48431. element.addEventListener("mousemove", this._onMouseMove, false);
  48432. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48433. element.addEventListener("MSGestureChange", this._onGesture, false);
  48434. BABYLON.Tools.RegisterTopRootEvents([
  48435. { name: "blur", handler: this._onLostFocus }
  48436. ]);
  48437. };
  48438. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48439. if (this._onLostFocus) {
  48440. BABYLON.Tools.UnregisterTopRootEvents([
  48441. { name: "blur", handler: this._onLostFocus }
  48442. ]);
  48443. }
  48444. if (element && this._observer) {
  48445. this.camera.getScene().onPointerObservable.remove(this._observer);
  48446. this._observer = null;
  48447. if (this._onContextMenu) {
  48448. element.removeEventListener("contextmenu", this._onContextMenu);
  48449. }
  48450. if (this._onMouseMove) {
  48451. element.removeEventListener("mousemove", this._onMouseMove);
  48452. }
  48453. if (this._onGestureStart) {
  48454. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48455. }
  48456. if (this._onGesture) {
  48457. element.removeEventListener("MSGestureChange", this._onGesture);
  48458. }
  48459. this._isPanClick = false;
  48460. this.pinchInwards = true;
  48461. this._onMouseMove = null;
  48462. this._onGestureStart = null;
  48463. this._onGesture = null;
  48464. this._MSGestureHandler = null;
  48465. this._onLostFocus = null;
  48466. this._onContextMenu = null;
  48467. }
  48468. };
  48469. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48470. return "ArcRotateCameraPointersInput";
  48471. };
  48472. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48473. return "pointers";
  48474. };
  48475. __decorate([
  48476. BABYLON.serialize()
  48477. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48478. __decorate([
  48479. BABYLON.serialize()
  48480. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48481. __decorate([
  48482. BABYLON.serialize()
  48483. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48484. __decorate([
  48485. BABYLON.serialize()
  48486. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48487. __decorate([
  48488. BABYLON.serialize()
  48489. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48490. __decorate([
  48491. BABYLON.serialize()
  48492. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48493. __decorate([
  48494. BABYLON.serialize()
  48495. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48496. __decorate([
  48497. BABYLON.serialize()
  48498. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48499. return ArcRotateCameraPointersInput;
  48500. }());
  48501. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48502. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48503. })(BABYLON || (BABYLON = {}));
  48504. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48505. var BABYLON;
  48506. (function (BABYLON) {
  48507. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48508. __extends(ArcRotateCameraInputsManager, _super);
  48509. function ArcRotateCameraInputsManager(camera) {
  48510. return _super.call(this, camera) || this;
  48511. }
  48512. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48513. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48514. return this;
  48515. };
  48516. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48517. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48518. return this;
  48519. };
  48520. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48521. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48522. return this;
  48523. };
  48524. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48525. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48526. return this;
  48527. };
  48528. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48529. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48530. return this;
  48531. };
  48532. return ArcRotateCameraInputsManager;
  48533. }(BABYLON.CameraInputsManager));
  48534. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48535. })(BABYLON || (BABYLON = {}));
  48536. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48537. var BABYLON;
  48538. (function (BABYLON) {
  48539. var ArcRotateCamera = /** @class */ (function (_super) {
  48540. __extends(ArcRotateCamera, _super);
  48541. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48542. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48543. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48544. _this.inertialAlphaOffset = 0;
  48545. _this.inertialBetaOffset = 0;
  48546. _this.inertialRadiusOffset = 0;
  48547. _this.lowerAlphaLimit = null;
  48548. _this.upperAlphaLimit = null;
  48549. _this.lowerBetaLimit = 0.01;
  48550. _this.upperBetaLimit = Math.PI;
  48551. _this.lowerRadiusLimit = null;
  48552. _this.upperRadiusLimit = null;
  48553. _this.inertialPanningX = 0;
  48554. _this.inertialPanningY = 0;
  48555. _this.pinchToPanMaxDistance = 20;
  48556. _this.panningDistanceLimit = null;
  48557. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48558. _this.panningInertia = 0.9;
  48559. //-- end properties for backward compatibility for inputs
  48560. _this.zoomOnFactor = 1;
  48561. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48562. _this.allowUpsideDown = true;
  48563. _this._viewMatrix = new BABYLON.Matrix();
  48564. // Panning
  48565. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48566. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48567. _this.checkCollisions = false;
  48568. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48569. _this._previousPosition = BABYLON.Vector3.Zero();
  48570. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48571. _this._newPosition = BABYLON.Vector3.Zero();
  48572. _this._computationVector = BABYLON.Vector3.Zero();
  48573. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48574. if (collidedMesh === void 0) { collidedMesh = null; }
  48575. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48576. newPosition.multiplyInPlace(_this._collider._radius);
  48577. }
  48578. if (!collidedMesh) {
  48579. _this._previousPosition.copyFrom(_this.position);
  48580. }
  48581. else {
  48582. _this.setPosition(newPosition);
  48583. if (_this.onCollide) {
  48584. _this.onCollide(collidedMesh);
  48585. }
  48586. }
  48587. // Recompute because of constraints
  48588. var cosa = Math.cos(_this.alpha);
  48589. var sina = Math.sin(_this.alpha);
  48590. var cosb = Math.cos(_this.beta);
  48591. var sinb = Math.sin(_this.beta);
  48592. if (sinb === 0) {
  48593. sinb = 0.0001;
  48594. }
  48595. var target = _this._getTargetPosition();
  48596. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48597. target.addToRef(_this._computationVector, _this._newPosition);
  48598. _this.position.copyFrom(_this._newPosition);
  48599. var up = _this.upVector;
  48600. if (_this.allowUpsideDown && _this.beta < 0) {
  48601. up = up.clone();
  48602. up = up.negate();
  48603. }
  48604. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48605. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48606. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48607. _this._collisionTriggered = false;
  48608. };
  48609. _this._target = BABYLON.Vector3.Zero();
  48610. if (target) {
  48611. _this.setTarget(target);
  48612. }
  48613. _this.alpha = alpha;
  48614. _this.beta = beta;
  48615. _this.radius = radius;
  48616. _this.getViewMatrix();
  48617. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48618. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48619. return _this;
  48620. }
  48621. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48622. get: function () {
  48623. return this._target;
  48624. },
  48625. set: function (value) {
  48626. this.setTarget(value);
  48627. },
  48628. enumerable: true,
  48629. configurable: true
  48630. });
  48631. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48632. //-- begin properties for backward compatibility for inputs
  48633. get: function () {
  48634. var pointers = this.inputs.attached["pointers"];
  48635. if (pointers)
  48636. return pointers.angularSensibilityX;
  48637. return 0;
  48638. },
  48639. set: function (value) {
  48640. var pointers = this.inputs.attached["pointers"];
  48641. if (pointers) {
  48642. pointers.angularSensibilityX = value;
  48643. }
  48644. },
  48645. enumerable: true,
  48646. configurable: true
  48647. });
  48648. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48649. get: function () {
  48650. var pointers = this.inputs.attached["pointers"];
  48651. if (pointers)
  48652. return pointers.angularSensibilityY;
  48653. return 0;
  48654. },
  48655. set: function (value) {
  48656. var pointers = this.inputs.attached["pointers"];
  48657. if (pointers) {
  48658. pointers.angularSensibilityY = value;
  48659. }
  48660. },
  48661. enumerable: true,
  48662. configurable: true
  48663. });
  48664. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48665. get: function () {
  48666. var pointers = this.inputs.attached["pointers"];
  48667. if (pointers)
  48668. return pointers.pinchPrecision;
  48669. return 0;
  48670. },
  48671. set: function (value) {
  48672. var pointers = this.inputs.attached["pointers"];
  48673. if (pointers) {
  48674. pointers.pinchPrecision = value;
  48675. }
  48676. },
  48677. enumerable: true,
  48678. configurable: true
  48679. });
  48680. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48681. get: function () {
  48682. var pointers = this.inputs.attached["pointers"];
  48683. if (pointers)
  48684. return pointers.pinchDeltaPercentage;
  48685. return 0;
  48686. },
  48687. set: function (value) {
  48688. var pointers = this.inputs.attached["pointers"];
  48689. if (pointers) {
  48690. pointers.pinchDeltaPercentage = value;
  48691. }
  48692. },
  48693. enumerable: true,
  48694. configurable: true
  48695. });
  48696. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48697. get: function () {
  48698. var pointers = this.inputs.attached["pointers"];
  48699. if (pointers)
  48700. return pointers.panningSensibility;
  48701. return 0;
  48702. },
  48703. set: function (value) {
  48704. var pointers = this.inputs.attached["pointers"];
  48705. if (pointers) {
  48706. pointers.panningSensibility = value;
  48707. }
  48708. },
  48709. enumerable: true,
  48710. configurable: true
  48711. });
  48712. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48713. get: function () {
  48714. var keyboard = this.inputs.attached["keyboard"];
  48715. if (keyboard)
  48716. return keyboard.keysUp;
  48717. return [];
  48718. },
  48719. set: function (value) {
  48720. var keyboard = this.inputs.attached["keyboard"];
  48721. if (keyboard)
  48722. keyboard.keysUp = value;
  48723. },
  48724. enumerable: true,
  48725. configurable: true
  48726. });
  48727. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48728. get: function () {
  48729. var keyboard = this.inputs.attached["keyboard"];
  48730. if (keyboard)
  48731. return keyboard.keysDown;
  48732. return [];
  48733. },
  48734. set: function (value) {
  48735. var keyboard = this.inputs.attached["keyboard"];
  48736. if (keyboard)
  48737. keyboard.keysDown = value;
  48738. },
  48739. enumerable: true,
  48740. configurable: true
  48741. });
  48742. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48743. get: function () {
  48744. var keyboard = this.inputs.attached["keyboard"];
  48745. if (keyboard)
  48746. return keyboard.keysLeft;
  48747. return [];
  48748. },
  48749. set: function (value) {
  48750. var keyboard = this.inputs.attached["keyboard"];
  48751. if (keyboard)
  48752. keyboard.keysLeft = value;
  48753. },
  48754. enumerable: true,
  48755. configurable: true
  48756. });
  48757. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48758. get: function () {
  48759. var keyboard = this.inputs.attached["keyboard"];
  48760. if (keyboard)
  48761. return keyboard.keysRight;
  48762. return [];
  48763. },
  48764. set: function (value) {
  48765. var keyboard = this.inputs.attached["keyboard"];
  48766. if (keyboard)
  48767. keyboard.keysRight = value;
  48768. },
  48769. enumerable: true,
  48770. configurable: true
  48771. });
  48772. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48773. get: function () {
  48774. var mousewheel = this.inputs.attached["mousewheel"];
  48775. if (mousewheel)
  48776. return mousewheel.wheelPrecision;
  48777. return 0;
  48778. },
  48779. set: function (value) {
  48780. var mousewheel = this.inputs.attached["mousewheel"];
  48781. if (mousewheel)
  48782. mousewheel.wheelPrecision = value;
  48783. },
  48784. enumerable: true,
  48785. configurable: true
  48786. });
  48787. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48788. get: function () {
  48789. var mousewheel = this.inputs.attached["mousewheel"];
  48790. if (mousewheel)
  48791. return mousewheel.wheelDeltaPercentage;
  48792. return 0;
  48793. },
  48794. set: function (value) {
  48795. var mousewheel = this.inputs.attached["mousewheel"];
  48796. if (mousewheel)
  48797. mousewheel.wheelDeltaPercentage = value;
  48798. },
  48799. enumerable: true,
  48800. configurable: true
  48801. });
  48802. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48803. get: function () {
  48804. return this._bouncingBehavior;
  48805. },
  48806. enumerable: true,
  48807. configurable: true
  48808. });
  48809. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48810. get: function () {
  48811. return this._bouncingBehavior != null;
  48812. },
  48813. set: function (value) {
  48814. if (value === this.useBouncingBehavior) {
  48815. return;
  48816. }
  48817. if (value) {
  48818. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48819. this.addBehavior(this._bouncingBehavior);
  48820. }
  48821. else if (this._bouncingBehavior) {
  48822. this.removeBehavior(this._bouncingBehavior);
  48823. this._bouncingBehavior = null;
  48824. }
  48825. },
  48826. enumerable: true,
  48827. configurable: true
  48828. });
  48829. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48830. get: function () {
  48831. return this._framingBehavior;
  48832. },
  48833. enumerable: true,
  48834. configurable: true
  48835. });
  48836. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48837. get: function () {
  48838. return this._framingBehavior != null;
  48839. },
  48840. set: function (value) {
  48841. if (value === this.useFramingBehavior) {
  48842. return;
  48843. }
  48844. if (value) {
  48845. this._framingBehavior = new BABYLON.FramingBehavior();
  48846. this.addBehavior(this._framingBehavior);
  48847. }
  48848. else if (this._framingBehavior) {
  48849. this.removeBehavior(this._framingBehavior);
  48850. this._framingBehavior = null;
  48851. }
  48852. },
  48853. enumerable: true,
  48854. configurable: true
  48855. });
  48856. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48857. get: function () {
  48858. return this._autoRotationBehavior;
  48859. },
  48860. enumerable: true,
  48861. configurable: true
  48862. });
  48863. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48864. get: function () {
  48865. return this._autoRotationBehavior != null;
  48866. },
  48867. set: function (value) {
  48868. if (value === this.useAutoRotationBehavior) {
  48869. return;
  48870. }
  48871. if (value) {
  48872. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48873. this.addBehavior(this._autoRotationBehavior);
  48874. }
  48875. else if (this._autoRotationBehavior) {
  48876. this.removeBehavior(this._autoRotationBehavior);
  48877. this._autoRotationBehavior = null;
  48878. }
  48879. },
  48880. enumerable: true,
  48881. configurable: true
  48882. });
  48883. // Cache
  48884. ArcRotateCamera.prototype._initCache = function () {
  48885. _super.prototype._initCache.call(this);
  48886. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48887. this._cache.alpha = undefined;
  48888. this._cache.beta = undefined;
  48889. this._cache.radius = undefined;
  48890. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48891. };
  48892. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48893. if (!ignoreParentClass) {
  48894. _super.prototype._updateCache.call(this);
  48895. }
  48896. this._cache._target.copyFrom(this._getTargetPosition());
  48897. this._cache.alpha = this.alpha;
  48898. this._cache.beta = this.beta;
  48899. this._cache.radius = this.radius;
  48900. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48901. };
  48902. ArcRotateCamera.prototype._getTargetPosition = function () {
  48903. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48904. var pos = this._targetHost.getAbsolutePosition();
  48905. if (this._targetBoundingCenter) {
  48906. pos.addToRef(this._targetBoundingCenter, this._target);
  48907. }
  48908. else {
  48909. this._target.copyFrom(pos);
  48910. }
  48911. }
  48912. var lockedTargetPosition = this._getLockedTargetPosition();
  48913. if (lockedTargetPosition) {
  48914. return lockedTargetPosition;
  48915. }
  48916. return this._target;
  48917. };
  48918. ArcRotateCamera.prototype.storeState = function () {
  48919. this._storedAlpha = this.alpha;
  48920. this._storedBeta = this.beta;
  48921. this._storedRadius = this.radius;
  48922. this._storedTarget = this._getTargetPosition().clone();
  48923. return _super.prototype.storeState.call(this);
  48924. };
  48925. /**
  48926. * Restored camera state. You must call storeState() first
  48927. */
  48928. ArcRotateCamera.prototype._restoreStateValues = function () {
  48929. if (!_super.prototype._restoreStateValues.call(this)) {
  48930. return false;
  48931. }
  48932. this.alpha = this._storedAlpha;
  48933. this.beta = this._storedBeta;
  48934. this.radius = this._storedRadius;
  48935. this.setTarget(this._storedTarget.clone());
  48936. this.inertialAlphaOffset = 0;
  48937. this.inertialBetaOffset = 0;
  48938. this.inertialRadiusOffset = 0;
  48939. this.inertialPanningX = 0;
  48940. this.inertialPanningY = 0;
  48941. return true;
  48942. };
  48943. // Synchronized
  48944. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48945. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48946. return false;
  48947. return this._cache._target.equals(this._getTargetPosition())
  48948. && this._cache.alpha === this.alpha
  48949. && this._cache.beta === this.beta
  48950. && this._cache.radius === this.radius
  48951. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48952. };
  48953. // Methods
  48954. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48955. var _this = this;
  48956. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48957. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48958. this._useCtrlForPanning = useCtrlForPanning;
  48959. this._panningMouseButton = panningMouseButton;
  48960. this.inputs.attachElement(element, noPreventDefault);
  48961. this._reset = function () {
  48962. _this.inertialAlphaOffset = 0;
  48963. _this.inertialBetaOffset = 0;
  48964. _this.inertialRadiusOffset = 0;
  48965. _this.inertialPanningX = 0;
  48966. _this.inertialPanningY = 0;
  48967. };
  48968. };
  48969. ArcRotateCamera.prototype.detachControl = function (element) {
  48970. this.inputs.detachElement(element);
  48971. if (this._reset) {
  48972. this._reset();
  48973. }
  48974. };
  48975. ArcRotateCamera.prototype._checkInputs = function () {
  48976. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48977. if (this._collisionTriggered) {
  48978. return;
  48979. }
  48980. this.inputs.checkInputs();
  48981. // Inertia
  48982. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48983. var inertialAlphaOffset = this.inertialAlphaOffset;
  48984. if (this.beta <= 0)
  48985. inertialAlphaOffset *= -1;
  48986. if (this.getScene().useRightHandedSystem)
  48987. inertialAlphaOffset *= -1;
  48988. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48989. inertialAlphaOffset *= -1;
  48990. this.alpha += inertialAlphaOffset;
  48991. this.beta += this.inertialBetaOffset;
  48992. this.radius -= this.inertialRadiusOffset;
  48993. this.inertialAlphaOffset *= this.inertia;
  48994. this.inertialBetaOffset *= this.inertia;
  48995. this.inertialRadiusOffset *= this.inertia;
  48996. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48997. this.inertialAlphaOffset = 0;
  48998. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48999. this.inertialBetaOffset = 0;
  49000. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49001. this.inertialRadiusOffset = 0;
  49002. }
  49003. // Panning inertia
  49004. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49005. if (!this._localDirection) {
  49006. this._localDirection = BABYLON.Vector3.Zero();
  49007. this._transformedDirection = BABYLON.Vector3.Zero();
  49008. }
  49009. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49010. this._localDirection.multiplyInPlace(this.panningAxis);
  49011. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49012. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49013. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49014. if (!this.panningAxis.y) {
  49015. this._transformedDirection.y = 0;
  49016. }
  49017. if (!this._targetHost) {
  49018. if (this.panningDistanceLimit) {
  49019. this._transformedDirection.addInPlace(this._target);
  49020. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49021. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49022. this._target.copyFrom(this._transformedDirection);
  49023. }
  49024. }
  49025. else {
  49026. this._target.addInPlace(this._transformedDirection);
  49027. }
  49028. }
  49029. this.inertialPanningX *= this.panningInertia;
  49030. this.inertialPanningY *= this.panningInertia;
  49031. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49032. this.inertialPanningX = 0;
  49033. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49034. this.inertialPanningY = 0;
  49035. }
  49036. // Limits
  49037. this._checkLimits();
  49038. _super.prototype._checkInputs.call(this);
  49039. };
  49040. ArcRotateCamera.prototype._checkLimits = function () {
  49041. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49042. if (this.allowUpsideDown && this.beta > Math.PI) {
  49043. this.beta = this.beta - (2 * Math.PI);
  49044. }
  49045. }
  49046. else {
  49047. if (this.beta < this.lowerBetaLimit) {
  49048. this.beta = this.lowerBetaLimit;
  49049. }
  49050. }
  49051. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49052. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49053. this.beta = this.beta + (2 * Math.PI);
  49054. }
  49055. }
  49056. else {
  49057. if (this.beta > this.upperBetaLimit) {
  49058. this.beta = this.upperBetaLimit;
  49059. }
  49060. }
  49061. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49062. this.alpha = this.lowerAlphaLimit;
  49063. }
  49064. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49065. this.alpha = this.upperAlphaLimit;
  49066. }
  49067. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49068. this.radius = this.lowerRadiusLimit;
  49069. }
  49070. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49071. this.radius = this.upperRadiusLimit;
  49072. }
  49073. };
  49074. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49075. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49076. this.radius = this._computationVector.length();
  49077. if (this.radius === 0) {
  49078. this.radius = 0.0001; // Just to avoid division by zero
  49079. }
  49080. // Alpha
  49081. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49082. if (this._computationVector.z < 0) {
  49083. this.alpha = 2 * Math.PI - this.alpha;
  49084. }
  49085. // Beta
  49086. this.beta = Math.acos(this._computationVector.y / this.radius);
  49087. this._checkLimits();
  49088. };
  49089. ArcRotateCamera.prototype.setPosition = function (position) {
  49090. if (this.position.equals(position)) {
  49091. return;
  49092. }
  49093. this.position.copyFrom(position);
  49094. this.rebuildAnglesAndRadius();
  49095. };
  49096. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49097. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49098. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49099. if (target.getBoundingInfo) {
  49100. if (toBoundingCenter) {
  49101. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49102. }
  49103. else {
  49104. this._targetBoundingCenter = null;
  49105. }
  49106. this._targetHost = target;
  49107. this._target = this._getTargetPosition();
  49108. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49109. }
  49110. else {
  49111. var newTarget = target;
  49112. var currentTarget = this._getTargetPosition();
  49113. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49114. return;
  49115. }
  49116. this._targetHost = null;
  49117. this._target = newTarget;
  49118. this._targetBoundingCenter = null;
  49119. this.onMeshTargetChangedObservable.notifyObservers(null);
  49120. }
  49121. this.rebuildAnglesAndRadius();
  49122. };
  49123. ArcRotateCamera.prototype._getViewMatrix = function () {
  49124. // Compute
  49125. var cosa = Math.cos(this.alpha);
  49126. var sina = Math.sin(this.alpha);
  49127. var cosb = Math.cos(this.beta);
  49128. var sinb = Math.sin(this.beta);
  49129. if (sinb === 0) {
  49130. sinb = 0.0001;
  49131. }
  49132. var target = this._getTargetPosition();
  49133. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49134. target.addToRef(this._computationVector, this._newPosition);
  49135. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49136. if (!this._collider) {
  49137. this._collider = new BABYLON.Collider();
  49138. }
  49139. this._collider._radius = this.collisionRadius;
  49140. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49141. this._collisionTriggered = true;
  49142. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49143. }
  49144. else {
  49145. this.position.copyFrom(this._newPosition);
  49146. var up = this.upVector;
  49147. if (this.allowUpsideDown && sinb < 0) {
  49148. up = up.clone();
  49149. up = up.negate();
  49150. }
  49151. this._computeViewMatrix(this.position, target, up);
  49152. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49153. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49154. }
  49155. this._currentTarget = target;
  49156. return this._viewMatrix;
  49157. };
  49158. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49159. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49160. meshes = meshes || this.getScene().meshes;
  49161. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49162. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49163. this.radius = distance * this.zoomOnFactor;
  49164. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49165. };
  49166. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49167. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49168. var meshesOrMinMaxVector;
  49169. var distance;
  49170. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49171. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49172. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49173. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49174. }
  49175. else { //minMaxVector and distance
  49176. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49177. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49178. distance = minMaxVectorAndDistance.distance;
  49179. }
  49180. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49181. if (!doNotUpdateMaxZ) {
  49182. this.maxZ = distance * 2;
  49183. }
  49184. };
  49185. /**
  49186. * @override
  49187. * Override Camera.createRigCamera
  49188. */
  49189. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49190. var alphaShift = 0;
  49191. switch (this.cameraRigMode) {
  49192. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49193. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49194. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49195. case BABYLON.Camera.RIG_MODE_VR:
  49196. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49197. break;
  49198. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49199. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49200. break;
  49201. }
  49202. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49203. rigCam._cameraRigParams = {};
  49204. return rigCam;
  49205. };
  49206. /**
  49207. * @override
  49208. * Override Camera._updateRigCameras
  49209. */
  49210. ArcRotateCamera.prototype._updateRigCameras = function () {
  49211. var camLeft = this._rigCameras[0];
  49212. var camRight = this._rigCameras[1];
  49213. camLeft.beta = camRight.beta = this.beta;
  49214. camLeft.radius = camRight.radius = this.radius;
  49215. switch (this.cameraRigMode) {
  49216. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49217. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49218. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49219. case BABYLON.Camera.RIG_MODE_VR:
  49220. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49221. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49222. break;
  49223. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49224. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49225. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49226. break;
  49227. }
  49228. _super.prototype._updateRigCameras.call(this);
  49229. };
  49230. ArcRotateCamera.prototype.dispose = function () {
  49231. this.inputs.clear();
  49232. _super.prototype.dispose.call(this);
  49233. };
  49234. ArcRotateCamera.prototype.getClassName = function () {
  49235. return "ArcRotateCamera";
  49236. };
  49237. __decorate([
  49238. BABYLON.serialize()
  49239. ], ArcRotateCamera.prototype, "alpha", void 0);
  49240. __decorate([
  49241. BABYLON.serialize()
  49242. ], ArcRotateCamera.prototype, "beta", void 0);
  49243. __decorate([
  49244. BABYLON.serialize()
  49245. ], ArcRotateCamera.prototype, "radius", void 0);
  49246. __decorate([
  49247. BABYLON.serializeAsVector3("target")
  49248. ], ArcRotateCamera.prototype, "_target", void 0);
  49249. __decorate([
  49250. BABYLON.serialize()
  49251. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49252. __decorate([
  49253. BABYLON.serialize()
  49254. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49255. __decorate([
  49256. BABYLON.serialize()
  49257. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49258. __decorate([
  49259. BABYLON.serialize()
  49260. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49261. __decorate([
  49262. BABYLON.serialize()
  49263. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49264. __decorate([
  49265. BABYLON.serialize()
  49266. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49267. __decorate([
  49268. BABYLON.serialize()
  49269. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49270. __decorate([
  49271. BABYLON.serialize()
  49272. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49273. __decorate([
  49274. BABYLON.serialize()
  49275. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49276. __decorate([
  49277. BABYLON.serialize()
  49278. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49279. __decorate([
  49280. BABYLON.serialize()
  49281. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49282. __decorate([
  49283. BABYLON.serialize()
  49284. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49285. __decorate([
  49286. BABYLON.serialize()
  49287. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49288. __decorate([
  49289. BABYLON.serializeAsVector3()
  49290. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49291. __decorate([
  49292. BABYLON.serialize()
  49293. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49294. __decorate([
  49295. BABYLON.serialize()
  49296. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49297. __decorate([
  49298. BABYLON.serialize()
  49299. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49300. return ArcRotateCamera;
  49301. }(BABYLON.TargetCamera));
  49302. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49303. })(BABYLON || (BABYLON = {}));
  49304. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49305. var BABYLON;
  49306. (function (BABYLON) {
  49307. /**
  49308. * The HemisphericLight simulates the ambient environment light,
  49309. * so the passed direction is the light reflection direction, not the incoming direction.
  49310. */
  49311. var HemisphericLight = /** @class */ (function (_super) {
  49312. __extends(HemisphericLight, _super);
  49313. /**
  49314. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49315. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49316. * The HemisphericLight can't cast shadows.
  49317. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49318. * @param name The friendly name of the light
  49319. * @param direction The direction of the light reflection
  49320. * @param scene The scene the light belongs to
  49321. */
  49322. function HemisphericLight(name, direction, scene) {
  49323. var _this = _super.call(this, name, scene) || this;
  49324. /**
  49325. * The groundColor is the light in the opposite direction to the one specified during creation.
  49326. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  49327. */
  49328. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49329. _this.direction = direction || BABYLON.Vector3.Up();
  49330. return _this;
  49331. }
  49332. HemisphericLight.prototype._buildUniformLayout = function () {
  49333. this._uniformBuffer.addUniform("vLightData", 4);
  49334. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49335. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49336. this._uniformBuffer.addUniform("vLightGround", 3);
  49337. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49338. this._uniformBuffer.addUniform("depthValues", 2);
  49339. this._uniformBuffer.create();
  49340. };
  49341. /**
  49342. * Returns the string "HemisphericLight".
  49343. * @return The class name
  49344. */
  49345. HemisphericLight.prototype.getClassName = function () {
  49346. return "HemisphericLight";
  49347. };
  49348. /**
  49349. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49350. * Returns the updated direction.
  49351. * @param target The target the direction should point to
  49352. * @return The computed direction
  49353. */
  49354. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49355. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49356. return this.direction;
  49357. };
  49358. /**
  49359. * Returns the shadow generator associated to the light.
  49360. * @returns Always null for hemispheric lights because it does not support shadows.
  49361. */
  49362. HemisphericLight.prototype.getShadowGenerator = function () {
  49363. return null;
  49364. };
  49365. /**
  49366. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49367. * @param effect The effect to update
  49368. * @param lightIndex The index of the light in the effect to update
  49369. * @returns The hemispheric light
  49370. */
  49371. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49372. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49373. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49374. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49375. return this;
  49376. };
  49377. /**
  49378. * @hidden internal use only.
  49379. */
  49380. HemisphericLight.prototype._getWorldMatrix = function () {
  49381. if (!this._worldMatrix) {
  49382. this._worldMatrix = BABYLON.Matrix.Identity();
  49383. }
  49384. return this._worldMatrix;
  49385. };
  49386. /**
  49387. * Returns the integer 3.
  49388. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49389. */
  49390. HemisphericLight.prototype.getTypeID = function () {
  49391. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49392. };
  49393. __decorate([
  49394. BABYLON.serializeAsColor3()
  49395. ], HemisphericLight.prototype, "groundColor", void 0);
  49396. __decorate([
  49397. BABYLON.serializeAsVector3()
  49398. ], HemisphericLight.prototype, "direction", void 0);
  49399. return HemisphericLight;
  49400. }(BABYLON.Light));
  49401. BABYLON.HemisphericLight = HemisphericLight;
  49402. })(BABYLON || (BABYLON = {}));
  49403. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49404. var BABYLON;
  49405. (function (BABYLON) {
  49406. /**
  49407. * Base implementation IShadowLight
  49408. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49409. */
  49410. var ShadowLight = /** @class */ (function (_super) {
  49411. __extends(ShadowLight, _super);
  49412. function ShadowLight() {
  49413. var _this = _super !== null && _super.apply(this, arguments) || this;
  49414. _this._needProjectionMatrixCompute = true;
  49415. return _this;
  49416. }
  49417. ShadowLight.prototype._setPosition = function (value) {
  49418. this._position = value;
  49419. };
  49420. Object.defineProperty(ShadowLight.prototype, "position", {
  49421. /**
  49422. * Sets the position the shadow will be casted from. Also use as the light position for both
  49423. * point and spot lights.
  49424. */
  49425. get: function () {
  49426. return this._position;
  49427. },
  49428. /**
  49429. * Sets the position the shadow will be casted from. Also use as the light position for both
  49430. * point and spot lights.
  49431. */
  49432. set: function (value) {
  49433. this._setPosition(value);
  49434. },
  49435. enumerable: true,
  49436. configurable: true
  49437. });
  49438. ShadowLight.prototype._setDirection = function (value) {
  49439. this._direction = value;
  49440. };
  49441. Object.defineProperty(ShadowLight.prototype, "direction", {
  49442. /**
  49443. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49444. * Also use as the light direction on spot and directional lights.
  49445. */
  49446. get: function () {
  49447. return this._direction;
  49448. },
  49449. /**
  49450. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49451. * Also use as the light direction on spot and directional lights.
  49452. */
  49453. set: function (value) {
  49454. this._setDirection(value);
  49455. },
  49456. enumerable: true,
  49457. configurable: true
  49458. });
  49459. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49460. /**
  49461. * Gets the shadow projection clipping minimum z value.
  49462. */
  49463. get: function () {
  49464. return this._shadowMinZ;
  49465. },
  49466. /**
  49467. * Sets the shadow projection clipping minimum z value.
  49468. */
  49469. set: function (value) {
  49470. this._shadowMinZ = value;
  49471. this.forceProjectionMatrixCompute();
  49472. },
  49473. enumerable: true,
  49474. configurable: true
  49475. });
  49476. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49477. /**
  49478. * Sets the shadow projection clipping maximum z value.
  49479. */
  49480. get: function () {
  49481. return this._shadowMaxZ;
  49482. },
  49483. /**
  49484. * Gets the shadow projection clipping maximum z value.
  49485. */
  49486. set: function (value) {
  49487. this._shadowMaxZ = value;
  49488. this.forceProjectionMatrixCompute();
  49489. },
  49490. enumerable: true,
  49491. configurable: true
  49492. });
  49493. /**
  49494. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49495. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49496. */
  49497. ShadowLight.prototype.computeTransformedInformation = function () {
  49498. if (this.parent && this.parent.getWorldMatrix) {
  49499. if (!this.transformedPosition) {
  49500. this.transformedPosition = BABYLON.Vector3.Zero();
  49501. }
  49502. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49503. // In case the direction is present.
  49504. if (this.direction) {
  49505. if (!this.transformedDirection) {
  49506. this.transformedDirection = BABYLON.Vector3.Zero();
  49507. }
  49508. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49509. }
  49510. return true;
  49511. }
  49512. return false;
  49513. };
  49514. /**
  49515. * Return the depth scale used for the shadow map.
  49516. * @returns the depth scale.
  49517. */
  49518. ShadowLight.prototype.getDepthScale = function () {
  49519. return 50.0;
  49520. };
  49521. /**
  49522. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49523. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49524. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49525. */
  49526. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49527. return this.transformedDirection ? this.transformedDirection : this.direction;
  49528. };
  49529. /**
  49530. * Returns the ShadowLight absolute position in the World.
  49531. * @returns the position vector in world space
  49532. */
  49533. ShadowLight.prototype.getAbsolutePosition = function () {
  49534. return this.transformedPosition ? this.transformedPosition : this.position;
  49535. };
  49536. /**
  49537. * Sets the ShadowLight direction toward the passed target.
  49538. * @param target The point tot target in local space
  49539. * @returns the updated ShadowLight direction
  49540. */
  49541. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49542. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49543. return this.direction;
  49544. };
  49545. /**
  49546. * Returns the light rotation in euler definition.
  49547. * @returns the x y z rotation in local space.
  49548. */
  49549. ShadowLight.prototype.getRotation = function () {
  49550. this.direction.normalize();
  49551. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49552. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49553. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49554. };
  49555. /**
  49556. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49557. * @returns true if a cube texture needs to be use
  49558. */
  49559. ShadowLight.prototype.needCube = function () {
  49560. return false;
  49561. };
  49562. /**
  49563. * Detects if the projection matrix requires to be recomputed this frame.
  49564. * @returns true if it requires to be recomputed otherwise, false.
  49565. */
  49566. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49567. return this._needProjectionMatrixCompute;
  49568. };
  49569. /**
  49570. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49571. */
  49572. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49573. this._needProjectionMatrixCompute = true;
  49574. };
  49575. /**
  49576. * Get the world matrix of the sahdow lights.
  49577. * @hidden Internal Use Only
  49578. */
  49579. ShadowLight.prototype._getWorldMatrix = function () {
  49580. if (!this._worldMatrix) {
  49581. this._worldMatrix = BABYLON.Matrix.Identity();
  49582. }
  49583. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49584. return this._worldMatrix;
  49585. };
  49586. /**
  49587. * Gets the minZ used for shadow according to both the scene and the light.
  49588. * @param activeCamera The camera we are returning the min for
  49589. * @returns the depth min z
  49590. */
  49591. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49592. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49593. };
  49594. /**
  49595. * Gets the maxZ used for shadow according to both the scene and the light.
  49596. * @param activeCamera The camera we are returning the max for
  49597. * @returns the depth max z
  49598. */
  49599. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49600. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49601. };
  49602. /**
  49603. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49604. * @param matrix The materix to updated with the projection information
  49605. * @param viewMatrix The transform matrix of the light
  49606. * @param renderList The list of mesh to render in the map
  49607. * @returns The current light
  49608. */
  49609. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49610. if (this.customProjectionMatrixBuilder) {
  49611. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49612. }
  49613. else {
  49614. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49615. }
  49616. return this;
  49617. };
  49618. __decorate([
  49619. BABYLON.serializeAsVector3()
  49620. ], ShadowLight.prototype, "position", null);
  49621. __decorate([
  49622. BABYLON.serializeAsVector3()
  49623. ], ShadowLight.prototype, "direction", null);
  49624. __decorate([
  49625. BABYLON.serialize()
  49626. ], ShadowLight.prototype, "shadowMinZ", null);
  49627. __decorate([
  49628. BABYLON.serialize()
  49629. ], ShadowLight.prototype, "shadowMaxZ", null);
  49630. return ShadowLight;
  49631. }(BABYLON.Light));
  49632. BABYLON.ShadowLight = ShadowLight;
  49633. })(BABYLON || (BABYLON = {}));
  49634. //# sourceMappingURL=babylon.shadowLight.js.map
  49635. var BABYLON;
  49636. (function (BABYLON) {
  49637. /**
  49638. * A point light is a light defined by an unique point in world space.
  49639. * The light is emitted in every direction from this point.
  49640. * A good example of a point light is a standard light bulb.
  49641. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49642. */
  49643. var PointLight = /** @class */ (function (_super) {
  49644. __extends(PointLight, _super);
  49645. /**
  49646. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49647. * A PointLight emits the light in every direction.
  49648. * It can cast shadows.
  49649. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49650. * ```javascript
  49651. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49652. * ```
  49653. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49654. * @param name The light friendly name
  49655. * @param position The position of the point light in the scene
  49656. * @param scene The scene the lights belongs to
  49657. */
  49658. function PointLight(name, position, scene) {
  49659. var _this = _super.call(this, name, scene) || this;
  49660. _this._shadowAngle = Math.PI / 2;
  49661. _this.position = position;
  49662. return _this;
  49663. }
  49664. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49665. /**
  49666. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49667. * This specifies what angle the shadow will use to be created.
  49668. *
  49669. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49670. */
  49671. get: function () {
  49672. return this._shadowAngle;
  49673. },
  49674. /**
  49675. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49676. * This specifies what angle the shadow will use to be created.
  49677. *
  49678. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49679. */
  49680. set: function (value) {
  49681. this._shadowAngle = value;
  49682. this.forceProjectionMatrixCompute();
  49683. },
  49684. enumerable: true,
  49685. configurable: true
  49686. });
  49687. Object.defineProperty(PointLight.prototype, "direction", {
  49688. /**
  49689. * Gets the direction if it has been set.
  49690. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49691. */
  49692. get: function () {
  49693. return this._direction;
  49694. },
  49695. /**
  49696. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49697. */
  49698. set: function (value) {
  49699. var previousNeedCube = this.needCube();
  49700. this._direction = value;
  49701. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49702. this._shadowGenerator.recreateShadowMap();
  49703. }
  49704. },
  49705. enumerable: true,
  49706. configurable: true
  49707. });
  49708. /**
  49709. * Returns the string "PointLight"
  49710. * @returns the class name
  49711. */
  49712. PointLight.prototype.getClassName = function () {
  49713. return "PointLight";
  49714. };
  49715. /**
  49716. * Returns the integer 0.
  49717. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49718. */
  49719. PointLight.prototype.getTypeID = function () {
  49720. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49721. };
  49722. /**
  49723. * Specifies wether or not the shadowmap should be a cube texture.
  49724. * @returns true if the shadowmap needs to be a cube texture.
  49725. */
  49726. PointLight.prototype.needCube = function () {
  49727. return !this.direction;
  49728. };
  49729. /**
  49730. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49731. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49732. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49733. */
  49734. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49735. if (this.direction) {
  49736. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49737. }
  49738. else {
  49739. switch (faceIndex) {
  49740. case 0:
  49741. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49742. case 1:
  49743. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49744. case 2:
  49745. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49746. case 3:
  49747. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49748. case 4:
  49749. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49750. case 5:
  49751. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49752. }
  49753. }
  49754. return BABYLON.Vector3.Zero();
  49755. };
  49756. /**
  49757. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49758. * - fov = PI / 2
  49759. * - aspect ratio : 1.0
  49760. * - z-near and far equal to the active camera minZ and maxZ.
  49761. * Returns the PointLight.
  49762. */
  49763. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49764. var activeCamera = this.getScene().activeCamera;
  49765. if (!activeCamera) {
  49766. return;
  49767. }
  49768. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49769. };
  49770. PointLight.prototype._buildUniformLayout = function () {
  49771. this._uniformBuffer.addUniform("vLightData", 4);
  49772. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49773. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49774. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49775. this._uniformBuffer.addUniform("depthValues", 2);
  49776. this._uniformBuffer.create();
  49777. };
  49778. /**
  49779. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49780. * @param effect The effect to update
  49781. * @param lightIndex The index of the light in the effect to update
  49782. * @returns The point light
  49783. */
  49784. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49785. if (this.computeTransformedInformation()) {
  49786. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49787. return this;
  49788. }
  49789. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49790. return this;
  49791. };
  49792. __decorate([
  49793. BABYLON.serialize()
  49794. ], PointLight.prototype, "shadowAngle", null);
  49795. return PointLight;
  49796. }(BABYLON.ShadowLight));
  49797. BABYLON.PointLight = PointLight;
  49798. })(BABYLON || (BABYLON = {}));
  49799. //# sourceMappingURL=babylon.pointLight.js.map
  49800. var BABYLON;
  49801. (function (BABYLON) {
  49802. /**
  49803. * A directional light is defined by a direction (what a surprise!).
  49804. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49805. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  49806. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49807. */
  49808. var DirectionalLight = /** @class */ (function (_super) {
  49809. __extends(DirectionalLight, _super);
  49810. /**
  49811. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49812. * The directional light is emitted from everywhere in the given direction.
  49813. * It can cast shawdows.
  49814. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49815. * @param name The friendly name of the light
  49816. * @param direction The direction of the light
  49817. * @param scene The scene the light belongs to
  49818. */
  49819. function DirectionalLight(name, direction, scene) {
  49820. var _this = _super.call(this, name, scene) || this;
  49821. _this._shadowFrustumSize = 0;
  49822. _this._shadowOrthoScale = 0.1;
  49823. /**
  49824. * Automatically compute the projection matrix to best fit (including all the casters)
  49825. * on each frame.
  49826. */
  49827. _this.autoUpdateExtends = true;
  49828. // Cache
  49829. _this._orthoLeft = Number.MAX_VALUE;
  49830. _this._orthoRight = Number.MIN_VALUE;
  49831. _this._orthoTop = Number.MIN_VALUE;
  49832. _this._orthoBottom = Number.MAX_VALUE;
  49833. _this.position = direction.scale(-1.0);
  49834. _this.direction = direction;
  49835. return _this;
  49836. }
  49837. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49838. /**
  49839. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49840. */
  49841. get: function () {
  49842. return this._shadowFrustumSize;
  49843. },
  49844. /**
  49845. * Specifies a fix frustum size for the shadow generation.
  49846. */
  49847. set: function (value) {
  49848. this._shadowFrustumSize = value;
  49849. this.forceProjectionMatrixCompute();
  49850. },
  49851. enumerable: true,
  49852. configurable: true
  49853. });
  49854. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49855. /**
  49856. * Gets the shadow projection scale against the optimal computed one.
  49857. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49858. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49859. */
  49860. get: function () {
  49861. return this._shadowOrthoScale;
  49862. },
  49863. /**
  49864. * Sets the shadow projection scale against the optimal computed one.
  49865. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49866. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49867. */
  49868. set: function (value) {
  49869. this._shadowOrthoScale = value;
  49870. this.forceProjectionMatrixCompute();
  49871. },
  49872. enumerable: true,
  49873. configurable: true
  49874. });
  49875. /**
  49876. * Returns the string "DirectionalLight".
  49877. * @return The class name
  49878. */
  49879. DirectionalLight.prototype.getClassName = function () {
  49880. return "DirectionalLight";
  49881. };
  49882. /**
  49883. * Returns the integer 1.
  49884. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49885. */
  49886. DirectionalLight.prototype.getTypeID = function () {
  49887. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49888. };
  49889. /**
  49890. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49891. * Returns the DirectionalLight Shadow projection matrix.
  49892. */
  49893. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49894. if (this.shadowFrustumSize > 0) {
  49895. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49896. }
  49897. else {
  49898. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49899. }
  49900. };
  49901. /**
  49902. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49903. * Returns the DirectionalLight Shadow projection matrix.
  49904. */
  49905. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49906. var activeCamera = this.getScene().activeCamera;
  49907. if (!activeCamera) {
  49908. return;
  49909. }
  49910. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49911. };
  49912. /**
  49913. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49914. * Returns the DirectionalLight Shadow projection matrix.
  49915. */
  49916. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49917. var activeCamera = this.getScene().activeCamera;
  49918. if (!activeCamera) {
  49919. return;
  49920. }
  49921. // Check extends
  49922. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49923. var tempVector3 = BABYLON.Vector3.Zero();
  49924. this._orthoLeft = Number.MAX_VALUE;
  49925. this._orthoRight = Number.MIN_VALUE;
  49926. this._orthoTop = Number.MIN_VALUE;
  49927. this._orthoBottom = Number.MAX_VALUE;
  49928. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49929. var mesh = renderList[meshIndex];
  49930. if (!mesh) {
  49931. continue;
  49932. }
  49933. var boundingInfo = mesh.getBoundingInfo();
  49934. var boundingBox = boundingInfo.boundingBox;
  49935. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49936. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49937. if (tempVector3.x < this._orthoLeft)
  49938. this._orthoLeft = tempVector3.x;
  49939. if (tempVector3.y < this._orthoBottom)
  49940. this._orthoBottom = tempVector3.y;
  49941. if (tempVector3.x > this._orthoRight)
  49942. this._orthoRight = tempVector3.x;
  49943. if (tempVector3.y > this._orthoTop)
  49944. this._orthoTop = tempVector3.y;
  49945. }
  49946. }
  49947. }
  49948. var xOffset = this._orthoRight - this._orthoLeft;
  49949. var yOffset = this._orthoTop - this._orthoBottom;
  49950. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49951. };
  49952. DirectionalLight.prototype._buildUniformLayout = function () {
  49953. this._uniformBuffer.addUniform("vLightData", 4);
  49954. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49955. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49956. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49957. this._uniformBuffer.addUniform("depthValues", 2);
  49958. this._uniformBuffer.create();
  49959. };
  49960. /**
  49961. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49962. * @param effect The effect to update
  49963. * @param lightIndex The index of the light in the effect to update
  49964. * @returns The directional light
  49965. */
  49966. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49967. if (this.computeTransformedInformation()) {
  49968. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49969. return this;
  49970. }
  49971. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49972. return this;
  49973. };
  49974. /**
  49975. * Gets the minZ used for shadow according to both the scene and the light.
  49976. *
  49977. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49978. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49979. * @param activeCamera The camera we are returning the min for
  49980. * @returns the depth min z
  49981. */
  49982. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49983. return 1;
  49984. };
  49985. /**
  49986. * Gets the maxZ used for shadow according to both the scene and the light.
  49987. *
  49988. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49989. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49990. * @param activeCamera The camera we are returning the max for
  49991. * @returns the depth max z
  49992. */
  49993. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49994. return 1;
  49995. };
  49996. __decorate([
  49997. BABYLON.serialize()
  49998. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49999. __decorate([
  50000. BABYLON.serialize()
  50001. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50002. __decorate([
  50003. BABYLON.serialize()
  50004. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50005. return DirectionalLight;
  50006. }(BABYLON.ShadowLight));
  50007. BABYLON.DirectionalLight = DirectionalLight;
  50008. })(BABYLON || (BABYLON = {}));
  50009. //# sourceMappingURL=babylon.directionalLight.js.map
  50010. var BABYLON;
  50011. (function (BABYLON) {
  50012. /**
  50013. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50014. * These values define a cone of light starting from the position, emitting toward the direction.
  50015. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50016. * and the exponent defines the speed of the decay of the light with distance (reach).
  50017. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50018. */
  50019. var SpotLight = /** @class */ (function (_super) {
  50020. __extends(SpotLight, _super);
  50021. /**
  50022. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50023. * It can cast shadows.
  50024. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50025. * @param name The light friendly name
  50026. * @param position The position of the spot light in the scene
  50027. * @param direction The direction of the light in the scene
  50028. * @param angle The cone angle of the light in Radians
  50029. * @param exponent The light decay speed with the distance from the emission spot
  50030. * @param scene The scene the lights belongs to
  50031. */
  50032. function SpotLight(name, position, direction, angle, exponent, scene) {
  50033. var _this = _super.call(this, name, scene) || this;
  50034. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50035. _this._projectionTextureLightNear = 1e-6;
  50036. _this._projectionTextureLightFar = 1000.0;
  50037. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50038. _this._projectionTextureViewLightDirty = true;
  50039. _this._projectionTextureProjectionLightDirty = true;
  50040. _this._projectionTextureDirty = true;
  50041. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50042. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50043. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50044. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  50045. _this.position = position;
  50046. _this.direction = direction;
  50047. _this.angle = angle;
  50048. _this.exponent = exponent;
  50049. return _this;
  50050. }
  50051. Object.defineProperty(SpotLight.prototype, "angle", {
  50052. /**
  50053. * Gets the cone angle of the spot light in Radians.
  50054. */
  50055. get: function () {
  50056. return this._angle;
  50057. },
  50058. /**
  50059. * Sets the cone angle of the spot light in Radians.
  50060. */
  50061. set: function (value) {
  50062. this._angle = value;
  50063. this._projectionTextureProjectionLightDirty = true;
  50064. this.forceProjectionMatrixCompute();
  50065. },
  50066. enumerable: true,
  50067. configurable: true
  50068. });
  50069. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50070. /**
  50071. * Allows scaling the angle of the light for shadow generation only.
  50072. */
  50073. get: function () {
  50074. return this._shadowAngleScale;
  50075. },
  50076. /**
  50077. * Allows scaling the angle of the light for shadow generation only.
  50078. */
  50079. set: function (value) {
  50080. this._shadowAngleScale = value;
  50081. this.forceProjectionMatrixCompute();
  50082. },
  50083. enumerable: true,
  50084. configurable: true
  50085. });
  50086. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50087. /**
  50088. * Allows reading the projecton texture
  50089. */
  50090. get: function () {
  50091. return this._projectionTextureMatrix;
  50092. },
  50093. enumerable: true,
  50094. configurable: true
  50095. });
  50096. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50097. /**
  50098. * Gets the near clip of the Spotlight for texture projection.
  50099. */
  50100. get: function () {
  50101. return this._projectionTextureLightNear;
  50102. },
  50103. /**
  50104. * Sets the near clip of the Spotlight for texture projection.
  50105. */
  50106. set: function (value) {
  50107. this._projectionTextureLightNear = value;
  50108. this._projectionTextureProjectionLightDirty = true;
  50109. },
  50110. enumerable: true,
  50111. configurable: true
  50112. });
  50113. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50114. /**
  50115. * Gets the far clip of the Spotlight for texture projection.
  50116. */
  50117. get: function () {
  50118. return this._projectionTextureLightFar;
  50119. },
  50120. /**
  50121. * Sets the far clip of the Spotlight for texture projection.
  50122. */
  50123. set: function (value) {
  50124. this._projectionTextureLightFar = value;
  50125. this._projectionTextureProjectionLightDirty = true;
  50126. },
  50127. enumerable: true,
  50128. configurable: true
  50129. });
  50130. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50131. /**
  50132. * Gets the Up vector of the Spotlight for texture projection.
  50133. */
  50134. get: function () {
  50135. return this._projectionTextureUpDirection;
  50136. },
  50137. /**
  50138. * Sets the Up vector of the Spotlight for texture projection.
  50139. */
  50140. set: function (value) {
  50141. this._projectionTextureUpDirection = value;
  50142. this._projectionTextureProjectionLightDirty = true;
  50143. },
  50144. enumerable: true,
  50145. configurable: true
  50146. });
  50147. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50148. /**
  50149. * Gets the projection texture of the light.
  50150. */
  50151. get: function () {
  50152. return this._projectionTexture;
  50153. },
  50154. /**
  50155. * Sets the projection texture of the light.
  50156. */
  50157. set: function (value) {
  50158. this._projectionTexture = value;
  50159. this._projectionTextureDirty = true;
  50160. },
  50161. enumerable: true,
  50162. configurable: true
  50163. });
  50164. /**
  50165. * Returns the string "SpotLight".
  50166. * @returns the class name
  50167. */
  50168. SpotLight.prototype.getClassName = function () {
  50169. return "SpotLight";
  50170. };
  50171. /**
  50172. * Returns the integer 2.
  50173. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50174. */
  50175. SpotLight.prototype.getTypeID = function () {
  50176. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50177. };
  50178. /**
  50179. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50180. */
  50181. SpotLight.prototype._setDirection = function (value) {
  50182. _super.prototype._setDirection.call(this, value);
  50183. this._projectionTextureViewLightDirty = true;
  50184. };
  50185. /**
  50186. * Overrides the position setter to recompute the projection texture view light Matrix.
  50187. */
  50188. SpotLight.prototype._setPosition = function (value) {
  50189. _super.prototype._setPosition.call(this, value);
  50190. this._projectionTextureViewLightDirty = true;
  50191. };
  50192. /**
  50193. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  50194. * Returns the SpotLight.
  50195. */
  50196. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50197. var activeCamera = this.getScene().activeCamera;
  50198. if (!activeCamera) {
  50199. return;
  50200. }
  50201. this._shadowAngleScale = this._shadowAngleScale || 1;
  50202. var angle = this._shadowAngleScale * this._angle;
  50203. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50204. };
  50205. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50206. this._projectionTextureViewLightDirty = false;
  50207. this._projectionTextureDirty = true;
  50208. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50209. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50210. };
  50211. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50212. this._projectionTextureProjectionLightDirty = false;
  50213. this._projectionTextureDirty = true;
  50214. var light_far = this.projectionTextureLightFar;
  50215. var light_near = this.projectionTextureLightNear;
  50216. var P = light_far / (light_far - light_near);
  50217. var Q = -P * light_near;
  50218. var S = 1.0 / Math.tan(this._angle / 2.0);
  50219. var A = 1.0;
  50220. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  50221. };
  50222. /**
  50223. * Main function for light texture projection matrix computing.
  50224. */
  50225. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50226. this._projectionTextureDirty = false;
  50227. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50228. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50229. };
  50230. SpotLight.prototype._buildUniformLayout = function () {
  50231. this._uniformBuffer.addUniform("vLightData", 4);
  50232. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50233. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50234. this._uniformBuffer.addUniform("vLightDirection", 3);
  50235. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50236. this._uniformBuffer.addUniform("depthValues", 2);
  50237. this._uniformBuffer.create();
  50238. };
  50239. /**
  50240. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50241. * @param effect The effect to update
  50242. * @param lightIndex The index of the light in the effect to update
  50243. * @returns The spot light
  50244. */
  50245. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50246. var normalizeDirection;
  50247. if (this.computeTransformedInformation()) {
  50248. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50249. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50250. }
  50251. else {
  50252. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50253. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50254. }
  50255. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50256. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50257. if (this._projectionTextureViewLightDirty) {
  50258. this._computeProjectionTextureViewLightMatrix();
  50259. }
  50260. if (this._projectionTextureProjectionLightDirty) {
  50261. this._computeProjectionTextureProjectionLightMatrix();
  50262. }
  50263. if (this._projectionTextureDirty) {
  50264. this._computeProjectionTextureMatrix();
  50265. }
  50266. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50267. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50268. }
  50269. return this;
  50270. };
  50271. /**
  50272. * Disposes the light and the associated resources.
  50273. */
  50274. SpotLight.prototype.dispose = function () {
  50275. _super.prototype.dispose.call(this);
  50276. if (this._projectionTexture) {
  50277. this._projectionTexture.dispose();
  50278. }
  50279. };
  50280. __decorate([
  50281. BABYLON.serialize()
  50282. ], SpotLight.prototype, "angle", null);
  50283. __decorate([
  50284. BABYLON.serialize()
  50285. ], SpotLight.prototype, "shadowAngleScale", null);
  50286. __decorate([
  50287. BABYLON.serialize()
  50288. ], SpotLight.prototype, "exponent", void 0);
  50289. __decorate([
  50290. BABYLON.serialize()
  50291. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50292. __decorate([
  50293. BABYLON.serialize()
  50294. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50295. __decorate([
  50296. BABYLON.serialize()
  50297. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50298. __decorate([
  50299. BABYLON.serializeAsTexture("projectedLightTexture")
  50300. ], SpotLight.prototype, "_projectionTexture", void 0);
  50301. return SpotLight;
  50302. }(BABYLON.ShadowLight));
  50303. BABYLON.SpotLight = SpotLight;
  50304. })(BABYLON || (BABYLON = {}));
  50305. //# sourceMappingURL=babylon.spotLight.js.map
  50306. var BABYLON;
  50307. (function (BABYLON) {
  50308. /**
  50309. * Class used to override all child animations of a given target
  50310. */
  50311. var AnimationPropertiesOverride = /** @class */ (function () {
  50312. function AnimationPropertiesOverride() {
  50313. /**
  50314. * Gets or sets a value indicating if animation blending must be used
  50315. */
  50316. this.enableBlending = false;
  50317. /**
  50318. * Gets or sets the blending speed to use when enableBlending is true
  50319. */
  50320. this.blendingSpeed = 0.01;
  50321. /**
  50322. * Gets or sets the default loop mode to use
  50323. */
  50324. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50325. }
  50326. return AnimationPropertiesOverride;
  50327. }());
  50328. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50329. })(BABYLON || (BABYLON = {}));
  50330. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50331. var BABYLON;
  50332. (function (BABYLON) {
  50333. /**
  50334. * Represents the range of an animation
  50335. */
  50336. var AnimationRange = /** @class */ (function () {
  50337. /**
  50338. * Initializes the range of an animation
  50339. * @param name The name of the animation range
  50340. * @param from The starting frame of the animation
  50341. * @param to The ending frame of the animation
  50342. */
  50343. function AnimationRange(
  50344. /**The name of the animation range**/
  50345. name,
  50346. /**The starting frame of the animation */
  50347. from,
  50348. /**The ending frame of the animation*/
  50349. to) {
  50350. this.name = name;
  50351. this.from = from;
  50352. this.to = to;
  50353. }
  50354. /**
  50355. * Makes a copy of the animation range
  50356. * @returns A copy of the animation range
  50357. */
  50358. AnimationRange.prototype.clone = function () {
  50359. return new AnimationRange(this.name, this.from, this.to);
  50360. };
  50361. return AnimationRange;
  50362. }());
  50363. BABYLON.AnimationRange = AnimationRange;
  50364. /**
  50365. * Composed of a frame, and an action function
  50366. */
  50367. var AnimationEvent = /** @class */ (function () {
  50368. /**
  50369. * Initializes the animation event
  50370. * @param frame The frame for which the event is triggered
  50371. * @param action The event to perform when triggered
  50372. * @param onlyOnce Specifies if the event should be triggered only once
  50373. */
  50374. function AnimationEvent(
  50375. /** The frame for which the event is triggered **/
  50376. frame,
  50377. /** The event to perform when triggered **/
  50378. action,
  50379. /** Specifies if the event should be triggered only once**/
  50380. onlyOnce) {
  50381. this.frame = frame;
  50382. this.action = action;
  50383. this.onlyOnce = onlyOnce;
  50384. /**
  50385. * Specifies if the animation event is done
  50386. */
  50387. this.isDone = false;
  50388. }
  50389. return AnimationEvent;
  50390. }());
  50391. BABYLON.AnimationEvent = AnimationEvent;
  50392. /**
  50393. * A cursor which tracks a point on a path
  50394. */
  50395. var PathCursor = /** @class */ (function () {
  50396. /**
  50397. * Initializes the path cursor
  50398. * @param path The path to track
  50399. */
  50400. function PathCursor(path) {
  50401. this.path = path;
  50402. /**
  50403. * Stores path cursor callbacks for when an onchange event is triggered
  50404. */
  50405. this._onchange = new Array();
  50406. /**
  50407. * The value of the path cursor
  50408. */
  50409. this.value = 0;
  50410. /**
  50411. * The animation array of the path cursor
  50412. */
  50413. this.animations = new Array();
  50414. }
  50415. /**
  50416. * Gets the cursor point on the path
  50417. * @returns A point on the path cursor at the cursor location
  50418. */
  50419. PathCursor.prototype.getPoint = function () {
  50420. var point = this.path.getPointAtLengthPosition(this.value);
  50421. return new BABYLON.Vector3(point.x, 0, point.y);
  50422. };
  50423. /**
  50424. * Moves the cursor ahead by the step amount
  50425. * @param step The amount to move the cursor forward
  50426. * @returns This path cursor
  50427. */
  50428. PathCursor.prototype.moveAhead = function (step) {
  50429. if (step === void 0) { step = 0.002; }
  50430. this.move(step);
  50431. return this;
  50432. };
  50433. /**
  50434. * Moves the cursor behind by the step amount
  50435. * @param step The amount to move the cursor back
  50436. * @returns This path cursor
  50437. */
  50438. PathCursor.prototype.moveBack = function (step) {
  50439. if (step === void 0) { step = 0.002; }
  50440. this.move(-step);
  50441. return this;
  50442. };
  50443. /**
  50444. * Moves the cursor by the step amount
  50445. * If the step amount is greater than one, an exception is thrown
  50446. * @param step The amount to move the cursor
  50447. * @returns This path cursor
  50448. */
  50449. PathCursor.prototype.move = function (step) {
  50450. if (Math.abs(step) > 1) {
  50451. throw "step size should be less than 1.";
  50452. }
  50453. this.value += step;
  50454. this.ensureLimits();
  50455. this.raiseOnChange();
  50456. return this;
  50457. };
  50458. /**
  50459. * Ensures that the value is limited between zero and one
  50460. * @returns This path cursor
  50461. */
  50462. PathCursor.prototype.ensureLimits = function () {
  50463. while (this.value > 1) {
  50464. this.value -= 1;
  50465. }
  50466. while (this.value < 0) {
  50467. this.value += 1;
  50468. }
  50469. return this;
  50470. };
  50471. /**
  50472. * Runs onchange callbacks on change (used by the animation engine)
  50473. * @returns This path cursor
  50474. */
  50475. PathCursor.prototype.raiseOnChange = function () {
  50476. var _this = this;
  50477. this._onchange.forEach(function (f) { return f(_this); });
  50478. return this;
  50479. };
  50480. /**
  50481. * Executes a function on change
  50482. * @param f A path cursor onchange callback
  50483. * @returns This path cursor
  50484. */
  50485. PathCursor.prototype.onchange = function (f) {
  50486. this._onchange.push(f);
  50487. return this;
  50488. };
  50489. return PathCursor;
  50490. }());
  50491. BABYLON.PathCursor = PathCursor;
  50492. /**
  50493. * Enum for the animation key frame interpolation type
  50494. */
  50495. var AnimationKeyInterpolation;
  50496. (function (AnimationKeyInterpolation) {
  50497. /**
  50498. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50499. */
  50500. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50501. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50502. /**
  50503. * Class used to store any kind of animation
  50504. */
  50505. var Animation = /** @class */ (function () {
  50506. /**
  50507. * Initializes the animation
  50508. * @param name Name of the animation
  50509. * @param targetProperty Property to animate
  50510. * @param framePerSecond The frames per second of the animation
  50511. * @param dataType The data type of the animation
  50512. * @param loopMode The loop mode of the animation
  50513. * @param enableBlendings Specifies if blending should be enabled
  50514. */
  50515. function Animation(
  50516. /**Name of the animation */
  50517. name,
  50518. /**Property to animate */
  50519. targetProperty,
  50520. /**The frames per second of the animation */
  50521. framePerSecond,
  50522. /**The data type of the animation */
  50523. dataType,
  50524. /**The loop mode of the animation */
  50525. loopMode,
  50526. /**Specifies if blending should be enabled */
  50527. enableBlending) {
  50528. this.name = name;
  50529. this.targetProperty = targetProperty;
  50530. this.framePerSecond = framePerSecond;
  50531. this.dataType = dataType;
  50532. this.loopMode = loopMode;
  50533. this.enableBlending = enableBlending;
  50534. /**
  50535. * @hidden Internal use only
  50536. */
  50537. this._runtimeAnimations = new Array();
  50538. /**
  50539. * The set of event that will be linked to this animation
  50540. */
  50541. this._events = new Array();
  50542. /**
  50543. * Stores the blending speed of the animation
  50544. */
  50545. this.blendingSpeed = 0.01;
  50546. /**
  50547. * Stores the animation ranges for the animation
  50548. */
  50549. this._ranges = {};
  50550. this.targetPropertyPath = targetProperty.split(".");
  50551. this.dataType = dataType;
  50552. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50553. }
  50554. /**
  50555. * @hidden Internal use
  50556. */
  50557. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50558. var dataType = undefined;
  50559. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50560. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50561. }
  50562. else if (from instanceof BABYLON.Quaternion) {
  50563. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50564. }
  50565. else if (from instanceof BABYLON.Vector3) {
  50566. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50567. }
  50568. else if (from instanceof BABYLON.Vector2) {
  50569. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50570. }
  50571. else if (from instanceof BABYLON.Color3) {
  50572. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50573. }
  50574. else if (from instanceof BABYLON.Size) {
  50575. dataType = Animation.ANIMATIONTYPE_SIZE;
  50576. }
  50577. if (dataType == undefined) {
  50578. return null;
  50579. }
  50580. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50581. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50582. animation.setKeys(keys);
  50583. if (easingFunction !== undefined) {
  50584. animation.setEasingFunction(easingFunction);
  50585. }
  50586. return animation;
  50587. };
  50588. /**
  50589. * Sets up an animation
  50590. * @param property The property to animate
  50591. * @param animationType The animation type to apply
  50592. * @param framePerSecond The frames per second of the animation
  50593. * @param easingFunction The easing function used in the animation
  50594. * @returns The created animation
  50595. */
  50596. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50597. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50598. animation.setEasingFunction(easingFunction);
  50599. return animation;
  50600. };
  50601. /**
  50602. * Create and start an animation on a node
  50603. * @param name defines the name of the global animation that will be run on all nodes
  50604. * @param node defines the root node where the animation will take place
  50605. * @param targetProperty defines property to animate
  50606. * @param framePerSecond defines the number of frame per second yo use
  50607. * @param totalFrame defines the number of frames in total
  50608. * @param from defines the initial value
  50609. * @param to defines the final value
  50610. * @param loopMode defines which loop mode you want to use (off by default)
  50611. * @param easingFunction defines the easing function to use (linear by default)
  50612. * @param onAnimationEnd defines the callback to call when animation end
  50613. * @returns the animatable created for this animation
  50614. */
  50615. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50616. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50617. if (!animation) {
  50618. return null;
  50619. }
  50620. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50621. };
  50622. /**
  50623. * Create and start an animation on a node and its descendants
  50624. * @param name defines the name of the global animation that will be run on all nodes
  50625. * @param node defines the root node where the animation will take place
  50626. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  50627. * @param targetProperty defines property to animate
  50628. * @param framePerSecond defines the number of frame per second to use
  50629. * @param totalFrame defines the number of frames in total
  50630. * @param from defines the initial value
  50631. * @param to defines the final value
  50632. * @param loopMode defines which loop mode you want to use (off by default)
  50633. * @param easingFunction defines the easing function to use (linear by default)
  50634. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50635. * @returns the list of animatables created for all nodes
  50636. * @example https://www.babylonjs-playground.com/#MH0VLI
  50637. */
  50638. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50639. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50640. if (!animation) {
  50641. return null;
  50642. }
  50643. var scene = node.getScene();
  50644. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50645. };
  50646. /**
  50647. * Creates a new animation, merges it with the existing animations and starts it
  50648. * @param name Name of the animation
  50649. * @param node Node which contains the scene that begins the animations
  50650. * @param targetProperty Specifies which property to animate
  50651. * @param framePerSecond The frames per second of the animation
  50652. * @param totalFrame The total number of frames
  50653. * @param from The frame at the beginning of the animation
  50654. * @param to The frame at the end of the animation
  50655. * @param loopMode Specifies the loop mode of the animation
  50656. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50657. * @param onAnimationEnd Callback to run once the animation is complete
  50658. * @returns Nullable animation
  50659. */
  50660. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50661. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50662. if (!animation) {
  50663. return null;
  50664. }
  50665. node.animations.push(animation);
  50666. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50667. };
  50668. /**
  50669. * Transition property of the Camera to the target Value
  50670. * @param property The property to transition
  50671. * @param targetValue The target Value of the property
  50672. * @param host The object where the property to animate belongs
  50673. * @param scene Scene used to run the animation
  50674. * @param frameRate Framerate (in frame/s) to use
  50675. * @param transition The transition type we want to use
  50676. * @param duration The duration of the animation, in milliseconds
  50677. * @param onAnimationEnd Callback trigger at the end of the animation
  50678. * @returns Nullable animation
  50679. */
  50680. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50681. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50682. if (duration <= 0) {
  50683. host[property] = targetValue;
  50684. if (onAnimationEnd) {
  50685. onAnimationEnd();
  50686. }
  50687. return null;
  50688. }
  50689. var endFrame = frameRate * (duration / 1000);
  50690. transition.setKeys([{
  50691. frame: 0,
  50692. value: host[property].clone ? host[property].clone() : host[property]
  50693. },
  50694. {
  50695. frame: endFrame,
  50696. value: targetValue
  50697. }]);
  50698. if (!host.animations) {
  50699. host.animations = [];
  50700. }
  50701. host.animations.push(transition);
  50702. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50703. animation.onAnimationEnd = onAnimationEnd;
  50704. return animation;
  50705. };
  50706. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50707. /**
  50708. * Return the array of runtime animations currently using this animation
  50709. */
  50710. get: function () {
  50711. return this._runtimeAnimations;
  50712. },
  50713. enumerable: true,
  50714. configurable: true
  50715. });
  50716. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50717. /**
  50718. * Specifies if any of the runtime animations are currently running
  50719. */
  50720. get: function () {
  50721. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50722. var runtimeAnimation = _a[_i];
  50723. if (!runtimeAnimation.isStopped) {
  50724. return true;
  50725. }
  50726. }
  50727. return false;
  50728. },
  50729. enumerable: true,
  50730. configurable: true
  50731. });
  50732. // Methods
  50733. /**
  50734. * Converts the animation to a string
  50735. * @param fullDetails support for multiple levels of logging within scene loading
  50736. * @returns String form of the animation
  50737. */
  50738. Animation.prototype.toString = function (fullDetails) {
  50739. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50740. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50741. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50742. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50743. if (fullDetails) {
  50744. ret += ", Ranges: {";
  50745. var first = true;
  50746. for (var name in this._ranges) {
  50747. if (first) {
  50748. ret += ", ";
  50749. first = false;
  50750. }
  50751. ret += name;
  50752. }
  50753. ret += "}";
  50754. }
  50755. return ret;
  50756. };
  50757. /**
  50758. * Add an event to this animation
  50759. * @param event Event to add
  50760. */
  50761. Animation.prototype.addEvent = function (event) {
  50762. this._events.push(event);
  50763. };
  50764. /**
  50765. * Remove all events found at the given frame
  50766. * @param frame The frame to remove events from
  50767. */
  50768. Animation.prototype.removeEvents = function (frame) {
  50769. for (var index = 0; index < this._events.length; index++) {
  50770. if (this._events[index].frame === frame) {
  50771. this._events.splice(index, 1);
  50772. index--;
  50773. }
  50774. }
  50775. };
  50776. /**
  50777. * Retrieves all the events from the animation
  50778. * @returns Events from the animation
  50779. */
  50780. Animation.prototype.getEvents = function () {
  50781. return this._events;
  50782. };
  50783. /**
  50784. * Creates an animation range
  50785. * @param name Name of the animation range
  50786. * @param from Starting frame of the animation range
  50787. * @param to Ending frame of the animation
  50788. */
  50789. Animation.prototype.createRange = function (name, from, to) {
  50790. // check name not already in use; could happen for bones after serialized
  50791. if (!this._ranges[name]) {
  50792. this._ranges[name] = new AnimationRange(name, from, to);
  50793. }
  50794. };
  50795. /**
  50796. * Deletes an animation range by name
  50797. * @param name Name of the animation range to delete
  50798. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50799. */
  50800. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50801. if (deleteFrames === void 0) { deleteFrames = true; }
  50802. var range = this._ranges[name];
  50803. if (!range) {
  50804. return;
  50805. }
  50806. if (deleteFrames) {
  50807. var from = range.from;
  50808. var to = range.to;
  50809. // this loop MUST go high to low for multiple splices to work
  50810. for (var key = this._keys.length - 1; key >= 0; key--) {
  50811. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50812. this._keys.splice(key, 1);
  50813. }
  50814. }
  50815. }
  50816. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50817. };
  50818. /**
  50819. * Gets the animation range by name, or null if not defined
  50820. * @param name Name of the animation range
  50821. * @returns Nullable animation range
  50822. */
  50823. Animation.prototype.getRange = function (name) {
  50824. return this._ranges[name];
  50825. };
  50826. /**
  50827. * Gets the key frames from the animation
  50828. * @returns The key frames of the animation
  50829. */
  50830. Animation.prototype.getKeys = function () {
  50831. return this._keys;
  50832. };
  50833. /**
  50834. * Gets the highest frame rate of the animation
  50835. * @returns Highest frame rate of the animation
  50836. */
  50837. Animation.prototype.getHighestFrame = function () {
  50838. var ret = 0;
  50839. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50840. if (ret < this._keys[key].frame) {
  50841. ret = this._keys[key].frame;
  50842. }
  50843. }
  50844. return ret;
  50845. };
  50846. /**
  50847. * Gets the easing function of the animation
  50848. * @returns Easing function of the animation
  50849. */
  50850. Animation.prototype.getEasingFunction = function () {
  50851. return this._easingFunction;
  50852. };
  50853. /**
  50854. * Sets the easing function of the animation
  50855. * @param easingFunction A custom mathematical formula for animation
  50856. */
  50857. Animation.prototype.setEasingFunction = function (easingFunction) {
  50858. this._easingFunction = easingFunction;
  50859. };
  50860. /**
  50861. * Interpolates a scalar linearly
  50862. * @param startValue Start value of the animation curve
  50863. * @param endValue End value of the animation curve
  50864. * @param gradient Scalar amount to interpolate
  50865. * @returns Interpolated scalar value
  50866. */
  50867. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50868. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50869. };
  50870. /**
  50871. * Interpolates a scalar cubically
  50872. * @param startValue Start value of the animation curve
  50873. * @param outTangent End tangent of the animation
  50874. * @param endValue End value of the animation curve
  50875. * @param inTangent Start tangent of the animation curve
  50876. * @param gradient Scalar amount to interpolate
  50877. * @returns Interpolated scalar value
  50878. */
  50879. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50880. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50881. };
  50882. /**
  50883. * Interpolates a quaternion using a spherical linear interpolation
  50884. * @param startValue Start value of the animation curve
  50885. * @param endValue End value of the animation curve
  50886. * @param gradient Scalar amount to interpolate
  50887. * @returns Interpolated quaternion value
  50888. */
  50889. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50890. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50891. };
  50892. /**
  50893. * Interpolates a quaternion cubically
  50894. * @param startValue Start value of the animation curve
  50895. * @param outTangent End tangent of the animation curve
  50896. * @param endValue End value of the animation curve
  50897. * @param inTangent Start tangent of the animation curve
  50898. * @param gradient Scalar amount to interpolate
  50899. * @returns Interpolated quaternion value
  50900. */
  50901. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50902. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50903. };
  50904. /**
  50905. * Interpolates a Vector3 linearl
  50906. * @param startValue Start value of the animation curve
  50907. * @param endValue End value of the animation curve
  50908. * @param gradient Scalar amount to interpolate
  50909. * @returns Interpolated scalar value
  50910. */
  50911. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50912. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50913. };
  50914. /**
  50915. * Interpolates a Vector3 cubically
  50916. * @param startValue Start value of the animation curve
  50917. * @param outTangent End tangent of the animation
  50918. * @param endValue End value of the animation curve
  50919. * @param inTangent Start tangent of the animation curve
  50920. * @param gradient Scalar amount to interpolate
  50921. * @returns InterpolatedVector3 value
  50922. */
  50923. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50924. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50925. };
  50926. /**
  50927. * Interpolates a Vector2 linearly
  50928. * @param startValue Start value of the animation curve
  50929. * @param endValue End value of the animation curve
  50930. * @param gradient Scalar amount to interpolate
  50931. * @returns Interpolated Vector2 value
  50932. */
  50933. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50934. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50935. };
  50936. /**
  50937. * Interpolates a Vector2 cubically
  50938. * @param startValue Start value of the animation curve
  50939. * @param outTangent End tangent of the animation
  50940. * @param endValue End value of the animation curve
  50941. * @param inTangent Start tangent of the animation curve
  50942. * @param gradient Scalar amount to interpolate
  50943. * @returns Interpolated Vector2 value
  50944. */
  50945. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50946. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50947. };
  50948. /**
  50949. * Interpolates a size linearly
  50950. * @param startValue Start value of the animation curve
  50951. * @param endValue End value of the animation curve
  50952. * @param gradient Scalar amount to interpolate
  50953. * @returns Interpolated Size value
  50954. */
  50955. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50956. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50957. };
  50958. /**
  50959. * Interpolates a Color3 linearly
  50960. * @param startValue Start value of the animation curve
  50961. * @param endValue End value of the animation curve
  50962. * @param gradient Scalar amount to interpolate
  50963. * @returns Interpolated Color3 value
  50964. */
  50965. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50966. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50967. };
  50968. /**
  50969. * @hidden Internal use only
  50970. */
  50971. Animation.prototype._getKeyValue = function (value) {
  50972. if (typeof value === "function") {
  50973. return value();
  50974. }
  50975. return value;
  50976. };
  50977. /**
  50978. * @hidden Internal use only
  50979. */
  50980. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50981. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50982. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50983. }
  50984. var keys = this.getKeys();
  50985. // Try to get a hash to find the right key
  50986. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  50987. if (keys[startKeyIndex].frame >= currentFrame) {
  50988. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50989. startKeyIndex--;
  50990. }
  50991. }
  50992. for (var key = startKeyIndex; key < keys.length; key++) {
  50993. var endKey = keys[key + 1];
  50994. if (endKey.frame >= currentFrame) {
  50995. var startKey = keys[key];
  50996. var startValue = this._getKeyValue(startKey.value);
  50997. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50998. return startValue;
  50999. }
  51000. var endValue = this._getKeyValue(endKey.value);
  51001. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51002. var frameDelta = endKey.frame - startKey.frame;
  51003. // gradient : percent of currentFrame between the frame inf and the frame sup
  51004. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51005. // check for easingFunction and correction of gradient
  51006. var easingFunction = this.getEasingFunction();
  51007. if (easingFunction != null) {
  51008. gradient = easingFunction.ease(gradient);
  51009. }
  51010. switch (this.dataType) {
  51011. // Float
  51012. case Animation.ANIMATIONTYPE_FLOAT:
  51013. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51014. switch (loopMode) {
  51015. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51016. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51017. return floatValue;
  51018. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51019. return offsetValue * repeatCount + floatValue;
  51020. }
  51021. break;
  51022. // Quaternion
  51023. case Animation.ANIMATIONTYPE_QUATERNION:
  51024. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51025. switch (loopMode) {
  51026. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51027. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51028. return quatValue;
  51029. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51030. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51031. }
  51032. return quatValue;
  51033. // Vector3
  51034. case Animation.ANIMATIONTYPE_VECTOR3:
  51035. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51036. switch (loopMode) {
  51037. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51038. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51039. return vec3Value;
  51040. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51041. return vec3Value.add(offsetValue.scale(repeatCount));
  51042. }
  51043. // Vector2
  51044. case Animation.ANIMATIONTYPE_VECTOR2:
  51045. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51046. switch (loopMode) {
  51047. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51048. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51049. return vec2Value;
  51050. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51051. return vec2Value.add(offsetValue.scale(repeatCount));
  51052. }
  51053. // Size
  51054. case Animation.ANIMATIONTYPE_SIZE:
  51055. switch (loopMode) {
  51056. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51057. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51058. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51059. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51060. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51061. }
  51062. // Color3
  51063. case Animation.ANIMATIONTYPE_COLOR3:
  51064. switch (loopMode) {
  51065. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51066. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51067. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51068. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51069. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51070. }
  51071. // Matrix
  51072. case Animation.ANIMATIONTYPE_MATRIX:
  51073. switch (loopMode) {
  51074. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51075. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51076. if (Animation.AllowMatricesInterpolation) {
  51077. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51078. }
  51079. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51080. return startValue;
  51081. }
  51082. default:
  51083. break;
  51084. }
  51085. break;
  51086. }
  51087. }
  51088. return this._getKeyValue(keys[keys.length - 1].value);
  51089. };
  51090. /**
  51091. * Defines the function to use to interpolate matrices
  51092. * @param startValue defines the start matrix
  51093. * @param endValue defines the end matrix
  51094. * @param gradient defines the gradient between both matrices
  51095. * @param result defines an optional target matrix where to store the interpolation
  51096. * @returns the interpolated matrix
  51097. */
  51098. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51099. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51100. if (result) {
  51101. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51102. return result;
  51103. }
  51104. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51105. }
  51106. if (result) {
  51107. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51108. return result;
  51109. }
  51110. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51111. };
  51112. /**
  51113. * Makes a copy of the animation
  51114. * @returns Cloned animation
  51115. */
  51116. Animation.prototype.clone = function () {
  51117. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51118. clone.enableBlending = this.enableBlending;
  51119. clone.blendingSpeed = this.blendingSpeed;
  51120. if (this._keys) {
  51121. clone.setKeys(this._keys);
  51122. }
  51123. if (this._ranges) {
  51124. clone._ranges = {};
  51125. for (var name in this._ranges) {
  51126. var range = this._ranges[name];
  51127. if (!range) {
  51128. continue;
  51129. }
  51130. clone._ranges[name] = range.clone();
  51131. }
  51132. }
  51133. return clone;
  51134. };
  51135. /**
  51136. * Sets the key frames of the animation
  51137. * @param values The animation key frames to set
  51138. */
  51139. Animation.prototype.setKeys = function (values) {
  51140. this._keys = values.slice(0);
  51141. };
  51142. /**
  51143. * Serializes the animation to an object
  51144. * @returns Serialized object
  51145. */
  51146. Animation.prototype.serialize = function () {
  51147. var serializationObject = {};
  51148. serializationObject.name = this.name;
  51149. serializationObject.property = this.targetProperty;
  51150. serializationObject.framePerSecond = this.framePerSecond;
  51151. serializationObject.dataType = this.dataType;
  51152. serializationObject.loopBehavior = this.loopMode;
  51153. serializationObject.enableBlending = this.enableBlending;
  51154. serializationObject.blendingSpeed = this.blendingSpeed;
  51155. var dataType = this.dataType;
  51156. serializationObject.keys = [];
  51157. var keys = this.getKeys();
  51158. for (var index = 0; index < keys.length; index++) {
  51159. var animationKey = keys[index];
  51160. var key = {};
  51161. key.frame = animationKey.frame;
  51162. switch (dataType) {
  51163. case Animation.ANIMATIONTYPE_FLOAT:
  51164. key.values = [animationKey.value];
  51165. break;
  51166. case Animation.ANIMATIONTYPE_QUATERNION:
  51167. case Animation.ANIMATIONTYPE_MATRIX:
  51168. case Animation.ANIMATIONTYPE_VECTOR3:
  51169. case Animation.ANIMATIONTYPE_COLOR3:
  51170. key.values = animationKey.value.asArray();
  51171. break;
  51172. }
  51173. serializationObject.keys.push(key);
  51174. }
  51175. serializationObject.ranges = [];
  51176. for (var name in this._ranges) {
  51177. var source = this._ranges[name];
  51178. if (!source) {
  51179. continue;
  51180. }
  51181. var range = {};
  51182. range.name = name;
  51183. range.from = source.from;
  51184. range.to = source.to;
  51185. serializationObject.ranges.push(range);
  51186. }
  51187. return serializationObject;
  51188. };
  51189. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51190. /**
  51191. * Get the float animation type
  51192. */
  51193. get: function () {
  51194. return Animation._ANIMATIONTYPE_FLOAT;
  51195. },
  51196. enumerable: true,
  51197. configurable: true
  51198. });
  51199. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51200. /**
  51201. * Get the Vector3 animation type
  51202. */
  51203. get: function () {
  51204. return Animation._ANIMATIONTYPE_VECTOR3;
  51205. },
  51206. enumerable: true,
  51207. configurable: true
  51208. });
  51209. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51210. /**
  51211. * Get the Vectpr2 animation type
  51212. */
  51213. get: function () {
  51214. return Animation._ANIMATIONTYPE_VECTOR2;
  51215. },
  51216. enumerable: true,
  51217. configurable: true
  51218. });
  51219. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51220. /**
  51221. * Get the Size animation type
  51222. */
  51223. get: function () {
  51224. return Animation._ANIMATIONTYPE_SIZE;
  51225. },
  51226. enumerable: true,
  51227. configurable: true
  51228. });
  51229. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51230. /**
  51231. * Get the Quaternion animation type
  51232. */
  51233. get: function () {
  51234. return Animation._ANIMATIONTYPE_QUATERNION;
  51235. },
  51236. enumerable: true,
  51237. configurable: true
  51238. });
  51239. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51240. /**
  51241. * Get the Matrix animation type
  51242. */
  51243. get: function () {
  51244. return Animation._ANIMATIONTYPE_MATRIX;
  51245. },
  51246. enumerable: true,
  51247. configurable: true
  51248. });
  51249. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51250. /**
  51251. * Get the Color3 animation type
  51252. */
  51253. get: function () {
  51254. return Animation._ANIMATIONTYPE_COLOR3;
  51255. },
  51256. enumerable: true,
  51257. configurable: true
  51258. });
  51259. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51260. /**
  51261. * Get the Relative Loop Mode
  51262. */
  51263. get: function () {
  51264. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51265. },
  51266. enumerable: true,
  51267. configurable: true
  51268. });
  51269. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51270. /**
  51271. * Get the Cycle Loop Mode
  51272. */
  51273. get: function () {
  51274. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51275. },
  51276. enumerable: true,
  51277. configurable: true
  51278. });
  51279. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51280. /**
  51281. * Get the Constant Loop Mode
  51282. */
  51283. get: function () {
  51284. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51285. },
  51286. enumerable: true,
  51287. configurable: true
  51288. });
  51289. /** @hidden */
  51290. Animation._UniversalLerp = function (left, right, amount) {
  51291. var constructor = left.constructor;
  51292. if (constructor.Lerp) { // Lerp supported
  51293. return constructor.Lerp(left, right, amount);
  51294. }
  51295. else if (constructor.Slerp) { // Slerp supported
  51296. return constructor.Slerp(left, right, amount);
  51297. }
  51298. else if (left.toFixed) { // Number
  51299. return left * (1.0 - amount) + amount * right;
  51300. }
  51301. else { // Blending not supported
  51302. return right;
  51303. }
  51304. };
  51305. /**
  51306. * Parses an animation object and creates an animation
  51307. * @param parsedAnimation Parsed animation object
  51308. * @returns Animation object
  51309. */
  51310. Animation.Parse = function (parsedAnimation) {
  51311. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51312. var dataType = parsedAnimation.dataType;
  51313. var keys = [];
  51314. var data;
  51315. var index;
  51316. if (parsedAnimation.enableBlending) {
  51317. animation.enableBlending = parsedAnimation.enableBlending;
  51318. }
  51319. if (parsedAnimation.blendingSpeed) {
  51320. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51321. }
  51322. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51323. var key = parsedAnimation.keys[index];
  51324. var inTangent;
  51325. var outTangent;
  51326. switch (dataType) {
  51327. case Animation.ANIMATIONTYPE_FLOAT:
  51328. data = key.values[0];
  51329. if (key.values.length >= 1) {
  51330. inTangent = key.values[1];
  51331. }
  51332. if (key.values.length >= 2) {
  51333. outTangent = key.values[2];
  51334. }
  51335. break;
  51336. case Animation.ANIMATIONTYPE_QUATERNION:
  51337. data = BABYLON.Quaternion.FromArray(key.values);
  51338. if (key.values.length >= 8) {
  51339. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51340. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51341. inTangent = _inTangent;
  51342. }
  51343. }
  51344. if (key.values.length >= 12) {
  51345. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51346. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51347. outTangent = _outTangent;
  51348. }
  51349. }
  51350. break;
  51351. case Animation.ANIMATIONTYPE_MATRIX:
  51352. data = BABYLON.Matrix.FromArray(key.values);
  51353. break;
  51354. case Animation.ANIMATIONTYPE_COLOR3:
  51355. data = BABYLON.Color3.FromArray(key.values);
  51356. break;
  51357. case Animation.ANIMATIONTYPE_VECTOR3:
  51358. default:
  51359. data = BABYLON.Vector3.FromArray(key.values);
  51360. break;
  51361. }
  51362. var keyData = {};
  51363. keyData.frame = key.frame;
  51364. keyData.value = data;
  51365. if (inTangent != undefined) {
  51366. keyData.inTangent = inTangent;
  51367. }
  51368. if (outTangent != undefined) {
  51369. keyData.outTangent = outTangent;
  51370. }
  51371. keys.push(keyData);
  51372. }
  51373. animation.setKeys(keys);
  51374. if (parsedAnimation.ranges) {
  51375. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51376. data = parsedAnimation.ranges[index];
  51377. animation.createRange(data.name, data.from, data.to);
  51378. }
  51379. }
  51380. return animation;
  51381. };
  51382. /**
  51383. * Appends the serialized animations from the source animations
  51384. * @param source Source containing the animations
  51385. * @param destination Target to store the animations
  51386. */
  51387. Animation.AppendSerializedAnimations = function (source, destination) {
  51388. if (source.animations) {
  51389. destination.animations = [];
  51390. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51391. var animation = source.animations[animationIndex];
  51392. destination.animations.push(animation.serialize());
  51393. }
  51394. }
  51395. };
  51396. /**
  51397. * Use matrix interpolation instead of using direct key value when animating matrices
  51398. */
  51399. Animation.AllowMatricesInterpolation = false;
  51400. /**
  51401. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51402. */
  51403. Animation.AllowMatrixDecomposeForInterpolation = true;
  51404. // Statics
  51405. /**
  51406. * Float animation type
  51407. */
  51408. Animation._ANIMATIONTYPE_FLOAT = 0;
  51409. /**
  51410. * Vector3 animation type
  51411. */
  51412. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51413. /**
  51414. * Quaternion animation type
  51415. */
  51416. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51417. /**
  51418. * Matrix animation type
  51419. */
  51420. Animation._ANIMATIONTYPE_MATRIX = 3;
  51421. /**
  51422. * Color3 animation type
  51423. */
  51424. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51425. /**
  51426. * Vector2 animation type
  51427. */
  51428. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51429. /**
  51430. * Size animation type
  51431. */
  51432. Animation._ANIMATIONTYPE_SIZE = 6;
  51433. /**
  51434. * Relative Loop Mode
  51435. */
  51436. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51437. /**
  51438. * Cycle Loop Mode
  51439. */
  51440. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51441. /**
  51442. * Constant Loop Mode
  51443. */
  51444. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51445. return Animation;
  51446. }());
  51447. BABYLON.Animation = Animation;
  51448. })(BABYLON || (BABYLON = {}));
  51449. //# sourceMappingURL=babylon.animation.js.map
  51450. var BABYLON;
  51451. (function (BABYLON) {
  51452. /**
  51453. * This class defines the direct association between an animation and a target
  51454. */
  51455. var TargetedAnimation = /** @class */ (function () {
  51456. function TargetedAnimation() {
  51457. }
  51458. return TargetedAnimation;
  51459. }());
  51460. BABYLON.TargetedAnimation = TargetedAnimation;
  51461. /**
  51462. * Use this class to create coordinated animations on multiple targets
  51463. */
  51464. var AnimationGroup = /** @class */ (function () {
  51465. function AnimationGroup(name, scene) {
  51466. if (scene === void 0) { scene = null; }
  51467. this.name = name;
  51468. this._targetedAnimations = new Array();
  51469. this._animatables = new Array();
  51470. this._from = Number.MAX_VALUE;
  51471. this._to = -Number.MAX_VALUE;
  51472. this._speedRatio = 1;
  51473. this.onAnimationEndObservable = new BABYLON.Observable();
  51474. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51475. this._scene.animationGroups.push(this);
  51476. }
  51477. Object.defineProperty(AnimationGroup.prototype, "from", {
  51478. /**
  51479. * Gets the first frame
  51480. */
  51481. get: function () {
  51482. return this._from;
  51483. },
  51484. enumerable: true,
  51485. configurable: true
  51486. });
  51487. Object.defineProperty(AnimationGroup.prototype, "to", {
  51488. /**
  51489. * Gets the last frame
  51490. */
  51491. get: function () {
  51492. return this._to;
  51493. },
  51494. enumerable: true,
  51495. configurable: true
  51496. });
  51497. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51498. /**
  51499. * Define if the animations are started
  51500. */
  51501. get: function () {
  51502. return this._isStarted;
  51503. },
  51504. enumerable: true,
  51505. configurable: true
  51506. });
  51507. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51508. /**
  51509. * Gets or sets the speed ratio to use for all animations
  51510. */
  51511. get: function () {
  51512. return this._speedRatio;
  51513. },
  51514. /**
  51515. * Gets or sets the speed ratio to use for all animations
  51516. */
  51517. set: function (value) {
  51518. if (this._speedRatio === value) {
  51519. return;
  51520. }
  51521. this._speedRatio = value;
  51522. for (var index = 0; index < this._animatables.length; index++) {
  51523. var animatable = this._animatables[index];
  51524. animatable.speedRatio = this._speedRatio;
  51525. }
  51526. },
  51527. enumerable: true,
  51528. configurable: true
  51529. });
  51530. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51531. /**
  51532. * Gets the targeted animations for this animation group
  51533. */
  51534. get: function () {
  51535. return this._targetedAnimations;
  51536. },
  51537. enumerable: true,
  51538. configurable: true
  51539. });
  51540. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51541. /**
  51542. * returning the list of animatables controlled by this animation group.
  51543. */
  51544. get: function () {
  51545. return this._animatables;
  51546. },
  51547. enumerable: true,
  51548. configurable: true
  51549. });
  51550. /**
  51551. * Add an animation (with its target) in the group
  51552. * @param animation defines the animation we want to add
  51553. * @param target defines the target of the animation
  51554. * @returns the {BABYLON.TargetedAnimation} object
  51555. */
  51556. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51557. var targetedAnimation = {
  51558. animation: animation,
  51559. target: target
  51560. };
  51561. var keys = animation.getKeys();
  51562. if (this._from > keys[0].frame) {
  51563. this._from = keys[0].frame;
  51564. }
  51565. if (this._to < keys[keys.length - 1].frame) {
  51566. this._to = keys[keys.length - 1].frame;
  51567. }
  51568. this._targetedAnimations.push(targetedAnimation);
  51569. return targetedAnimation;
  51570. };
  51571. /**
  51572. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51573. * It can add constant keys at begin or end
  51574. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51575. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51576. */
  51577. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51578. if (beginFrame === void 0) { beginFrame = null; }
  51579. if (endFrame === void 0) { endFrame = null; }
  51580. if (beginFrame == null)
  51581. beginFrame = this._from;
  51582. if (endFrame == null)
  51583. endFrame = this._to;
  51584. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51585. var targetedAnimation = this._targetedAnimations[index];
  51586. var keys = targetedAnimation.animation.getKeys();
  51587. var startKey = keys[0];
  51588. var endKey = keys[keys.length - 1];
  51589. if (startKey.frame > beginFrame) {
  51590. var newKey = {
  51591. frame: beginFrame,
  51592. value: startKey.value,
  51593. inTangent: startKey.inTangent,
  51594. outTangent: startKey.outTangent,
  51595. interpolation: startKey.interpolation
  51596. };
  51597. keys.splice(0, 0, newKey);
  51598. }
  51599. if (endKey.frame < endFrame) {
  51600. var newKey = {
  51601. frame: endFrame,
  51602. value: endKey.value,
  51603. inTangent: endKey.outTangent,
  51604. outTangent: endKey.outTangent,
  51605. interpolation: endKey.interpolation
  51606. };
  51607. keys.push(newKey);
  51608. }
  51609. }
  51610. this._from = beginFrame;
  51611. this._to = endFrame;
  51612. return this;
  51613. };
  51614. /**
  51615. * Start all animations on given targets
  51616. * @param loop defines if animations must loop
  51617. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51618. * @param from defines the from key (optional)
  51619. * @param to defines the to key (optional)
  51620. * @returns the current animation group
  51621. */
  51622. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51623. var _this = this;
  51624. if (loop === void 0) { loop = false; }
  51625. if (speedRatio === void 0) { speedRatio = 1; }
  51626. if (this._isStarted || this._targetedAnimations.length === 0) {
  51627. return this;
  51628. }
  51629. var _loop_1 = function (targetedAnimation) {
  51630. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51631. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51632. }));
  51633. };
  51634. var this_1 = this;
  51635. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51636. var targetedAnimation = _a[_i];
  51637. _loop_1(targetedAnimation);
  51638. }
  51639. this._speedRatio = speedRatio;
  51640. this._isStarted = true;
  51641. return this;
  51642. };
  51643. /**
  51644. * Pause all animations
  51645. */
  51646. AnimationGroup.prototype.pause = function () {
  51647. if (!this._isStarted) {
  51648. return this;
  51649. }
  51650. for (var index = 0; index < this._animatables.length; index++) {
  51651. var animatable = this._animatables[index];
  51652. animatable.pause();
  51653. }
  51654. return this;
  51655. };
  51656. /**
  51657. * Play all animations to initial state
  51658. * This function will start() the animations if they were not started or will restart() them if they were paused
  51659. * @param loop defines if animations must loop
  51660. */
  51661. AnimationGroup.prototype.play = function (loop) {
  51662. if (this.isStarted) {
  51663. if (loop !== undefined) {
  51664. for (var index = 0; index < this._animatables.length; index++) {
  51665. var animatable = this._animatables[index];
  51666. animatable.loopAnimation = loop;
  51667. }
  51668. }
  51669. this.restart();
  51670. }
  51671. else {
  51672. this.start(loop, this._speedRatio);
  51673. }
  51674. return this;
  51675. };
  51676. /**
  51677. * Reset all animations to initial state
  51678. */
  51679. AnimationGroup.prototype.reset = function () {
  51680. if (!this._isStarted) {
  51681. return this;
  51682. }
  51683. for (var index = 0; index < this._animatables.length; index++) {
  51684. var animatable = this._animatables[index];
  51685. animatable.reset();
  51686. }
  51687. return this;
  51688. };
  51689. /**
  51690. * Restart animations from key 0
  51691. */
  51692. AnimationGroup.prototype.restart = function () {
  51693. if (!this._isStarted) {
  51694. return this;
  51695. }
  51696. for (var index = 0; index < this._animatables.length; index++) {
  51697. var animatable = this._animatables[index];
  51698. animatable.restart();
  51699. }
  51700. return this;
  51701. };
  51702. /**
  51703. * Stop all animations
  51704. */
  51705. AnimationGroup.prototype.stop = function () {
  51706. if (!this._isStarted) {
  51707. return this;
  51708. }
  51709. for (var index = 0; index < this._animatables.length; index++) {
  51710. var animatable = this._animatables[index];
  51711. animatable.stop();
  51712. }
  51713. this._isStarted = false;
  51714. return this;
  51715. };
  51716. /**
  51717. * Set animation weight for all animatables
  51718. * @param weight defines the weight to use
  51719. * @return the animationGroup
  51720. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51721. */
  51722. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51723. for (var index = 0; index < this._animatables.length; index++) {
  51724. var animatable = this._animatables[index];
  51725. animatable.weight = weight;
  51726. }
  51727. return this;
  51728. };
  51729. /**
  51730. * Synchronize and normalize all animatables with a source animatable
  51731. * @param root defines the root animatable to synchronize with
  51732. * @return the animationGroup
  51733. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51734. */
  51735. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51736. for (var index = 0; index < this._animatables.length; index++) {
  51737. var animatable = this._animatables[index];
  51738. animatable.syncWith(root);
  51739. }
  51740. return this;
  51741. };
  51742. /**
  51743. * Goes to a specific frame in this animation group
  51744. * @param frame the frame number to go to
  51745. * @return the animationGroup
  51746. */
  51747. AnimationGroup.prototype.goToFrame = function (frame) {
  51748. if (!this._isStarted) {
  51749. return this;
  51750. }
  51751. for (var index = 0; index < this._animatables.length; index++) {
  51752. var animatable = this._animatables[index];
  51753. animatable.goToFrame(frame);
  51754. }
  51755. return this;
  51756. };
  51757. /**
  51758. * Dispose all associated resources
  51759. */
  51760. AnimationGroup.prototype.dispose = function () {
  51761. this._targetedAnimations = [];
  51762. this._animatables = [];
  51763. var index = this._scene.animationGroups.indexOf(this);
  51764. if (index > -1) {
  51765. this._scene.animationGroups.splice(index, 1);
  51766. }
  51767. };
  51768. return AnimationGroup;
  51769. }());
  51770. BABYLON.AnimationGroup = AnimationGroup;
  51771. })(BABYLON || (BABYLON = {}));
  51772. //# sourceMappingURL=babylon.animationGroup.js.map
  51773. var BABYLON;
  51774. (function (BABYLON) {
  51775. /**
  51776. * Defines a runtime animation
  51777. */
  51778. var RuntimeAnimation = /** @class */ (function () {
  51779. /**
  51780. * Create a new RuntimeAnimation object
  51781. * @param target defines the target of the animation
  51782. * @param animation defines the source animation object
  51783. * @param scene defines the hosting scene
  51784. * @param host defines the initiating Animatable
  51785. */
  51786. function RuntimeAnimation(target, animation, scene, host) {
  51787. /**
  51788. * The current frame of the runtime animation
  51789. */
  51790. this._currentFrame = 0;
  51791. /**
  51792. * The original value of the runtime animation
  51793. */
  51794. this._originalValue = new Array();
  51795. /**
  51796. * The offsets cache of the runtime animation
  51797. */
  51798. this._offsetsCache = {};
  51799. /**
  51800. * The high limits cache of the runtime animation
  51801. */
  51802. this._highLimitsCache = {};
  51803. /**
  51804. * Specifies if the runtime animation has been stopped
  51805. */
  51806. this._stopped = false;
  51807. /**
  51808. * The blending factor of the runtime animation
  51809. */
  51810. this._blendingFactor = 0;
  51811. /**
  51812. * The target path of the runtime animation
  51813. */
  51814. this._targetPath = "";
  51815. /**
  51816. * The weight of the runtime animation
  51817. */
  51818. this._weight = 1.0;
  51819. /**
  51820. * The ratio offset of the runtime animation
  51821. */
  51822. this._ratioOffset = 0;
  51823. /**
  51824. * The previous delay of the runtime animation
  51825. */
  51826. this._previousDelay = 0;
  51827. /**
  51828. * The previous ratio of the runtime animation
  51829. */
  51830. this._previousRatio = 0;
  51831. this._animation = animation;
  51832. this._target = target;
  51833. this._scene = scene;
  51834. this._host = host;
  51835. animation._runtimeAnimations.push(this);
  51836. }
  51837. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51838. /**
  51839. * Gets the current frame of the runtime animation
  51840. */
  51841. get: function () {
  51842. return this._currentFrame;
  51843. },
  51844. enumerable: true,
  51845. configurable: true
  51846. });
  51847. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51848. /**
  51849. * Gets the weight of the runtime animation
  51850. */
  51851. get: function () {
  51852. return this._weight;
  51853. },
  51854. enumerable: true,
  51855. configurable: true
  51856. });
  51857. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51858. /**
  51859. * Gets the current value of the runtime animation
  51860. */
  51861. get: function () {
  51862. return this._currentValue;
  51863. },
  51864. enumerable: true,
  51865. configurable: true
  51866. });
  51867. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51868. /**
  51869. * Gets the target path of the runtime animation
  51870. */
  51871. get: function () {
  51872. return this._targetPath;
  51873. },
  51874. enumerable: true,
  51875. configurable: true
  51876. });
  51877. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51878. /**
  51879. * Gets the actual target of the runtime animation
  51880. */
  51881. get: function () {
  51882. return this._activeTarget;
  51883. },
  51884. enumerable: true,
  51885. configurable: true
  51886. });
  51887. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51888. /**
  51889. * Gets the animation from the runtime animation
  51890. */
  51891. get: function () {
  51892. return this._animation;
  51893. },
  51894. enumerable: true,
  51895. configurable: true
  51896. });
  51897. /**
  51898. * Resets the runtime animation to the beginning
  51899. * @param restoreOriginal defines whether to restore the target property to the original value
  51900. */
  51901. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51902. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51903. if (restoreOriginal) {
  51904. if (this._target instanceof Array) {
  51905. var index = 0;
  51906. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51907. var target = _a[_i];
  51908. if (this._originalValue[index] !== undefined) {
  51909. this._setValue(target, this._originalValue[index], -1);
  51910. }
  51911. index++;
  51912. }
  51913. }
  51914. else {
  51915. if (this._originalValue[0] !== undefined) {
  51916. this._setValue(this._target, this._originalValue[0], -1);
  51917. }
  51918. }
  51919. }
  51920. this._offsetsCache = {};
  51921. this._highLimitsCache = {};
  51922. this._currentFrame = 0;
  51923. this._blendingFactor = 0;
  51924. this._originalValue = new Array();
  51925. };
  51926. /**
  51927. * Specifies if the runtime animation is stopped
  51928. * @returns Boolean specifying if the runtime animation is stopped
  51929. */
  51930. RuntimeAnimation.prototype.isStopped = function () {
  51931. return this._stopped;
  51932. };
  51933. /**
  51934. * Disposes of the runtime animation
  51935. */
  51936. RuntimeAnimation.prototype.dispose = function () {
  51937. var index = this._animation.runtimeAnimations.indexOf(this);
  51938. if (index > -1) {
  51939. this._animation.runtimeAnimations.splice(index, 1);
  51940. }
  51941. };
  51942. /**
  51943. * Interpolates the animation from the current frame
  51944. * @param currentFrame The frame to interpolate the animation to
  51945. * @param repeatCount The number of times that the animation should loop
  51946. * @param loopMode The type of looping mode to use
  51947. * @param offsetValue Animation offset value
  51948. * @param highLimitValue The high limit value
  51949. * @returns The interpolated value
  51950. */
  51951. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51952. this._currentFrame = currentFrame;
  51953. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51954. this._workValue = BABYLON.Matrix.Zero();
  51955. }
  51956. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51957. };
  51958. /**
  51959. * Apply the interpolated value to the target
  51960. * @param currentValue defines the value computed by the animation
  51961. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51962. */
  51963. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51964. if (weight === void 0) { weight = 1.0; }
  51965. if (this._target instanceof Array) {
  51966. var index = 0;
  51967. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51968. var target = _a[_i];
  51969. this._setValue(target, currentValue, weight, index);
  51970. index++;
  51971. }
  51972. }
  51973. else {
  51974. this._setValue(this._target, currentValue, weight);
  51975. }
  51976. };
  51977. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51978. if (targetIndex === void 0) { targetIndex = 0; }
  51979. // Set value
  51980. var path;
  51981. var destination;
  51982. var targetPropertyPath = this._animation.targetPropertyPath;
  51983. if (targetPropertyPath.length > 1) {
  51984. var property = target[targetPropertyPath[0]];
  51985. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51986. property = property[targetPropertyPath[index]];
  51987. }
  51988. path = targetPropertyPath[targetPropertyPath.length - 1];
  51989. destination = property;
  51990. }
  51991. else {
  51992. path = targetPropertyPath[0];
  51993. destination = target;
  51994. }
  51995. this._targetPath = path;
  51996. this._activeTarget = destination;
  51997. this._weight = weight;
  51998. if (this._originalValue[targetIndex] === undefined) {
  51999. var originalValue = void 0;
  52000. if (destination.getRestPose && path === "_matrix") { // For bones
  52001. originalValue = destination.getRestPose();
  52002. }
  52003. else {
  52004. originalValue = destination[path];
  52005. }
  52006. if (originalValue && originalValue.clone) {
  52007. this._originalValue[targetIndex] = originalValue.clone();
  52008. }
  52009. else {
  52010. this._originalValue[targetIndex] = originalValue;
  52011. }
  52012. }
  52013. // Blending
  52014. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52015. if (enableBlending && this._blendingFactor <= 1.0) {
  52016. if (!this._originalBlendValue) {
  52017. var originalValue = destination[path];
  52018. if (originalValue.clone) {
  52019. this._originalBlendValue = originalValue.clone();
  52020. }
  52021. else {
  52022. this._originalBlendValue = originalValue;
  52023. }
  52024. }
  52025. if (this._originalBlendValue.m) { // Matrix
  52026. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52027. if (this._currentValue) {
  52028. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52029. }
  52030. else {
  52031. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52032. }
  52033. }
  52034. else {
  52035. if (this._currentValue) {
  52036. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52037. }
  52038. else {
  52039. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52040. }
  52041. }
  52042. }
  52043. else {
  52044. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52045. }
  52046. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52047. this._blendingFactor += blendingSpeed;
  52048. }
  52049. else {
  52050. this._currentValue = currentValue;
  52051. }
  52052. if (weight !== -1.0) {
  52053. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52054. }
  52055. else {
  52056. destination[path] = this._currentValue;
  52057. }
  52058. if (target.markAsDirty) {
  52059. target.markAsDirty(this._animation.targetProperty);
  52060. }
  52061. };
  52062. /**
  52063. * Gets the loop pmode of the runtime animation
  52064. * @returns Loop Mode
  52065. */
  52066. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52067. if (this._target && this._target.animationPropertiesOverride) {
  52068. return this._target.animationPropertiesOverride.loopMode;
  52069. }
  52070. return this._animation.loopMode;
  52071. };
  52072. /**
  52073. * Move the current animation to a given frame
  52074. * @param frame defines the frame to move to
  52075. */
  52076. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52077. var keys = this._animation.getKeys();
  52078. if (frame < keys[0].frame) {
  52079. frame = keys[0].frame;
  52080. }
  52081. else if (frame > keys[keys.length - 1].frame) {
  52082. frame = keys[keys.length - 1].frame;
  52083. }
  52084. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52085. this.setValue(currentValue, -1);
  52086. };
  52087. /**
  52088. * @hidden Internal use only
  52089. */
  52090. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52091. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52092. this._ratioOffset = this._previousRatio - newRatio;
  52093. };
  52094. /**
  52095. * Execute the current animation
  52096. * @param delay defines the delay to add to the current frame
  52097. * @param from defines the lower bound of the animation range
  52098. * @param to defines the upper bound of the animation range
  52099. * @param loop defines if the current animation must loop
  52100. * @param speedRatio defines the current speed ratio
  52101. * @param weight defines the weight of the animation (default is -1 so no weight)
  52102. * @returns a boolean indicating if the animation has ended
  52103. */
  52104. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52105. if (weight === void 0) { weight = -1.0; }
  52106. var targetPropertyPath = this._animation.targetPropertyPath;
  52107. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52108. this._stopped = true;
  52109. return false;
  52110. }
  52111. var returnValue = true;
  52112. var keys = this._animation.getKeys();
  52113. // Adding a start key at frame 0 if missing
  52114. if (keys[0].frame !== 0) {
  52115. var newKey = { frame: 0, value: keys[0].value };
  52116. keys.splice(0, 0, newKey);
  52117. }
  52118. // Check limits
  52119. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52120. from = keys[0].frame;
  52121. }
  52122. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52123. to = keys[keys.length - 1].frame;
  52124. }
  52125. //to and from cannot be the same key
  52126. if (from === to) {
  52127. if (from > keys[0].frame) {
  52128. from--;
  52129. }
  52130. else if (to < keys[keys.length - 1].frame) {
  52131. to++;
  52132. }
  52133. }
  52134. // Compute ratio
  52135. var range = to - from;
  52136. var offsetValue;
  52137. // ratio represents the frame delta between from and to
  52138. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52139. var highLimitValue = 0;
  52140. this._previousDelay = delay;
  52141. this._previousRatio = ratio;
  52142. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52143. returnValue = false;
  52144. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52145. }
  52146. else {
  52147. // Get max value if required
  52148. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52149. var keyOffset = to.toString() + from.toString();
  52150. if (!this._offsetsCache[keyOffset]) {
  52151. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52152. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52153. switch (this._animation.dataType) {
  52154. // Float
  52155. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52156. this._offsetsCache[keyOffset] = toValue - fromValue;
  52157. break;
  52158. // Quaternion
  52159. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52160. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52161. break;
  52162. // Vector3
  52163. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52164. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52165. // Vector2
  52166. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52167. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52168. // Size
  52169. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52170. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52171. // Color3
  52172. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52173. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52174. default:
  52175. break;
  52176. }
  52177. this._highLimitsCache[keyOffset] = toValue;
  52178. }
  52179. highLimitValue = this._highLimitsCache[keyOffset];
  52180. offsetValue = this._offsetsCache[keyOffset];
  52181. }
  52182. }
  52183. if (offsetValue === undefined) {
  52184. switch (this._animation.dataType) {
  52185. // Float
  52186. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52187. offsetValue = 0;
  52188. break;
  52189. // Quaternion
  52190. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52191. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52192. break;
  52193. // Vector3
  52194. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52195. offsetValue = BABYLON.Vector3.Zero();
  52196. break;
  52197. // Vector2
  52198. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52199. offsetValue = BABYLON.Vector2.Zero();
  52200. break;
  52201. // Size
  52202. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52203. offsetValue = BABYLON.Size.Zero();
  52204. break;
  52205. // Color3
  52206. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52207. offsetValue = BABYLON.Color3.Black();
  52208. }
  52209. }
  52210. // Compute value
  52211. var repeatCount = (ratio / range) >> 0;
  52212. var currentFrame = returnValue ? from + ratio % range : to;
  52213. // Need to normalize?
  52214. if (this._host && this._host.syncRoot) {
  52215. var syncRoot = this._host.syncRoot;
  52216. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52217. currentFrame = from + (to - from) * hostNormalizedFrame;
  52218. }
  52219. // Reset events if looping
  52220. var events = this._animation.getEvents();
  52221. if (range > 0 && this.currentFrame > currentFrame ||
  52222. range < 0 && this.currentFrame < currentFrame) {
  52223. // Need to reset animation events
  52224. for (var index = 0; index < events.length; index++) {
  52225. if (!events[index].onlyOnce) {
  52226. // reset event, the animation is looping
  52227. events[index].isDone = false;
  52228. }
  52229. }
  52230. }
  52231. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52232. // Set value
  52233. this.setValue(currentValue, weight);
  52234. // Check events
  52235. for (var index = 0; index < events.length; index++) {
  52236. // Make sure current frame has passed event frame and that event frame is within the current range
  52237. // Also, handle both forward and reverse animations
  52238. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52239. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52240. var event = events[index];
  52241. if (!event.isDone) {
  52242. // If event should be done only once, remove it.
  52243. if (event.onlyOnce) {
  52244. events.splice(index, 1);
  52245. index--;
  52246. }
  52247. event.isDone = true;
  52248. event.action();
  52249. } // Don't do anything if the event has already be done.
  52250. }
  52251. }
  52252. if (!returnValue) {
  52253. this._stopped = true;
  52254. }
  52255. return returnValue;
  52256. };
  52257. return RuntimeAnimation;
  52258. }());
  52259. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52260. })(BABYLON || (BABYLON = {}));
  52261. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52262. var BABYLON;
  52263. (function (BABYLON) {
  52264. var Animatable = /** @class */ (function () {
  52265. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52266. if (fromFrame === void 0) { fromFrame = 0; }
  52267. if (toFrame === void 0) { toFrame = 100; }
  52268. if (loopAnimation === void 0) { loopAnimation = false; }
  52269. if (speedRatio === void 0) { speedRatio = 1.0; }
  52270. this.target = target;
  52271. this.fromFrame = fromFrame;
  52272. this.toFrame = toFrame;
  52273. this.loopAnimation = loopAnimation;
  52274. this.onAnimationEnd = onAnimationEnd;
  52275. this._localDelayOffset = null;
  52276. this._pausedDelay = null;
  52277. this._runtimeAnimations = new Array();
  52278. this._paused = false;
  52279. this._speedRatio = 1;
  52280. this._weight = -1.0;
  52281. this.animationStarted = false;
  52282. this._scene = scene;
  52283. if (animations) {
  52284. this.appendAnimations(target, animations);
  52285. }
  52286. this._speedRatio = speedRatio;
  52287. scene._activeAnimatables.push(this);
  52288. }
  52289. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52290. /**
  52291. * Gets the root Animatable used to synchronize and normalize animations
  52292. */
  52293. get: function () {
  52294. return this._syncRoot;
  52295. },
  52296. enumerable: true,
  52297. configurable: true
  52298. });
  52299. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52300. /**
  52301. * Gets the current frame of the first RuntimeAnimation
  52302. * Used to synchronize Animatables
  52303. */
  52304. get: function () {
  52305. if (this._runtimeAnimations.length === 0) {
  52306. return 0;
  52307. }
  52308. return this._runtimeAnimations[0].currentFrame;
  52309. },
  52310. enumerable: true,
  52311. configurable: true
  52312. });
  52313. Object.defineProperty(Animatable.prototype, "weight", {
  52314. /**
  52315. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52316. */
  52317. get: function () {
  52318. return this._weight;
  52319. },
  52320. set: function (value) {
  52321. if (value === -1) { // -1 is ok and means no weight
  52322. this._weight = -1;
  52323. return;
  52324. }
  52325. // Else weight must be in [0, 1] range
  52326. this._weight = Math.min(Math.max(value, 0), 1.0);
  52327. },
  52328. enumerable: true,
  52329. configurable: true
  52330. });
  52331. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52332. /**
  52333. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52334. */
  52335. get: function () {
  52336. return this._speedRatio;
  52337. },
  52338. set: function (value) {
  52339. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52340. var animation = this._runtimeAnimations[index];
  52341. animation._prepareForSpeedRatioChange(value);
  52342. }
  52343. this._speedRatio = value;
  52344. },
  52345. enumerable: true,
  52346. configurable: true
  52347. });
  52348. // Methods
  52349. /**
  52350. * Synchronize and normalize current Animatable with a source Animatable
  52351. * This is useful when using animation weights and when animations are not of the same length
  52352. * @param root defines the root Animatable to synchronize with
  52353. * @returns the current Animatable
  52354. */
  52355. Animatable.prototype.syncWith = function (root) {
  52356. this._syncRoot = root;
  52357. if (root) {
  52358. // Make sure this animatable will animate after the root
  52359. var index = this._scene._activeAnimatables.indexOf(this);
  52360. if (index > -1) {
  52361. this._scene._activeAnimatables.splice(index, 1);
  52362. this._scene._activeAnimatables.push(this);
  52363. }
  52364. }
  52365. return this;
  52366. };
  52367. Animatable.prototype.getAnimations = function () {
  52368. return this._runtimeAnimations;
  52369. };
  52370. Animatable.prototype.appendAnimations = function (target, animations) {
  52371. for (var index = 0; index < animations.length; index++) {
  52372. var animation = animations[index];
  52373. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52374. }
  52375. };
  52376. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52377. var runtimeAnimations = this._runtimeAnimations;
  52378. for (var index = 0; index < runtimeAnimations.length; index++) {
  52379. if (runtimeAnimations[index].animation.targetProperty === property) {
  52380. return runtimeAnimations[index].animation;
  52381. }
  52382. }
  52383. return null;
  52384. };
  52385. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52386. var runtimeAnimations = this._runtimeAnimations;
  52387. for (var index = 0; index < runtimeAnimations.length; index++) {
  52388. if (runtimeAnimations[index].animation.targetProperty === property) {
  52389. return runtimeAnimations[index];
  52390. }
  52391. }
  52392. return null;
  52393. };
  52394. Animatable.prototype.reset = function () {
  52395. var runtimeAnimations = this._runtimeAnimations;
  52396. for (var index = 0; index < runtimeAnimations.length; index++) {
  52397. runtimeAnimations[index].reset(true);
  52398. }
  52399. this._localDelayOffset = null;
  52400. this._pausedDelay = null;
  52401. };
  52402. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52403. var runtimeAnimations = this._runtimeAnimations;
  52404. for (var index = 0; index < runtimeAnimations.length; index++) {
  52405. runtimeAnimations[index].animation.enableBlending = true;
  52406. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52407. }
  52408. };
  52409. Animatable.prototype.disableBlending = function () {
  52410. var runtimeAnimations = this._runtimeAnimations;
  52411. for (var index = 0; index < runtimeAnimations.length; index++) {
  52412. runtimeAnimations[index].animation.enableBlending = false;
  52413. }
  52414. };
  52415. Animatable.prototype.goToFrame = function (frame) {
  52416. var runtimeAnimations = this._runtimeAnimations;
  52417. if (runtimeAnimations[0]) {
  52418. var fps = runtimeAnimations[0].animation.framePerSecond;
  52419. var currentFrame = runtimeAnimations[0].currentFrame;
  52420. var adjustTime = frame - currentFrame;
  52421. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52422. if (this._localDelayOffset === null) {
  52423. this._localDelayOffset = 0;
  52424. }
  52425. this._localDelayOffset -= delay;
  52426. }
  52427. for (var index = 0; index < runtimeAnimations.length; index++) {
  52428. runtimeAnimations[index].goToFrame(frame);
  52429. }
  52430. };
  52431. Animatable.prototype.pause = function () {
  52432. if (this._paused) {
  52433. return;
  52434. }
  52435. this._paused = true;
  52436. };
  52437. Animatable.prototype.restart = function () {
  52438. this._paused = false;
  52439. };
  52440. Animatable.prototype.stop = function (animationName) {
  52441. if (animationName) {
  52442. var idx = this._scene._activeAnimatables.indexOf(this);
  52443. if (idx > -1) {
  52444. var runtimeAnimations = this._runtimeAnimations;
  52445. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52446. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52447. continue;
  52448. }
  52449. runtimeAnimations[index].dispose();
  52450. runtimeAnimations.splice(index, 1);
  52451. }
  52452. if (runtimeAnimations.length == 0) {
  52453. this._scene._activeAnimatables.splice(idx, 1);
  52454. if (this.onAnimationEnd) {
  52455. this.onAnimationEnd();
  52456. }
  52457. }
  52458. }
  52459. }
  52460. else {
  52461. var index = this._scene._activeAnimatables.indexOf(this);
  52462. if (index > -1) {
  52463. this._scene._activeAnimatables.splice(index, 1);
  52464. var runtimeAnimations = this._runtimeAnimations;
  52465. for (var index = 0; index < runtimeAnimations.length; index++) {
  52466. runtimeAnimations[index].dispose();
  52467. }
  52468. if (this.onAnimationEnd) {
  52469. this.onAnimationEnd();
  52470. }
  52471. }
  52472. }
  52473. };
  52474. Animatable.prototype._animate = function (delay) {
  52475. if (this._paused) {
  52476. this.animationStarted = false;
  52477. if (this._pausedDelay === null) {
  52478. this._pausedDelay = delay;
  52479. }
  52480. return true;
  52481. }
  52482. if (this._localDelayOffset === null) {
  52483. this._localDelayOffset = delay;
  52484. this._pausedDelay = null;
  52485. }
  52486. else if (this._pausedDelay !== null) {
  52487. this._localDelayOffset += delay - this._pausedDelay;
  52488. this._pausedDelay = null;
  52489. }
  52490. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52491. return true;
  52492. }
  52493. // Animating
  52494. var running = false;
  52495. var runtimeAnimations = this._runtimeAnimations;
  52496. var index;
  52497. for (index = 0; index < runtimeAnimations.length; index++) {
  52498. var animation = runtimeAnimations[index];
  52499. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52500. running = running || isRunning;
  52501. }
  52502. this.animationStarted = running;
  52503. if (!running) {
  52504. // Remove from active animatables
  52505. index = this._scene._activeAnimatables.indexOf(this);
  52506. this._scene._activeAnimatables.splice(index, 1);
  52507. // Dispose all runtime animations
  52508. for (index = 0; index < runtimeAnimations.length; index++) {
  52509. runtimeAnimations[index].dispose();
  52510. }
  52511. }
  52512. if (!running && this.onAnimationEnd) {
  52513. this.onAnimationEnd();
  52514. this.onAnimationEnd = null;
  52515. }
  52516. return running;
  52517. };
  52518. return Animatable;
  52519. }());
  52520. BABYLON.Animatable = Animatable;
  52521. })(BABYLON || (BABYLON = {}));
  52522. //# sourceMappingURL=babylon.animatable.js.map
  52523. var BABYLON;
  52524. (function (BABYLON) {
  52525. var EasingFunction = /** @class */ (function () {
  52526. function EasingFunction() {
  52527. // Properties
  52528. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52529. }
  52530. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52531. get: function () {
  52532. return EasingFunction._EASINGMODE_EASEIN;
  52533. },
  52534. enumerable: true,
  52535. configurable: true
  52536. });
  52537. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52538. get: function () {
  52539. return EasingFunction._EASINGMODE_EASEOUT;
  52540. },
  52541. enumerable: true,
  52542. configurable: true
  52543. });
  52544. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52545. get: function () {
  52546. return EasingFunction._EASINGMODE_EASEINOUT;
  52547. },
  52548. enumerable: true,
  52549. configurable: true
  52550. });
  52551. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52552. var n = Math.min(Math.max(easingMode, 0), 2);
  52553. this._easingMode = n;
  52554. };
  52555. EasingFunction.prototype.getEasingMode = function () {
  52556. return this._easingMode;
  52557. };
  52558. EasingFunction.prototype.easeInCore = function (gradient) {
  52559. throw new Error('You must implement this method');
  52560. };
  52561. EasingFunction.prototype.ease = function (gradient) {
  52562. switch (this._easingMode) {
  52563. case EasingFunction.EASINGMODE_EASEIN:
  52564. return this.easeInCore(gradient);
  52565. case EasingFunction.EASINGMODE_EASEOUT:
  52566. return (1 - this.easeInCore(1 - gradient));
  52567. }
  52568. if (gradient >= 0.5) {
  52569. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52570. }
  52571. return (this.easeInCore(gradient * 2) * 0.5);
  52572. };
  52573. //Statics
  52574. EasingFunction._EASINGMODE_EASEIN = 0;
  52575. EasingFunction._EASINGMODE_EASEOUT = 1;
  52576. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52577. return EasingFunction;
  52578. }());
  52579. BABYLON.EasingFunction = EasingFunction;
  52580. var CircleEase = /** @class */ (function (_super) {
  52581. __extends(CircleEase, _super);
  52582. function CircleEase() {
  52583. return _super !== null && _super.apply(this, arguments) || this;
  52584. }
  52585. CircleEase.prototype.easeInCore = function (gradient) {
  52586. gradient = Math.max(0, Math.min(1, gradient));
  52587. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52588. };
  52589. return CircleEase;
  52590. }(EasingFunction));
  52591. BABYLON.CircleEase = CircleEase;
  52592. var BackEase = /** @class */ (function (_super) {
  52593. __extends(BackEase, _super);
  52594. function BackEase(amplitude) {
  52595. if (amplitude === void 0) { amplitude = 1; }
  52596. var _this = _super.call(this) || this;
  52597. _this.amplitude = amplitude;
  52598. return _this;
  52599. }
  52600. BackEase.prototype.easeInCore = function (gradient) {
  52601. var num = Math.max(0, this.amplitude);
  52602. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52603. };
  52604. return BackEase;
  52605. }(EasingFunction));
  52606. BABYLON.BackEase = BackEase;
  52607. var BounceEase = /** @class */ (function (_super) {
  52608. __extends(BounceEase, _super);
  52609. function BounceEase(bounces, bounciness) {
  52610. if (bounces === void 0) { bounces = 3; }
  52611. if (bounciness === void 0) { bounciness = 2; }
  52612. var _this = _super.call(this) || this;
  52613. _this.bounces = bounces;
  52614. _this.bounciness = bounciness;
  52615. return _this;
  52616. }
  52617. BounceEase.prototype.easeInCore = function (gradient) {
  52618. var y = Math.max(0.0, this.bounces);
  52619. var bounciness = this.bounciness;
  52620. if (bounciness <= 1.0) {
  52621. bounciness = 1.001;
  52622. }
  52623. var num9 = Math.pow(bounciness, y);
  52624. var num5 = 1.0 - bounciness;
  52625. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52626. var num15 = gradient * num4;
  52627. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52628. var num3 = Math.floor(num65);
  52629. var num13 = num3 + 1.0;
  52630. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52631. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52632. var num7 = (num8 + num12) * 0.5;
  52633. var num6 = gradient - num7;
  52634. var num2 = num7 - num8;
  52635. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52636. };
  52637. return BounceEase;
  52638. }(EasingFunction));
  52639. BABYLON.BounceEase = BounceEase;
  52640. var CubicEase = /** @class */ (function (_super) {
  52641. __extends(CubicEase, _super);
  52642. function CubicEase() {
  52643. return _super !== null && _super.apply(this, arguments) || this;
  52644. }
  52645. CubicEase.prototype.easeInCore = function (gradient) {
  52646. return (gradient * gradient * gradient);
  52647. };
  52648. return CubicEase;
  52649. }(EasingFunction));
  52650. BABYLON.CubicEase = CubicEase;
  52651. var ElasticEase = /** @class */ (function (_super) {
  52652. __extends(ElasticEase, _super);
  52653. function ElasticEase(oscillations, springiness) {
  52654. if (oscillations === void 0) { oscillations = 3; }
  52655. if (springiness === void 0) { springiness = 3; }
  52656. var _this = _super.call(this) || this;
  52657. _this.oscillations = oscillations;
  52658. _this.springiness = springiness;
  52659. return _this;
  52660. }
  52661. ElasticEase.prototype.easeInCore = function (gradient) {
  52662. var num2;
  52663. var num3 = Math.max(0.0, this.oscillations);
  52664. var num = Math.max(0.0, this.springiness);
  52665. if (num == 0) {
  52666. num2 = gradient;
  52667. }
  52668. else {
  52669. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52670. }
  52671. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52672. };
  52673. return ElasticEase;
  52674. }(EasingFunction));
  52675. BABYLON.ElasticEase = ElasticEase;
  52676. var ExponentialEase = /** @class */ (function (_super) {
  52677. __extends(ExponentialEase, _super);
  52678. function ExponentialEase(exponent) {
  52679. if (exponent === void 0) { exponent = 2; }
  52680. var _this = _super.call(this) || this;
  52681. _this.exponent = exponent;
  52682. return _this;
  52683. }
  52684. ExponentialEase.prototype.easeInCore = function (gradient) {
  52685. if (this.exponent <= 0) {
  52686. return gradient;
  52687. }
  52688. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52689. };
  52690. return ExponentialEase;
  52691. }(EasingFunction));
  52692. BABYLON.ExponentialEase = ExponentialEase;
  52693. var PowerEase = /** @class */ (function (_super) {
  52694. __extends(PowerEase, _super);
  52695. function PowerEase(power) {
  52696. if (power === void 0) { power = 2; }
  52697. var _this = _super.call(this) || this;
  52698. _this.power = power;
  52699. return _this;
  52700. }
  52701. PowerEase.prototype.easeInCore = function (gradient) {
  52702. var y = Math.max(0.0, this.power);
  52703. return Math.pow(gradient, y);
  52704. };
  52705. return PowerEase;
  52706. }(EasingFunction));
  52707. BABYLON.PowerEase = PowerEase;
  52708. var QuadraticEase = /** @class */ (function (_super) {
  52709. __extends(QuadraticEase, _super);
  52710. function QuadraticEase() {
  52711. return _super !== null && _super.apply(this, arguments) || this;
  52712. }
  52713. QuadraticEase.prototype.easeInCore = function (gradient) {
  52714. return (gradient * gradient);
  52715. };
  52716. return QuadraticEase;
  52717. }(EasingFunction));
  52718. BABYLON.QuadraticEase = QuadraticEase;
  52719. var QuarticEase = /** @class */ (function (_super) {
  52720. __extends(QuarticEase, _super);
  52721. function QuarticEase() {
  52722. return _super !== null && _super.apply(this, arguments) || this;
  52723. }
  52724. QuarticEase.prototype.easeInCore = function (gradient) {
  52725. return (gradient * gradient * gradient * gradient);
  52726. };
  52727. return QuarticEase;
  52728. }(EasingFunction));
  52729. BABYLON.QuarticEase = QuarticEase;
  52730. var QuinticEase = /** @class */ (function (_super) {
  52731. __extends(QuinticEase, _super);
  52732. function QuinticEase() {
  52733. return _super !== null && _super.apply(this, arguments) || this;
  52734. }
  52735. QuinticEase.prototype.easeInCore = function (gradient) {
  52736. return (gradient * gradient * gradient * gradient * gradient);
  52737. };
  52738. return QuinticEase;
  52739. }(EasingFunction));
  52740. BABYLON.QuinticEase = QuinticEase;
  52741. var SineEase = /** @class */ (function (_super) {
  52742. __extends(SineEase, _super);
  52743. function SineEase() {
  52744. return _super !== null && _super.apply(this, arguments) || this;
  52745. }
  52746. SineEase.prototype.easeInCore = function (gradient) {
  52747. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52748. };
  52749. return SineEase;
  52750. }(EasingFunction));
  52751. BABYLON.SineEase = SineEase;
  52752. var BezierCurveEase = /** @class */ (function (_super) {
  52753. __extends(BezierCurveEase, _super);
  52754. function BezierCurveEase(x1, y1, x2, y2) {
  52755. if (x1 === void 0) { x1 = 0; }
  52756. if (y1 === void 0) { y1 = 0; }
  52757. if (x2 === void 0) { x2 = 1; }
  52758. if (y2 === void 0) { y2 = 1; }
  52759. var _this = _super.call(this) || this;
  52760. _this.x1 = x1;
  52761. _this.y1 = y1;
  52762. _this.x2 = x2;
  52763. _this.y2 = y2;
  52764. return _this;
  52765. }
  52766. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52767. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52768. };
  52769. return BezierCurveEase;
  52770. }(EasingFunction));
  52771. BABYLON.BezierCurveEase = BezierCurveEase;
  52772. })(BABYLON || (BABYLON = {}));
  52773. //# sourceMappingURL=babylon.easing.js.map
  52774. var BABYLON;
  52775. (function (BABYLON) {
  52776. /**
  52777. * A Condition applied to an Action
  52778. */
  52779. var Condition = /** @class */ (function () {
  52780. /**
  52781. * Creates a new Condition
  52782. * @param actionManager the manager of the action the condition is applied to
  52783. */
  52784. function Condition(actionManager) {
  52785. this._actionManager = actionManager;
  52786. }
  52787. /**
  52788. * Check if the current condition is valid
  52789. * @returns a boolean
  52790. */
  52791. Condition.prototype.isValid = function () {
  52792. return true;
  52793. };
  52794. /**
  52795. * Internal only
  52796. * @hidden
  52797. */
  52798. Condition.prototype._getProperty = function (propertyPath) {
  52799. return this._actionManager._getProperty(propertyPath);
  52800. };
  52801. /**
  52802. * Internal only
  52803. * @hidden
  52804. */
  52805. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52806. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52807. };
  52808. /**
  52809. * Serialize placeholder for child classes
  52810. * @returns the serialized object
  52811. */
  52812. Condition.prototype.serialize = function () {
  52813. };
  52814. /**
  52815. * Internal only
  52816. * @hidden
  52817. */
  52818. Condition.prototype._serialize = function (serializedCondition) {
  52819. return {
  52820. type: 2,
  52821. children: [],
  52822. name: serializedCondition.name,
  52823. properties: serializedCondition.properties
  52824. };
  52825. };
  52826. return Condition;
  52827. }());
  52828. BABYLON.Condition = Condition;
  52829. /**
  52830. * Defines specific conditional operators as extensions of Condition
  52831. */
  52832. var ValueCondition = /** @class */ (function (_super) {
  52833. __extends(ValueCondition, _super);
  52834. /**
  52835. * Creates a new ValueCondition
  52836. * @param actionManager manager for the action the condition applies to
  52837. * @param target for the action
  52838. * @param propertyPath path to specify the property of the target the conditional operator uses
  52839. * @param value the value compared by the conditional operator against the current value of the property
  52840. * @param operator the conditional operator, default ValueCondition.IsEqual
  52841. */
  52842. function ValueCondition(actionManager, target,
  52843. /** path to specify the property of the target the conditional operator uses */
  52844. propertyPath,
  52845. /** the value compared by the conditional operator against the current value of the property */
  52846. value,
  52847. /** the conditional operator, default ValueCondition.IsEqual */
  52848. operator) {
  52849. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52850. var _this = _super.call(this, actionManager) || this;
  52851. _this.propertyPath = propertyPath;
  52852. _this.value = value;
  52853. _this.operator = operator;
  52854. _this._target = target;
  52855. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52856. _this._property = _this._getProperty(_this.propertyPath);
  52857. return _this;
  52858. }
  52859. Object.defineProperty(ValueCondition, "IsEqual", {
  52860. /**
  52861. * returns the number for IsEqual
  52862. */
  52863. get: function () {
  52864. return ValueCondition._IsEqual;
  52865. },
  52866. enumerable: true,
  52867. configurable: true
  52868. });
  52869. Object.defineProperty(ValueCondition, "IsDifferent", {
  52870. /**
  52871. * Returns the number for IsDifferent
  52872. */
  52873. get: function () {
  52874. return ValueCondition._IsDifferent;
  52875. },
  52876. enumerable: true,
  52877. configurable: true
  52878. });
  52879. Object.defineProperty(ValueCondition, "IsGreater", {
  52880. /**
  52881. * Returns the number for IsGreater
  52882. */
  52883. get: function () {
  52884. return ValueCondition._IsGreater;
  52885. },
  52886. enumerable: true,
  52887. configurable: true
  52888. });
  52889. Object.defineProperty(ValueCondition, "IsLesser", {
  52890. /**
  52891. * Returns the number for IsLesser
  52892. */
  52893. get: function () {
  52894. return ValueCondition._IsLesser;
  52895. },
  52896. enumerable: true,
  52897. configurable: true
  52898. });
  52899. /**
  52900. * Compares the given value with the property value for the specified conditional operator
  52901. * @returns the result of the comparison
  52902. */
  52903. ValueCondition.prototype.isValid = function () {
  52904. switch (this.operator) {
  52905. case ValueCondition.IsGreater:
  52906. return this._effectiveTarget[this._property] > this.value;
  52907. case ValueCondition.IsLesser:
  52908. return this._effectiveTarget[this._property] < this.value;
  52909. case ValueCondition.IsEqual:
  52910. case ValueCondition.IsDifferent:
  52911. var check;
  52912. if (this.value.equals) {
  52913. check = this.value.equals(this._effectiveTarget[this._property]);
  52914. }
  52915. else {
  52916. check = this.value === this._effectiveTarget[this._property];
  52917. }
  52918. return this.operator === ValueCondition.IsEqual ? check : !check;
  52919. }
  52920. return false;
  52921. };
  52922. /**
  52923. * Serialize the ValueCondition into a JSON compatible object
  52924. * @returns serialization object
  52925. */
  52926. ValueCondition.prototype.serialize = function () {
  52927. return this._serialize({
  52928. name: "ValueCondition",
  52929. properties: [
  52930. BABYLON.Action._GetTargetProperty(this._target),
  52931. { name: "propertyPath", value: this.propertyPath },
  52932. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52933. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52934. ]
  52935. });
  52936. };
  52937. /**
  52938. * Gets the name of the conditional operator for the ValueCondition
  52939. * @param operator the conditional operator
  52940. * @returns the name
  52941. */
  52942. ValueCondition.GetOperatorName = function (operator) {
  52943. switch (operator) {
  52944. case ValueCondition._IsEqual: return "IsEqual";
  52945. case ValueCondition._IsDifferent: return "IsDifferent";
  52946. case ValueCondition._IsGreater: return "IsGreater";
  52947. case ValueCondition._IsLesser: return "IsLesser";
  52948. default: return "";
  52949. }
  52950. };
  52951. /**
  52952. * Internal only
  52953. * @hidden
  52954. */
  52955. ValueCondition._IsEqual = 0;
  52956. /**
  52957. * Internal only
  52958. * @hidden
  52959. */
  52960. ValueCondition._IsDifferent = 1;
  52961. /**
  52962. * Internal only
  52963. * @hidden
  52964. */
  52965. ValueCondition._IsGreater = 2;
  52966. /**
  52967. * Internal only
  52968. * @hidden
  52969. */
  52970. ValueCondition._IsLesser = 3;
  52971. return ValueCondition;
  52972. }(Condition));
  52973. BABYLON.ValueCondition = ValueCondition;
  52974. /**
  52975. * Defines a predicate condition as an extension of Condition
  52976. */
  52977. var PredicateCondition = /** @class */ (function (_super) {
  52978. __extends(PredicateCondition, _super);
  52979. /**
  52980. * Creates a new PredicateCondition
  52981. * @param actionManager manager for the action the condition applies to
  52982. * @param predicate defines the predicate function used to validate the condition
  52983. */
  52984. function PredicateCondition(actionManager,
  52985. /** defines the predicate function used to validate the condition */
  52986. predicate) {
  52987. var _this = _super.call(this, actionManager) || this;
  52988. _this.predicate = predicate;
  52989. return _this;
  52990. }
  52991. /**
  52992. * @returns the validity of the predicate condition
  52993. */
  52994. PredicateCondition.prototype.isValid = function () {
  52995. return this.predicate();
  52996. };
  52997. return PredicateCondition;
  52998. }(Condition));
  52999. BABYLON.PredicateCondition = PredicateCondition;
  53000. /**
  53001. * Defines a state condition as an extension of Condition
  53002. */
  53003. var StateCondition = /** @class */ (function (_super) {
  53004. __extends(StateCondition, _super);
  53005. /**
  53006. * Creates a new StateCondition
  53007. * @param actionManager manager for the action the condition applies to
  53008. * @param target of the condition
  53009. * @param value to compare with target state
  53010. */
  53011. function StateCondition(actionManager, target, value) {
  53012. var _this = _super.call(this, actionManager) || this;
  53013. _this.value = value;
  53014. _this._target = target;
  53015. return _this;
  53016. }
  53017. /**
  53018. * @returns the validity of the state
  53019. */
  53020. StateCondition.prototype.isValid = function () {
  53021. return this._target.state === this.value;
  53022. };
  53023. /**
  53024. * Serialize the StateCondition into a JSON compatible object
  53025. * @returns serialization object
  53026. */
  53027. StateCondition.prototype.serialize = function () {
  53028. return this._serialize({
  53029. name: "StateCondition",
  53030. properties: [
  53031. BABYLON.Action._GetTargetProperty(this._target),
  53032. { name: "value", value: this.value }
  53033. ]
  53034. });
  53035. };
  53036. return StateCondition;
  53037. }(Condition));
  53038. BABYLON.StateCondition = StateCondition;
  53039. })(BABYLON || (BABYLON = {}));
  53040. //# sourceMappingURL=babylon.condition.js.map
  53041. var BABYLON;
  53042. (function (BABYLON) {
  53043. /**
  53044. * The action to be carried out following a trigger
  53045. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53046. */
  53047. var Action = /** @class */ (function () {
  53048. /**
  53049. * Creates a new Action
  53050. * @param triggerOptions the trigger, with or without parameters, for the action
  53051. * @param condition an optional determinant of action
  53052. */
  53053. function Action(
  53054. /** the trigger, with or without parameters, for the action */
  53055. triggerOptions, condition) {
  53056. this.triggerOptions = triggerOptions;
  53057. /**
  53058. * An event triggered prior to action being executed.
  53059. */
  53060. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53061. if (triggerOptions.parameter) {
  53062. this.trigger = triggerOptions.trigger;
  53063. this._triggerParameter = triggerOptions.parameter;
  53064. }
  53065. else {
  53066. this.trigger = triggerOptions;
  53067. }
  53068. this._nextActiveAction = this;
  53069. this._condition = condition;
  53070. }
  53071. /**
  53072. * Internal only
  53073. * @hidden
  53074. */
  53075. Action.prototype._prepare = function () {
  53076. };
  53077. /**
  53078. * Gets the trigger parameters
  53079. * @returns the trigger parameters
  53080. */
  53081. Action.prototype.getTriggerParameter = function () {
  53082. return this._triggerParameter;
  53083. };
  53084. /**
  53085. * Internal only - executes current action event
  53086. * @hidden
  53087. */
  53088. Action.prototype._executeCurrent = function (evt) {
  53089. if (this._nextActiveAction._condition) {
  53090. var condition = this._nextActiveAction._condition;
  53091. var currentRenderId = this._actionManager.getScene().getRenderId();
  53092. // We cache the current evaluation for the current frame
  53093. if (condition._evaluationId === currentRenderId) {
  53094. if (!condition._currentResult) {
  53095. return;
  53096. }
  53097. }
  53098. else {
  53099. condition._evaluationId = currentRenderId;
  53100. if (!condition.isValid()) {
  53101. condition._currentResult = false;
  53102. return;
  53103. }
  53104. condition._currentResult = true;
  53105. }
  53106. }
  53107. this.onBeforeExecuteObservable.notifyObservers(this);
  53108. this._nextActiveAction.execute(evt);
  53109. this.skipToNextActiveAction();
  53110. };
  53111. /**
  53112. * Execute placeholder for child classes
  53113. * @param evt optional action event
  53114. */
  53115. Action.prototype.execute = function (evt) {
  53116. };
  53117. /**
  53118. * Skips to next active action
  53119. */
  53120. Action.prototype.skipToNextActiveAction = function () {
  53121. if (this._nextActiveAction._child) {
  53122. if (!this._nextActiveAction._child._actionManager) {
  53123. this._nextActiveAction._child._actionManager = this._actionManager;
  53124. }
  53125. this._nextActiveAction = this._nextActiveAction._child;
  53126. }
  53127. else {
  53128. this._nextActiveAction = this;
  53129. }
  53130. };
  53131. /**
  53132. * Adds action to chain of actions, may be a DoNothingAction
  53133. * @param action defines the next action to execute
  53134. * @returns The action passed in
  53135. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53136. */
  53137. Action.prototype.then = function (action) {
  53138. this._child = action;
  53139. action._actionManager = this._actionManager;
  53140. action._prepare();
  53141. return action;
  53142. };
  53143. /**
  53144. * Internal only
  53145. * @hidden
  53146. */
  53147. Action.prototype._getProperty = function (propertyPath) {
  53148. return this._actionManager._getProperty(propertyPath);
  53149. };
  53150. /**
  53151. * Internal only
  53152. * @hidden
  53153. */
  53154. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53155. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53156. };
  53157. /**
  53158. * Serialize placeholder for child classes
  53159. * @param parent of child
  53160. * @returns the serialized object
  53161. */
  53162. Action.prototype.serialize = function (parent) {
  53163. };
  53164. /**
  53165. * Internal only called by serialize
  53166. * @hidden
  53167. */
  53168. Action.prototype._serialize = function (serializedAction, parent) {
  53169. var serializationObject = {
  53170. type: 1,
  53171. children: [],
  53172. name: serializedAction.name,
  53173. properties: serializedAction.properties || []
  53174. };
  53175. // Serialize child
  53176. if (this._child) {
  53177. this._child.serialize(serializationObject);
  53178. }
  53179. // Check if "this" has a condition
  53180. if (this._condition) {
  53181. var serializedCondition = this._condition.serialize();
  53182. serializedCondition.children.push(serializationObject);
  53183. if (parent) {
  53184. parent.children.push(serializedCondition);
  53185. }
  53186. return serializedCondition;
  53187. }
  53188. if (parent) {
  53189. parent.children.push(serializationObject);
  53190. }
  53191. return serializationObject;
  53192. };
  53193. /**
  53194. * Internal only
  53195. * @hidden
  53196. */
  53197. Action._SerializeValueAsString = function (value) {
  53198. if (typeof value === "number") {
  53199. return value.toString();
  53200. }
  53201. if (typeof value === "boolean") {
  53202. return value ? "true" : "false";
  53203. }
  53204. if (value instanceof BABYLON.Vector2) {
  53205. return value.x + ", " + value.y;
  53206. }
  53207. if (value instanceof BABYLON.Vector3) {
  53208. return value.x + ", " + value.y + ", " + value.z;
  53209. }
  53210. if (value instanceof BABYLON.Color3) {
  53211. return value.r + ", " + value.g + ", " + value.b;
  53212. }
  53213. if (value instanceof BABYLON.Color4) {
  53214. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53215. }
  53216. return value; // string
  53217. };
  53218. /**
  53219. * Internal only
  53220. * @hidden
  53221. */
  53222. Action._GetTargetProperty = function (target) {
  53223. return {
  53224. name: "target",
  53225. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53226. : target instanceof BABYLON.Light ? "LightProperties"
  53227. : target instanceof BABYLON.Camera ? "CameraProperties"
  53228. : "SceneProperties",
  53229. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53230. };
  53231. };
  53232. return Action;
  53233. }());
  53234. BABYLON.Action = Action;
  53235. })(BABYLON || (BABYLON = {}));
  53236. //# sourceMappingURL=babylon.action.js.map
  53237. var BABYLON;
  53238. (function (BABYLON) {
  53239. /**
  53240. * ActionEvent is the event being sent when an action is triggered.
  53241. */
  53242. var ActionEvent = /** @class */ (function () {
  53243. /**
  53244. * Creates a new ActionEvent
  53245. * @param source The mesh or sprite that triggered the action
  53246. * @param pointerX The X mouse cursor position at the time of the event
  53247. * @param pointerY The Y mouse cursor position at the time of the event
  53248. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53249. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53250. * @param additionalData additional data for the event
  53251. */
  53252. function ActionEvent(
  53253. /** The mesh or sprite that triggered the action */
  53254. source,
  53255. /** The X mouse cursor position at the time of the event */
  53256. pointerX,
  53257. /** The Y mouse cursor position at the time of the event */
  53258. pointerY,
  53259. /** The mesh that is currently pointed at (can be null) */
  53260. meshUnderPointer,
  53261. /** the original (browser) event that triggered the ActionEvent */
  53262. sourceEvent,
  53263. /** additional data for the event */
  53264. additionalData) {
  53265. this.source = source;
  53266. this.pointerX = pointerX;
  53267. this.pointerY = pointerY;
  53268. this.meshUnderPointer = meshUnderPointer;
  53269. this.sourceEvent = sourceEvent;
  53270. this.additionalData = additionalData;
  53271. }
  53272. /**
  53273. * Helper function to auto-create an ActionEvent from a source mesh.
  53274. * @param source The source mesh that triggered the event
  53275. * @param evt The original (browser) event
  53276. * @param additionalData additional data for the event
  53277. * @returns the new ActionEvent
  53278. */
  53279. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53280. var scene = source.getScene();
  53281. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53282. };
  53283. /**
  53284. * Helper function to auto-create an ActionEvent from a source sprite
  53285. * @param source The source sprite that triggered the event
  53286. * @param scene Scene associated with the sprite
  53287. * @param evt The original (browser) event
  53288. * @param additionalData additional data for the event
  53289. * @returns the new ActionEvent
  53290. */
  53291. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53292. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53293. };
  53294. /**
  53295. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53296. * @param scene the scene where the event occurred
  53297. * @param evt The original (browser) event
  53298. * @returns the new ActionEvent
  53299. */
  53300. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53301. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53302. };
  53303. /**
  53304. * Helper function to auto-create an ActionEvent from a primitive
  53305. * @param prim defines the target primitive
  53306. * @param pointerPos defines the pointer position
  53307. * @param evt The original (browser) event
  53308. * @param additionalData additional data for the event
  53309. * @returns the new ActionEvent
  53310. */
  53311. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53312. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53313. };
  53314. return ActionEvent;
  53315. }());
  53316. BABYLON.ActionEvent = ActionEvent;
  53317. /**
  53318. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53319. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53320. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53321. */
  53322. var ActionManager = /** @class */ (function () {
  53323. /**
  53324. * Creates a new action manager
  53325. * @param scene defines the hosting scene
  53326. */
  53327. function ActionManager(scene) {
  53328. // Members
  53329. /** Gets the list of actions */
  53330. this.actions = new Array();
  53331. /** Gets the cursor to use when hovering items */
  53332. this.hoverCursor = '';
  53333. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53334. scene._actionManagers.push(this);
  53335. }
  53336. Object.defineProperty(ActionManager, "NothingTrigger", {
  53337. /**
  53338. * Nothing
  53339. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53340. */
  53341. get: function () {
  53342. return ActionManager._NothingTrigger;
  53343. },
  53344. enumerable: true,
  53345. configurable: true
  53346. });
  53347. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53348. /**
  53349. * On pick
  53350. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53351. */
  53352. get: function () {
  53353. return ActionManager._OnPickTrigger;
  53354. },
  53355. enumerable: true,
  53356. configurable: true
  53357. });
  53358. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53359. /**
  53360. * On left pick
  53361. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53362. */
  53363. get: function () {
  53364. return ActionManager._OnLeftPickTrigger;
  53365. },
  53366. enumerable: true,
  53367. configurable: true
  53368. });
  53369. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53370. /**
  53371. * On right pick
  53372. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53373. */
  53374. get: function () {
  53375. return ActionManager._OnRightPickTrigger;
  53376. },
  53377. enumerable: true,
  53378. configurable: true
  53379. });
  53380. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53381. /**
  53382. * On center pick
  53383. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53384. */
  53385. get: function () {
  53386. return ActionManager._OnCenterPickTrigger;
  53387. },
  53388. enumerable: true,
  53389. configurable: true
  53390. });
  53391. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53392. /**
  53393. * On pick down
  53394. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53395. */
  53396. get: function () {
  53397. return ActionManager._OnPickDownTrigger;
  53398. },
  53399. enumerable: true,
  53400. configurable: true
  53401. });
  53402. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53403. /**
  53404. * On double pick
  53405. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53406. */
  53407. get: function () {
  53408. return ActionManager._OnDoublePickTrigger;
  53409. },
  53410. enumerable: true,
  53411. configurable: true
  53412. });
  53413. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53414. /**
  53415. * On pick up
  53416. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53417. */
  53418. get: function () {
  53419. return ActionManager._OnPickUpTrigger;
  53420. },
  53421. enumerable: true,
  53422. configurable: true
  53423. });
  53424. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53425. /**
  53426. * On pick out.
  53427. * This trigger will only be raised if you also declared a OnPickDown
  53428. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53429. */
  53430. get: function () {
  53431. return ActionManager._OnPickOutTrigger;
  53432. },
  53433. enumerable: true,
  53434. configurable: true
  53435. });
  53436. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53437. /**
  53438. * On long press
  53439. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53440. */
  53441. get: function () {
  53442. return ActionManager._OnLongPressTrigger;
  53443. },
  53444. enumerable: true,
  53445. configurable: true
  53446. });
  53447. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53448. /**
  53449. * On pointer over
  53450. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53451. */
  53452. get: function () {
  53453. return ActionManager._OnPointerOverTrigger;
  53454. },
  53455. enumerable: true,
  53456. configurable: true
  53457. });
  53458. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53459. /**
  53460. * On pointer out
  53461. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53462. */
  53463. get: function () {
  53464. return ActionManager._OnPointerOutTrigger;
  53465. },
  53466. enumerable: true,
  53467. configurable: true
  53468. });
  53469. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53470. /**
  53471. * On every frame
  53472. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53473. */
  53474. get: function () {
  53475. return ActionManager._OnEveryFrameTrigger;
  53476. },
  53477. enumerable: true,
  53478. configurable: true
  53479. });
  53480. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53481. /**
  53482. * On intersection enter
  53483. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53484. */
  53485. get: function () {
  53486. return ActionManager._OnIntersectionEnterTrigger;
  53487. },
  53488. enumerable: true,
  53489. configurable: true
  53490. });
  53491. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53492. /**
  53493. * On intersection exit
  53494. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53495. */
  53496. get: function () {
  53497. return ActionManager._OnIntersectionExitTrigger;
  53498. },
  53499. enumerable: true,
  53500. configurable: true
  53501. });
  53502. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53503. /**
  53504. * On key down
  53505. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53506. */
  53507. get: function () {
  53508. return ActionManager._OnKeyDownTrigger;
  53509. },
  53510. enumerable: true,
  53511. configurable: true
  53512. });
  53513. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53514. /**
  53515. * On key up
  53516. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53517. */
  53518. get: function () {
  53519. return ActionManager._OnKeyUpTrigger;
  53520. },
  53521. enumerable: true,
  53522. configurable: true
  53523. });
  53524. // Methods
  53525. /**
  53526. * Releases all associated resources
  53527. */
  53528. ActionManager.prototype.dispose = function () {
  53529. var index = this._scene._actionManagers.indexOf(this);
  53530. for (var i = 0; i < this.actions.length; i++) {
  53531. var action = this.actions[i];
  53532. ActionManager.Triggers[action.trigger]--;
  53533. if (ActionManager.Triggers[action.trigger] === 0) {
  53534. delete ActionManager.Triggers[action.trigger];
  53535. }
  53536. }
  53537. if (index > -1) {
  53538. this._scene._actionManagers.splice(index, 1);
  53539. }
  53540. };
  53541. /**
  53542. * Gets hosting scene
  53543. * @returns the hosting scene
  53544. */
  53545. ActionManager.prototype.getScene = function () {
  53546. return this._scene;
  53547. };
  53548. /**
  53549. * Does this action manager handles actions of any of the given triggers
  53550. * @param triggers defines the triggers to be tested
  53551. * @return a boolean indicating whether one (or more) of the triggers is handled
  53552. */
  53553. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53554. for (var index = 0; index < this.actions.length; index++) {
  53555. var action = this.actions[index];
  53556. if (triggers.indexOf(action.trigger) > -1) {
  53557. return true;
  53558. }
  53559. }
  53560. return false;
  53561. };
  53562. /**
  53563. * Does this action manager handles actions of a given trigger
  53564. * @param trigger defines the trigger to be tested
  53565. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53566. * @return whether the trigger is handled
  53567. */
  53568. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53569. for (var index = 0; index < this.actions.length; index++) {
  53570. var action = this.actions[index];
  53571. if (action.trigger === trigger) {
  53572. if (parameterPredicate) {
  53573. if (parameterPredicate(action.getTriggerParameter())) {
  53574. return true;
  53575. }
  53576. }
  53577. else {
  53578. return true;
  53579. }
  53580. }
  53581. }
  53582. return false;
  53583. };
  53584. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53585. /**
  53586. * Does this action manager has pointer triggers
  53587. */
  53588. get: function () {
  53589. for (var index = 0; index < this.actions.length; index++) {
  53590. var action = this.actions[index];
  53591. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53592. return true;
  53593. }
  53594. }
  53595. return false;
  53596. },
  53597. enumerable: true,
  53598. configurable: true
  53599. });
  53600. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53601. /**
  53602. * Does this action manager has pick triggers
  53603. */
  53604. get: function () {
  53605. for (var index = 0; index < this.actions.length; index++) {
  53606. var action = this.actions[index];
  53607. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53608. return true;
  53609. }
  53610. }
  53611. return false;
  53612. },
  53613. enumerable: true,
  53614. configurable: true
  53615. });
  53616. Object.defineProperty(ActionManager, "HasTriggers", {
  53617. /**
  53618. * Does exist one action manager with at least one trigger
  53619. **/
  53620. get: function () {
  53621. for (var t in ActionManager.Triggers) {
  53622. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53623. return true;
  53624. }
  53625. }
  53626. return false;
  53627. },
  53628. enumerable: true,
  53629. configurable: true
  53630. });
  53631. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53632. /**
  53633. * Does exist one action manager with at least one pick trigger
  53634. **/
  53635. get: function () {
  53636. for (var t in ActionManager.Triggers) {
  53637. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53638. var t_int = parseInt(t);
  53639. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53640. return true;
  53641. }
  53642. }
  53643. }
  53644. return false;
  53645. },
  53646. enumerable: true,
  53647. configurable: true
  53648. });
  53649. /**
  53650. * Does exist one action manager that handles actions of a given trigger
  53651. * @param trigger defines the trigger to be tested
  53652. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53653. **/
  53654. ActionManager.HasSpecificTrigger = function (trigger) {
  53655. for (var t in ActionManager.Triggers) {
  53656. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53657. var t_int = parseInt(t);
  53658. if (t_int === trigger) {
  53659. return true;
  53660. }
  53661. }
  53662. }
  53663. return false;
  53664. };
  53665. /**
  53666. * Registers an action to this action manager
  53667. * @param action defines the action to be registered
  53668. * @return the action amended (prepared) after registration
  53669. */
  53670. ActionManager.prototype.registerAction = function (action) {
  53671. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53672. if (this.getScene().actionManager !== this) {
  53673. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53674. return null;
  53675. }
  53676. }
  53677. this.actions.push(action);
  53678. if (ActionManager.Triggers[action.trigger]) {
  53679. ActionManager.Triggers[action.trigger]++;
  53680. }
  53681. else {
  53682. ActionManager.Triggers[action.trigger] = 1;
  53683. }
  53684. action._actionManager = this;
  53685. action._prepare();
  53686. return action;
  53687. };
  53688. /**
  53689. * Unregisters an action to this action manager
  53690. * @param action defines the action to be unregistered
  53691. * @return a boolean indicating whether the action has been unregistered
  53692. */
  53693. ActionManager.prototype.unregisterAction = function (action) {
  53694. var index = this.actions.indexOf(action);
  53695. if (index !== -1) {
  53696. this.actions.splice(index, 1);
  53697. ActionManager.Triggers[action.trigger] -= 1;
  53698. if (ActionManager.Triggers[action.trigger] === 0) {
  53699. delete ActionManager.Triggers[action.trigger];
  53700. }
  53701. delete action._actionManager;
  53702. return true;
  53703. }
  53704. return false;
  53705. };
  53706. /**
  53707. * Process a specific trigger
  53708. * @param trigger defines the trigger to process
  53709. * @param evt defines the event details to be processed
  53710. */
  53711. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53712. for (var index = 0; index < this.actions.length; index++) {
  53713. var action = this.actions[index];
  53714. if (action.trigger === trigger) {
  53715. if (evt) {
  53716. if (trigger === ActionManager.OnKeyUpTrigger
  53717. || trigger === ActionManager.OnKeyDownTrigger) {
  53718. var parameter = action.getTriggerParameter();
  53719. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53720. if (!parameter.toLowerCase) {
  53721. continue;
  53722. }
  53723. var lowerCase = parameter.toLowerCase();
  53724. if (lowerCase !== evt.sourceEvent.key) {
  53725. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53726. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53727. if (actualkey !== lowerCase) {
  53728. continue;
  53729. }
  53730. }
  53731. }
  53732. }
  53733. }
  53734. action._executeCurrent(evt);
  53735. }
  53736. }
  53737. };
  53738. /** @hidden */
  53739. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53740. var properties = propertyPath.split(".");
  53741. for (var index = 0; index < properties.length - 1; index++) {
  53742. target = target[properties[index]];
  53743. }
  53744. return target;
  53745. };
  53746. /** @hidden */
  53747. ActionManager.prototype._getProperty = function (propertyPath) {
  53748. var properties = propertyPath.split(".");
  53749. return properties[properties.length - 1];
  53750. };
  53751. /**
  53752. * Serialize this manager to a JSON object
  53753. * @param name defines the property name to store this manager
  53754. * @returns a JSON representation of this manager
  53755. */
  53756. ActionManager.prototype.serialize = function (name) {
  53757. var root = {
  53758. children: new Array(),
  53759. name: name,
  53760. type: 3,
  53761. properties: new Array() // Empty for root but required
  53762. };
  53763. for (var i = 0; i < this.actions.length; i++) {
  53764. var triggerObject = {
  53765. type: 0,
  53766. children: new Array(),
  53767. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53768. properties: new Array()
  53769. };
  53770. var triggerOptions = this.actions[i].triggerOptions;
  53771. if (triggerOptions && typeof triggerOptions !== "number") {
  53772. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53773. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53774. }
  53775. else {
  53776. var parameter = {};
  53777. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53778. if (triggerOptions.parameter.mesh) {
  53779. parameter._meshId = triggerOptions.parameter.mesh.id;
  53780. }
  53781. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53782. }
  53783. }
  53784. // Serialize child action, recursively
  53785. this.actions[i].serialize(triggerObject);
  53786. // Add serialized trigger
  53787. root.children.push(triggerObject);
  53788. }
  53789. return root;
  53790. };
  53791. /**
  53792. * Creates a new ActionManager from a JSON data
  53793. * @param parsedActions defines the JSON data to read from
  53794. * @param object defines the hosting mesh
  53795. * @param scene defines the hosting scene
  53796. */
  53797. ActionManager.Parse = function (parsedActions, object, scene) {
  53798. var actionManager = new ActionManager(scene);
  53799. if (object === null)
  53800. scene.actionManager = actionManager;
  53801. else
  53802. object.actionManager = actionManager;
  53803. // instanciate a new object
  53804. var instanciate = function (name, params) {
  53805. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53806. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53807. newInstance.constructor.apply(newInstance, params);
  53808. return newInstance;
  53809. };
  53810. var parseParameter = function (name, value, target, propertyPath) {
  53811. if (propertyPath === null) {
  53812. // String, boolean or float
  53813. var floatValue = parseFloat(value);
  53814. if (value === "true" || value === "false")
  53815. return value === "true";
  53816. else
  53817. return isNaN(floatValue) ? value : floatValue;
  53818. }
  53819. var effectiveTarget = propertyPath.split(".");
  53820. var values = value.split(",");
  53821. // Get effective Target
  53822. for (var i = 0; i < effectiveTarget.length; i++) {
  53823. target = target[effectiveTarget[i]];
  53824. }
  53825. // Return appropriate value with its type
  53826. if (typeof (target) === "boolean")
  53827. return values[0] === "true";
  53828. if (typeof (target) === "string")
  53829. return values[0];
  53830. // Parameters with multiple values such as Vector3 etc.
  53831. var split = new Array();
  53832. for (var i = 0; i < values.length; i++)
  53833. split.push(parseFloat(values[i]));
  53834. if (target instanceof BABYLON.Vector3)
  53835. return BABYLON.Vector3.FromArray(split);
  53836. if (target instanceof BABYLON.Vector4)
  53837. return BABYLON.Vector4.FromArray(split);
  53838. if (target instanceof BABYLON.Color3)
  53839. return BABYLON.Color3.FromArray(split);
  53840. if (target instanceof BABYLON.Color4)
  53841. return BABYLON.Color4.FromArray(split);
  53842. return parseFloat(values[0]);
  53843. };
  53844. // traverse graph per trigger
  53845. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53846. if (combineArray === void 0) { combineArray = null; }
  53847. if (parsedAction.detached)
  53848. return;
  53849. var parameters = new Array();
  53850. var target = null;
  53851. var propertyPath = null;
  53852. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53853. // Parameters
  53854. if (parsedAction.type === 2)
  53855. parameters.push(actionManager);
  53856. else
  53857. parameters.push(trigger);
  53858. if (combine) {
  53859. var actions = new Array();
  53860. for (var j = 0; j < parsedAction.combine.length; j++) {
  53861. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53862. }
  53863. parameters.push(actions);
  53864. }
  53865. else {
  53866. for (var i = 0; i < parsedAction.properties.length; i++) {
  53867. var value = parsedAction.properties[i].value;
  53868. var name = parsedAction.properties[i].name;
  53869. var targetType = parsedAction.properties[i].targetType;
  53870. if (name === "target")
  53871. if (targetType !== null && targetType === "SceneProperties")
  53872. value = target = scene;
  53873. else
  53874. value = target = scene.getNodeByName(value);
  53875. else if (name === "parent")
  53876. value = scene.getNodeByName(value);
  53877. else if (name === "sound")
  53878. value = scene.getSoundByName(value);
  53879. else if (name !== "propertyPath") {
  53880. if (parsedAction.type === 2 && name === "operator")
  53881. value = BABYLON.ValueCondition[value];
  53882. else
  53883. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53884. }
  53885. else {
  53886. propertyPath = value;
  53887. }
  53888. parameters.push(value);
  53889. }
  53890. }
  53891. if (combineArray === null) {
  53892. parameters.push(condition);
  53893. }
  53894. else {
  53895. parameters.push(null);
  53896. }
  53897. // If interpolate value action
  53898. if (parsedAction.name === "InterpolateValueAction") {
  53899. var param = parameters[parameters.length - 2];
  53900. parameters[parameters.length - 1] = param;
  53901. parameters[parameters.length - 2] = condition;
  53902. }
  53903. // Action or condition(s) and not CombineAction
  53904. var newAction = instanciate(parsedAction.name, parameters);
  53905. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53906. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53907. if (action)
  53908. action.then(nothing);
  53909. else
  53910. actionManager.registerAction(nothing);
  53911. action = nothing;
  53912. }
  53913. if (combineArray === null) {
  53914. if (newAction instanceof BABYLON.Condition) {
  53915. condition = newAction;
  53916. newAction = action;
  53917. }
  53918. else {
  53919. condition = null;
  53920. if (action)
  53921. action.then(newAction);
  53922. else
  53923. actionManager.registerAction(newAction);
  53924. }
  53925. }
  53926. else {
  53927. combineArray.push(newAction);
  53928. }
  53929. for (var i = 0; i < parsedAction.children.length; i++)
  53930. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53931. };
  53932. // triggers
  53933. for (var i = 0; i < parsedActions.children.length; i++) {
  53934. var triggerParams;
  53935. var trigger = parsedActions.children[i];
  53936. if (trigger.properties.length > 0) {
  53937. var param = trigger.properties[0].value;
  53938. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53939. if (value._meshId) {
  53940. value.mesh = scene.getMeshByID(value._meshId);
  53941. }
  53942. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53943. }
  53944. else
  53945. triggerParams = ActionManager[trigger.name];
  53946. for (var j = 0; j < trigger.children.length; j++) {
  53947. if (!trigger.detached)
  53948. traverse(trigger.children[j], triggerParams, null, null);
  53949. }
  53950. }
  53951. };
  53952. /**
  53953. * Get a trigger name by index
  53954. * @param trigger defines the trigger index
  53955. * @returns a trigger name
  53956. */
  53957. ActionManager.GetTriggerName = function (trigger) {
  53958. switch (trigger) {
  53959. case 0: return "NothingTrigger";
  53960. case 1: return "OnPickTrigger";
  53961. case 2: return "OnLeftPickTrigger";
  53962. case 3: return "OnRightPickTrigger";
  53963. case 4: return "OnCenterPickTrigger";
  53964. case 5: return "OnPickDownTrigger";
  53965. case 6: return "OnPickUpTrigger";
  53966. case 7: return "OnLongPressTrigger";
  53967. case 8: return "OnPointerOverTrigger";
  53968. case 9: return "OnPointerOutTrigger";
  53969. case 10: return "OnEveryFrameTrigger";
  53970. case 11: return "OnIntersectionEnterTrigger";
  53971. case 12: return "OnIntersectionExitTrigger";
  53972. case 13: return "OnKeyDownTrigger";
  53973. case 14: return "OnKeyUpTrigger";
  53974. case 15: return "OnPickOutTrigger";
  53975. default: return "";
  53976. }
  53977. };
  53978. // Statics
  53979. ActionManager._NothingTrigger = 0;
  53980. ActionManager._OnPickTrigger = 1;
  53981. ActionManager._OnLeftPickTrigger = 2;
  53982. ActionManager._OnRightPickTrigger = 3;
  53983. ActionManager._OnCenterPickTrigger = 4;
  53984. ActionManager._OnPickDownTrigger = 5;
  53985. ActionManager._OnDoublePickTrigger = 6;
  53986. ActionManager._OnPickUpTrigger = 7;
  53987. ActionManager._OnLongPressTrigger = 8;
  53988. ActionManager._OnPointerOverTrigger = 9;
  53989. ActionManager._OnPointerOutTrigger = 10;
  53990. ActionManager._OnEveryFrameTrigger = 11;
  53991. ActionManager._OnIntersectionEnterTrigger = 12;
  53992. ActionManager._OnIntersectionExitTrigger = 13;
  53993. ActionManager._OnKeyDownTrigger = 14;
  53994. ActionManager._OnKeyUpTrigger = 15;
  53995. ActionManager._OnPickOutTrigger = 16;
  53996. /** Gets the list of active triggers */
  53997. ActionManager.Triggers = {};
  53998. return ActionManager;
  53999. }());
  54000. BABYLON.ActionManager = ActionManager;
  54001. })(BABYLON || (BABYLON = {}));
  54002. //# sourceMappingURL=babylon.actionManager.js.map
  54003. var BABYLON;
  54004. (function (BABYLON) {
  54005. var InterpolateValueAction = /** @class */ (function (_super) {
  54006. __extends(InterpolateValueAction, _super);
  54007. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54008. if (duration === void 0) { duration = 1000; }
  54009. var _this = _super.call(this, triggerOptions, condition) || this;
  54010. _this.propertyPath = propertyPath;
  54011. _this.value = value;
  54012. _this.duration = duration;
  54013. _this.stopOtherAnimations = stopOtherAnimations;
  54014. _this.onInterpolationDone = onInterpolationDone;
  54015. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54016. _this._target = _this._effectiveTarget = target;
  54017. return _this;
  54018. }
  54019. InterpolateValueAction.prototype._prepare = function () {
  54020. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54021. this._property = this._getProperty(this.propertyPath);
  54022. };
  54023. InterpolateValueAction.prototype.execute = function () {
  54024. var _this = this;
  54025. var scene = this._actionManager.getScene();
  54026. var keys = [
  54027. {
  54028. frame: 0,
  54029. value: this._effectiveTarget[this._property]
  54030. }, {
  54031. frame: 100,
  54032. value: this.value
  54033. }
  54034. ];
  54035. var dataType;
  54036. if (typeof this.value === "number") {
  54037. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54038. }
  54039. else if (this.value instanceof BABYLON.Color3) {
  54040. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54041. }
  54042. else if (this.value instanceof BABYLON.Vector3) {
  54043. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54044. }
  54045. else if (this.value instanceof BABYLON.Matrix) {
  54046. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54047. }
  54048. else if (this.value instanceof BABYLON.Quaternion) {
  54049. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54050. }
  54051. else {
  54052. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54053. return;
  54054. }
  54055. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54056. animation.setKeys(keys);
  54057. if (this.stopOtherAnimations) {
  54058. scene.stopAnimation(this._effectiveTarget);
  54059. }
  54060. var wrapper = function () {
  54061. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54062. if (_this.onInterpolationDone) {
  54063. _this.onInterpolationDone();
  54064. }
  54065. };
  54066. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54067. };
  54068. InterpolateValueAction.prototype.serialize = function (parent) {
  54069. return _super.prototype._serialize.call(this, {
  54070. name: "InterpolateValueAction",
  54071. properties: [
  54072. BABYLON.Action._GetTargetProperty(this._target),
  54073. { name: "propertyPath", value: this.propertyPath },
  54074. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54075. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54076. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54077. ]
  54078. }, parent);
  54079. };
  54080. return InterpolateValueAction;
  54081. }(BABYLON.Action));
  54082. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54083. })(BABYLON || (BABYLON = {}));
  54084. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54085. var BABYLON;
  54086. (function (BABYLON) {
  54087. var SwitchBooleanAction = /** @class */ (function (_super) {
  54088. __extends(SwitchBooleanAction, _super);
  54089. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54090. var _this = _super.call(this, triggerOptions, condition) || this;
  54091. _this.propertyPath = propertyPath;
  54092. _this._target = _this._effectiveTarget = target;
  54093. return _this;
  54094. }
  54095. SwitchBooleanAction.prototype._prepare = function () {
  54096. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54097. this._property = this._getProperty(this.propertyPath);
  54098. };
  54099. SwitchBooleanAction.prototype.execute = function () {
  54100. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54101. };
  54102. SwitchBooleanAction.prototype.serialize = function (parent) {
  54103. return _super.prototype._serialize.call(this, {
  54104. name: "SwitchBooleanAction",
  54105. properties: [
  54106. BABYLON.Action._GetTargetProperty(this._target),
  54107. { name: "propertyPath", value: this.propertyPath }
  54108. ]
  54109. }, parent);
  54110. };
  54111. return SwitchBooleanAction;
  54112. }(BABYLON.Action));
  54113. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54114. var SetStateAction = /** @class */ (function (_super) {
  54115. __extends(SetStateAction, _super);
  54116. function SetStateAction(triggerOptions, target, value, condition) {
  54117. var _this = _super.call(this, triggerOptions, condition) || this;
  54118. _this.value = value;
  54119. _this._target = target;
  54120. return _this;
  54121. }
  54122. SetStateAction.prototype.execute = function () {
  54123. this._target.state = this.value;
  54124. };
  54125. SetStateAction.prototype.serialize = function (parent) {
  54126. return _super.prototype._serialize.call(this, {
  54127. name: "SetStateAction",
  54128. properties: [
  54129. BABYLON.Action._GetTargetProperty(this._target),
  54130. { name: "value", value: this.value }
  54131. ]
  54132. }, parent);
  54133. };
  54134. return SetStateAction;
  54135. }(BABYLON.Action));
  54136. BABYLON.SetStateAction = SetStateAction;
  54137. var SetValueAction = /** @class */ (function (_super) {
  54138. __extends(SetValueAction, _super);
  54139. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54140. var _this = _super.call(this, triggerOptions, condition) || this;
  54141. _this.propertyPath = propertyPath;
  54142. _this.value = value;
  54143. _this._target = _this._effectiveTarget = target;
  54144. return _this;
  54145. }
  54146. SetValueAction.prototype._prepare = function () {
  54147. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54148. this._property = this._getProperty(this.propertyPath);
  54149. };
  54150. SetValueAction.prototype.execute = function () {
  54151. this._effectiveTarget[this._property] = this.value;
  54152. if (this._target.markAsDirty) {
  54153. this._target.markAsDirty(this._property);
  54154. }
  54155. };
  54156. SetValueAction.prototype.serialize = function (parent) {
  54157. return _super.prototype._serialize.call(this, {
  54158. name: "SetValueAction",
  54159. properties: [
  54160. BABYLON.Action._GetTargetProperty(this._target),
  54161. { name: "propertyPath", value: this.propertyPath },
  54162. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54163. ]
  54164. }, parent);
  54165. };
  54166. return SetValueAction;
  54167. }(BABYLON.Action));
  54168. BABYLON.SetValueAction = SetValueAction;
  54169. var IncrementValueAction = /** @class */ (function (_super) {
  54170. __extends(IncrementValueAction, _super);
  54171. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54172. var _this = _super.call(this, triggerOptions, condition) || this;
  54173. _this.propertyPath = propertyPath;
  54174. _this.value = value;
  54175. _this._target = _this._effectiveTarget = target;
  54176. return _this;
  54177. }
  54178. IncrementValueAction.prototype._prepare = function () {
  54179. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54180. this._property = this._getProperty(this.propertyPath);
  54181. if (typeof this._effectiveTarget[this._property] !== "number") {
  54182. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54183. }
  54184. };
  54185. IncrementValueAction.prototype.execute = function () {
  54186. this._effectiveTarget[this._property] += this.value;
  54187. if (this._target.markAsDirty) {
  54188. this._target.markAsDirty(this._property);
  54189. }
  54190. };
  54191. IncrementValueAction.prototype.serialize = function (parent) {
  54192. return _super.prototype._serialize.call(this, {
  54193. name: "IncrementValueAction",
  54194. properties: [
  54195. BABYLON.Action._GetTargetProperty(this._target),
  54196. { name: "propertyPath", value: this.propertyPath },
  54197. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54198. ]
  54199. }, parent);
  54200. };
  54201. return IncrementValueAction;
  54202. }(BABYLON.Action));
  54203. BABYLON.IncrementValueAction = IncrementValueAction;
  54204. var PlayAnimationAction = /** @class */ (function (_super) {
  54205. __extends(PlayAnimationAction, _super);
  54206. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54207. var _this = _super.call(this, triggerOptions, condition) || this;
  54208. _this.from = from;
  54209. _this.to = to;
  54210. _this.loop = loop;
  54211. _this._target = target;
  54212. return _this;
  54213. }
  54214. PlayAnimationAction.prototype._prepare = function () {
  54215. };
  54216. PlayAnimationAction.prototype.execute = function () {
  54217. var scene = this._actionManager.getScene();
  54218. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54219. };
  54220. PlayAnimationAction.prototype.serialize = function (parent) {
  54221. return _super.prototype._serialize.call(this, {
  54222. name: "PlayAnimationAction",
  54223. properties: [
  54224. BABYLON.Action._GetTargetProperty(this._target),
  54225. { name: "from", value: String(this.from) },
  54226. { name: "to", value: String(this.to) },
  54227. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54228. ]
  54229. }, parent);
  54230. };
  54231. return PlayAnimationAction;
  54232. }(BABYLON.Action));
  54233. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54234. var StopAnimationAction = /** @class */ (function (_super) {
  54235. __extends(StopAnimationAction, _super);
  54236. function StopAnimationAction(triggerOptions, target, condition) {
  54237. var _this = _super.call(this, triggerOptions, condition) || this;
  54238. _this._target = target;
  54239. return _this;
  54240. }
  54241. StopAnimationAction.prototype._prepare = function () {
  54242. };
  54243. StopAnimationAction.prototype.execute = function () {
  54244. var scene = this._actionManager.getScene();
  54245. scene.stopAnimation(this._target);
  54246. };
  54247. StopAnimationAction.prototype.serialize = function (parent) {
  54248. return _super.prototype._serialize.call(this, {
  54249. name: "StopAnimationAction",
  54250. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54251. }, parent);
  54252. };
  54253. return StopAnimationAction;
  54254. }(BABYLON.Action));
  54255. BABYLON.StopAnimationAction = StopAnimationAction;
  54256. var DoNothingAction = /** @class */ (function (_super) {
  54257. __extends(DoNothingAction, _super);
  54258. function DoNothingAction(triggerOptions, condition) {
  54259. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54260. return _super.call(this, triggerOptions, condition) || this;
  54261. }
  54262. DoNothingAction.prototype.execute = function () {
  54263. };
  54264. DoNothingAction.prototype.serialize = function (parent) {
  54265. return _super.prototype._serialize.call(this, {
  54266. name: "DoNothingAction",
  54267. properties: []
  54268. }, parent);
  54269. };
  54270. return DoNothingAction;
  54271. }(BABYLON.Action));
  54272. BABYLON.DoNothingAction = DoNothingAction;
  54273. var CombineAction = /** @class */ (function (_super) {
  54274. __extends(CombineAction, _super);
  54275. function CombineAction(triggerOptions, children, condition) {
  54276. var _this = _super.call(this, triggerOptions, condition) || this;
  54277. _this.children = children;
  54278. return _this;
  54279. }
  54280. CombineAction.prototype._prepare = function () {
  54281. for (var index = 0; index < this.children.length; index++) {
  54282. this.children[index]._actionManager = this._actionManager;
  54283. this.children[index]._prepare();
  54284. }
  54285. };
  54286. CombineAction.prototype.execute = function (evt) {
  54287. for (var index = 0; index < this.children.length; index++) {
  54288. this.children[index].execute(evt);
  54289. }
  54290. };
  54291. CombineAction.prototype.serialize = function (parent) {
  54292. var serializationObject = _super.prototype._serialize.call(this, {
  54293. name: "CombineAction",
  54294. properties: [],
  54295. combine: []
  54296. }, parent);
  54297. for (var i = 0; i < this.children.length; i++) {
  54298. serializationObject.combine.push(this.children[i].serialize(null));
  54299. }
  54300. return serializationObject;
  54301. };
  54302. return CombineAction;
  54303. }(BABYLON.Action));
  54304. BABYLON.CombineAction = CombineAction;
  54305. var ExecuteCodeAction = /** @class */ (function (_super) {
  54306. __extends(ExecuteCodeAction, _super);
  54307. function ExecuteCodeAction(triggerOptions, func, condition) {
  54308. var _this = _super.call(this, triggerOptions, condition) || this;
  54309. _this.func = func;
  54310. return _this;
  54311. }
  54312. ExecuteCodeAction.prototype.execute = function (evt) {
  54313. this.func(evt);
  54314. };
  54315. return ExecuteCodeAction;
  54316. }(BABYLON.Action));
  54317. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54318. var SetParentAction = /** @class */ (function (_super) {
  54319. __extends(SetParentAction, _super);
  54320. function SetParentAction(triggerOptions, target, parent, condition) {
  54321. var _this = _super.call(this, triggerOptions, condition) || this;
  54322. _this._target = target;
  54323. _this._parent = parent;
  54324. return _this;
  54325. }
  54326. SetParentAction.prototype._prepare = function () {
  54327. };
  54328. SetParentAction.prototype.execute = function () {
  54329. if (this._target.parent === this._parent) {
  54330. return;
  54331. }
  54332. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54333. invertParentWorldMatrix.invert();
  54334. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54335. this._target.parent = this._parent;
  54336. };
  54337. SetParentAction.prototype.serialize = function (parent) {
  54338. return _super.prototype._serialize.call(this, {
  54339. name: "SetParentAction",
  54340. properties: [
  54341. BABYLON.Action._GetTargetProperty(this._target),
  54342. BABYLON.Action._GetTargetProperty(this._parent),
  54343. ]
  54344. }, parent);
  54345. };
  54346. return SetParentAction;
  54347. }(BABYLON.Action));
  54348. BABYLON.SetParentAction = SetParentAction;
  54349. var PlaySoundAction = /** @class */ (function (_super) {
  54350. __extends(PlaySoundAction, _super);
  54351. function PlaySoundAction(triggerOptions, sound, condition) {
  54352. var _this = _super.call(this, triggerOptions, condition) || this;
  54353. _this._sound = sound;
  54354. return _this;
  54355. }
  54356. PlaySoundAction.prototype._prepare = function () {
  54357. };
  54358. PlaySoundAction.prototype.execute = function () {
  54359. if (this._sound !== undefined)
  54360. this._sound.play();
  54361. };
  54362. PlaySoundAction.prototype.serialize = function (parent) {
  54363. return _super.prototype._serialize.call(this, {
  54364. name: "PlaySoundAction",
  54365. properties: [{ name: "sound", value: this._sound.name }]
  54366. }, parent);
  54367. };
  54368. return PlaySoundAction;
  54369. }(BABYLON.Action));
  54370. BABYLON.PlaySoundAction = PlaySoundAction;
  54371. var StopSoundAction = /** @class */ (function (_super) {
  54372. __extends(StopSoundAction, _super);
  54373. function StopSoundAction(triggerOptions, sound, condition) {
  54374. var _this = _super.call(this, triggerOptions, condition) || this;
  54375. _this._sound = sound;
  54376. return _this;
  54377. }
  54378. StopSoundAction.prototype._prepare = function () {
  54379. };
  54380. StopSoundAction.prototype.execute = function () {
  54381. if (this._sound !== undefined)
  54382. this._sound.stop();
  54383. };
  54384. StopSoundAction.prototype.serialize = function (parent) {
  54385. return _super.prototype._serialize.call(this, {
  54386. name: "StopSoundAction",
  54387. properties: [{ name: "sound", value: this._sound.name }]
  54388. }, parent);
  54389. };
  54390. return StopSoundAction;
  54391. }(BABYLON.Action));
  54392. BABYLON.StopSoundAction = StopSoundAction;
  54393. })(BABYLON || (BABYLON = {}));
  54394. //# sourceMappingURL=babylon.directActions.js.map
  54395. var BABYLON;
  54396. (function (BABYLON) {
  54397. var SpriteManager = /** @class */ (function () {
  54398. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54399. if (epsilon === void 0) { epsilon = 0.01; }
  54400. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54401. this.name = name;
  54402. this.sprites = new Array();
  54403. this.renderingGroupId = 0;
  54404. this.layerMask = 0x0FFFFFFF;
  54405. this.fogEnabled = true;
  54406. this.isPickable = false;
  54407. /**
  54408. * An event triggered when the manager is disposed.
  54409. */
  54410. this.onDisposeObservable = new BABYLON.Observable();
  54411. this._vertexBuffers = {};
  54412. this._capacity = capacity;
  54413. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54414. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54415. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54416. if (cellSize.width && cellSize.height) {
  54417. this.cellWidth = cellSize.width;
  54418. this.cellHeight = cellSize.height;
  54419. }
  54420. else if (cellSize !== undefined) {
  54421. this.cellWidth = cellSize;
  54422. this.cellHeight = cellSize;
  54423. }
  54424. else {
  54425. return;
  54426. }
  54427. this._epsilon = epsilon;
  54428. this._scene = scene;
  54429. this._scene.spriteManagers.push(this);
  54430. var indices = [];
  54431. var index = 0;
  54432. for (var count = 0; count < capacity; count++) {
  54433. indices.push(index);
  54434. indices.push(index + 1);
  54435. indices.push(index + 2);
  54436. indices.push(index);
  54437. indices.push(index + 2);
  54438. indices.push(index + 3);
  54439. index += 4;
  54440. }
  54441. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54442. // VBO
  54443. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54444. this._vertexData = new Float32Array(capacity * 16 * 4);
  54445. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54446. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54447. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54448. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54449. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54450. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54451. this._vertexBuffers["options"] = options;
  54452. this._vertexBuffers["cellInfo"] = cellInfo;
  54453. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54454. // Effects
  54455. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54456. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54457. }
  54458. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54459. set: function (callback) {
  54460. if (this._onDisposeObserver) {
  54461. this.onDisposeObservable.remove(this._onDisposeObserver);
  54462. }
  54463. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54464. },
  54465. enumerable: true,
  54466. configurable: true
  54467. });
  54468. Object.defineProperty(SpriteManager.prototype, "texture", {
  54469. get: function () {
  54470. return this._spriteTexture;
  54471. },
  54472. set: function (value) {
  54473. this._spriteTexture = value;
  54474. },
  54475. enumerable: true,
  54476. configurable: true
  54477. });
  54478. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54479. var arrayOffset = index * 16;
  54480. if (offsetX === 0)
  54481. offsetX = this._epsilon;
  54482. else if (offsetX === 1)
  54483. offsetX = 1 - this._epsilon;
  54484. if (offsetY === 0)
  54485. offsetY = this._epsilon;
  54486. else if (offsetY === 1)
  54487. offsetY = 1 - this._epsilon;
  54488. this._vertexData[arrayOffset] = sprite.position.x;
  54489. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54490. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54491. this._vertexData[arrayOffset + 3] = sprite.angle;
  54492. this._vertexData[arrayOffset + 4] = sprite.width;
  54493. this._vertexData[arrayOffset + 5] = sprite.height;
  54494. this._vertexData[arrayOffset + 6] = offsetX;
  54495. this._vertexData[arrayOffset + 7] = offsetY;
  54496. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54497. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54498. var offset = (sprite.cellIndex / rowSize) >> 0;
  54499. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54500. this._vertexData[arrayOffset + 11] = offset;
  54501. // Color
  54502. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54503. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54504. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54505. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54506. };
  54507. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54508. var count = Math.min(this._capacity, this.sprites.length);
  54509. var min = BABYLON.Vector3.Zero();
  54510. var max = BABYLON.Vector3.Zero();
  54511. var distance = Number.MAX_VALUE;
  54512. var currentSprite = null;
  54513. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54514. var cameraView = camera.getViewMatrix();
  54515. for (var index = 0; index < count; index++) {
  54516. var sprite = this.sprites[index];
  54517. if (!sprite) {
  54518. continue;
  54519. }
  54520. if (predicate) {
  54521. if (!predicate(sprite)) {
  54522. continue;
  54523. }
  54524. }
  54525. else if (!sprite.isPickable) {
  54526. continue;
  54527. }
  54528. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54529. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54530. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54531. if (ray.intersectsBoxMinMax(min, max)) {
  54532. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54533. if (distance > currentDistance) {
  54534. distance = currentDistance;
  54535. currentSprite = sprite;
  54536. if (fastCheck) {
  54537. break;
  54538. }
  54539. }
  54540. }
  54541. }
  54542. if (currentSprite) {
  54543. var result = new BABYLON.PickingInfo();
  54544. result.hit = true;
  54545. result.pickedSprite = currentSprite;
  54546. result.distance = distance;
  54547. return result;
  54548. }
  54549. return null;
  54550. };
  54551. SpriteManager.prototype.render = function () {
  54552. // Check
  54553. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54554. return;
  54555. var engine = this._scene.getEngine();
  54556. var baseSize = this._spriteTexture.getBaseSize();
  54557. // Sprites
  54558. var deltaTime = engine.getDeltaTime();
  54559. var max = Math.min(this._capacity, this.sprites.length);
  54560. var rowSize = baseSize.width / this.cellWidth;
  54561. var offset = 0;
  54562. for (var index = 0; index < max; index++) {
  54563. var sprite = this.sprites[index];
  54564. if (!sprite) {
  54565. continue;
  54566. }
  54567. sprite._animate(deltaTime);
  54568. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54569. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54570. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54571. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54572. }
  54573. this._buffer.update(this._vertexData);
  54574. // Render
  54575. var effect = this._effectBase;
  54576. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54577. effect = this._effectFog;
  54578. }
  54579. engine.enableEffect(effect);
  54580. var viewMatrix = this._scene.getViewMatrix();
  54581. effect.setTexture("diffuseSampler", this._spriteTexture);
  54582. effect.setMatrix("view", viewMatrix);
  54583. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54584. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54585. // Fog
  54586. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54587. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54588. effect.setColor3("vFogColor", this._scene.fogColor);
  54589. }
  54590. // VBOs
  54591. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54592. // Draw order
  54593. engine.setDepthFunctionToLessOrEqual();
  54594. effect.setBool("alphaTest", true);
  54595. engine.setColorWrite(false);
  54596. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54597. engine.setColorWrite(true);
  54598. effect.setBool("alphaTest", false);
  54599. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54600. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54601. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54602. };
  54603. SpriteManager.prototype.dispose = function () {
  54604. if (this._buffer) {
  54605. this._buffer.dispose();
  54606. this._buffer = null;
  54607. }
  54608. if (this._indexBuffer) {
  54609. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54610. this._indexBuffer = null;
  54611. }
  54612. if (this._spriteTexture) {
  54613. this._spriteTexture.dispose();
  54614. this._spriteTexture = null;
  54615. }
  54616. // Remove from scene
  54617. var index = this._scene.spriteManagers.indexOf(this);
  54618. this._scene.spriteManagers.splice(index, 1);
  54619. // Callback
  54620. this.onDisposeObservable.notifyObservers(this);
  54621. this.onDisposeObservable.clear();
  54622. };
  54623. return SpriteManager;
  54624. }());
  54625. BABYLON.SpriteManager = SpriteManager;
  54626. })(BABYLON || (BABYLON = {}));
  54627. //# sourceMappingURL=babylon.spriteManager.js.map
  54628. var BABYLON;
  54629. (function (BABYLON) {
  54630. var Sprite = /** @class */ (function () {
  54631. function Sprite(name, manager) {
  54632. this.name = name;
  54633. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54634. this.width = 1.0;
  54635. this.height = 1.0;
  54636. this.angle = 0;
  54637. this.cellIndex = 0;
  54638. this.invertU = 0;
  54639. this.invertV = 0;
  54640. this.animations = new Array();
  54641. this.isPickable = false;
  54642. this._animationStarted = false;
  54643. this._loopAnimation = false;
  54644. this._fromIndex = 0;
  54645. this._toIndex = 0;
  54646. this._delay = 0;
  54647. this._direction = 1;
  54648. this._time = 0;
  54649. this._manager = manager;
  54650. this._manager.sprites.push(this);
  54651. this.position = BABYLON.Vector3.Zero();
  54652. }
  54653. Object.defineProperty(Sprite.prototype, "size", {
  54654. get: function () {
  54655. return this.width;
  54656. },
  54657. set: function (value) {
  54658. this.width = value;
  54659. this.height = value;
  54660. },
  54661. enumerable: true,
  54662. configurable: true
  54663. });
  54664. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54665. this._fromIndex = from;
  54666. this._toIndex = to;
  54667. this._loopAnimation = loop;
  54668. this._delay = delay;
  54669. this._animationStarted = true;
  54670. this._direction = from < to ? 1 : -1;
  54671. this.cellIndex = from;
  54672. this._time = 0;
  54673. this._onAnimationEnd = onAnimationEnd;
  54674. };
  54675. Sprite.prototype.stopAnimation = function () {
  54676. this._animationStarted = false;
  54677. };
  54678. Sprite.prototype._animate = function (deltaTime) {
  54679. if (!this._animationStarted)
  54680. return;
  54681. this._time += deltaTime;
  54682. if (this._time > this._delay) {
  54683. this._time = this._time % this._delay;
  54684. this.cellIndex += this._direction;
  54685. if (this.cellIndex > this._toIndex) {
  54686. if (this._loopAnimation) {
  54687. this.cellIndex = this._fromIndex;
  54688. }
  54689. else {
  54690. this.cellIndex = this._toIndex;
  54691. this._animationStarted = false;
  54692. if (this._onAnimationEnd) {
  54693. this._onAnimationEnd();
  54694. }
  54695. if (this.disposeWhenFinishedAnimating) {
  54696. this.dispose();
  54697. }
  54698. }
  54699. }
  54700. }
  54701. };
  54702. Sprite.prototype.dispose = function () {
  54703. for (var i = 0; i < this._manager.sprites.length; i++) {
  54704. if (this._manager.sprites[i] == this) {
  54705. this._manager.sprites.splice(i, 1);
  54706. }
  54707. }
  54708. };
  54709. return Sprite;
  54710. }());
  54711. BABYLON.Sprite = Sprite;
  54712. })(BABYLON || (BABYLON = {}));
  54713. //# sourceMappingURL=babylon.sprite.js.map
  54714. var BABYLON;
  54715. (function (BABYLON) {
  54716. var IntersectionInfo = /** @class */ (function () {
  54717. function IntersectionInfo(bu, bv, distance) {
  54718. this.bu = bu;
  54719. this.bv = bv;
  54720. this.distance = distance;
  54721. this.faceId = 0;
  54722. this.subMeshId = 0;
  54723. }
  54724. return IntersectionInfo;
  54725. }());
  54726. BABYLON.IntersectionInfo = IntersectionInfo;
  54727. var PickingInfo = /** @class */ (function () {
  54728. function PickingInfo() {
  54729. this.hit = false;
  54730. this.distance = 0;
  54731. this.pickedPoint = null;
  54732. this.pickedMesh = null;
  54733. this.bu = 0;
  54734. this.bv = 0;
  54735. this.faceId = -1;
  54736. this.subMeshId = 0;
  54737. this.pickedSprite = null;
  54738. }
  54739. // Methods
  54740. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54741. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54742. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54743. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54744. return null;
  54745. }
  54746. var indices = this.pickedMesh.getIndices();
  54747. if (!indices) {
  54748. return null;
  54749. }
  54750. var result;
  54751. if (useVerticesNormals) {
  54752. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54753. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54754. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54755. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54756. normal0 = normal0.scale(this.bu);
  54757. normal1 = normal1.scale(this.bv);
  54758. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54759. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54760. }
  54761. else {
  54762. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54763. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54764. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54765. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54766. var p1p2 = vertex1.subtract(vertex2);
  54767. var p3p2 = vertex3.subtract(vertex2);
  54768. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54769. }
  54770. if (useWorldCoordinates) {
  54771. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54772. }
  54773. return BABYLON.Vector3.Normalize(result);
  54774. };
  54775. PickingInfo.prototype.getTextureCoordinates = function () {
  54776. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54777. return null;
  54778. }
  54779. var indices = this.pickedMesh.getIndices();
  54780. if (!indices) {
  54781. return null;
  54782. }
  54783. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54784. if (!uvs) {
  54785. return null;
  54786. }
  54787. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54788. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54789. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54790. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54791. uv1 = uv1.scale(this.bu);
  54792. uv2 = uv2.scale(this.bv);
  54793. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54794. };
  54795. return PickingInfo;
  54796. }());
  54797. BABYLON.PickingInfo = PickingInfo;
  54798. })(BABYLON || (BABYLON = {}));
  54799. //# sourceMappingURL=babylon.pickingInfo.js.map
  54800. var BABYLON;
  54801. (function (BABYLON) {
  54802. var Ray = /** @class */ (function () {
  54803. function Ray(origin, direction, length) {
  54804. if (length === void 0) { length = Number.MAX_VALUE; }
  54805. this.origin = origin;
  54806. this.direction = direction;
  54807. this.length = length;
  54808. }
  54809. // Methods
  54810. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54811. var d = 0.0;
  54812. var maxValue = Number.MAX_VALUE;
  54813. var inv;
  54814. var min;
  54815. var max;
  54816. var temp;
  54817. if (Math.abs(this.direction.x) < 0.0000001) {
  54818. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54819. return false;
  54820. }
  54821. }
  54822. else {
  54823. inv = 1.0 / this.direction.x;
  54824. min = (minimum.x - this.origin.x) * inv;
  54825. max = (maximum.x - this.origin.x) * inv;
  54826. if (max === -Infinity) {
  54827. max = Infinity;
  54828. }
  54829. if (min > max) {
  54830. temp = min;
  54831. min = max;
  54832. max = temp;
  54833. }
  54834. d = Math.max(min, d);
  54835. maxValue = Math.min(max, maxValue);
  54836. if (d > maxValue) {
  54837. return false;
  54838. }
  54839. }
  54840. if (Math.abs(this.direction.y) < 0.0000001) {
  54841. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54842. return false;
  54843. }
  54844. }
  54845. else {
  54846. inv = 1.0 / this.direction.y;
  54847. min = (minimum.y - this.origin.y) * inv;
  54848. max = (maximum.y - this.origin.y) * inv;
  54849. if (max === -Infinity) {
  54850. max = Infinity;
  54851. }
  54852. if (min > max) {
  54853. temp = min;
  54854. min = max;
  54855. max = temp;
  54856. }
  54857. d = Math.max(min, d);
  54858. maxValue = Math.min(max, maxValue);
  54859. if (d > maxValue) {
  54860. return false;
  54861. }
  54862. }
  54863. if (Math.abs(this.direction.z) < 0.0000001) {
  54864. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54865. return false;
  54866. }
  54867. }
  54868. else {
  54869. inv = 1.0 / this.direction.z;
  54870. min = (minimum.z - this.origin.z) * inv;
  54871. max = (maximum.z - this.origin.z) * inv;
  54872. if (max === -Infinity) {
  54873. max = Infinity;
  54874. }
  54875. if (min > max) {
  54876. temp = min;
  54877. min = max;
  54878. max = temp;
  54879. }
  54880. d = Math.max(min, d);
  54881. maxValue = Math.min(max, maxValue);
  54882. if (d > maxValue) {
  54883. return false;
  54884. }
  54885. }
  54886. return true;
  54887. };
  54888. Ray.prototype.intersectsBox = function (box) {
  54889. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54890. };
  54891. Ray.prototype.intersectsSphere = function (sphere) {
  54892. var x = sphere.center.x - this.origin.x;
  54893. var y = sphere.center.y - this.origin.y;
  54894. var z = sphere.center.z - this.origin.z;
  54895. var pyth = (x * x) + (y * y) + (z * z);
  54896. var rr = sphere.radius * sphere.radius;
  54897. if (pyth <= rr) {
  54898. return true;
  54899. }
  54900. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54901. if (dot < 0.0) {
  54902. return false;
  54903. }
  54904. var temp = pyth - (dot * dot);
  54905. return temp <= rr;
  54906. };
  54907. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54908. if (!this._edge1) {
  54909. this._edge1 = BABYLON.Vector3.Zero();
  54910. this._edge2 = BABYLON.Vector3.Zero();
  54911. this._pvec = BABYLON.Vector3.Zero();
  54912. this._tvec = BABYLON.Vector3.Zero();
  54913. this._qvec = BABYLON.Vector3.Zero();
  54914. }
  54915. vertex1.subtractToRef(vertex0, this._edge1);
  54916. vertex2.subtractToRef(vertex0, this._edge2);
  54917. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54918. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54919. if (det === 0) {
  54920. return null;
  54921. }
  54922. var invdet = 1 / det;
  54923. this.origin.subtractToRef(vertex0, this._tvec);
  54924. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54925. if (bu < 0 || bu > 1.0) {
  54926. return null;
  54927. }
  54928. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54929. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54930. if (bv < 0 || bu + bv > 1.0) {
  54931. return null;
  54932. }
  54933. //check if the distance is longer than the predefined length.
  54934. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54935. if (distance > this.length) {
  54936. return null;
  54937. }
  54938. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54939. };
  54940. Ray.prototype.intersectsPlane = function (plane) {
  54941. var distance;
  54942. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54943. if (Math.abs(result1) < 9.99999997475243E-07) {
  54944. return null;
  54945. }
  54946. else {
  54947. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54948. distance = (-plane.d - result2) / result1;
  54949. if (distance < 0.0) {
  54950. if (distance < -9.99999997475243E-07) {
  54951. return null;
  54952. }
  54953. else {
  54954. return 0;
  54955. }
  54956. }
  54957. return distance;
  54958. }
  54959. };
  54960. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54961. var tm = BABYLON.Tmp.Matrix[0];
  54962. mesh.getWorldMatrix().invertToRef(tm);
  54963. if (this._tmpRay) {
  54964. Ray.TransformToRef(this, tm, this._tmpRay);
  54965. }
  54966. else {
  54967. this._tmpRay = Ray.Transform(this, tm);
  54968. }
  54969. return mesh.intersects(this._tmpRay, fastCheck);
  54970. };
  54971. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54972. if (results) {
  54973. results.length = 0;
  54974. }
  54975. else {
  54976. results = [];
  54977. }
  54978. for (var i = 0; i < meshes.length; i++) {
  54979. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54980. if (pickInfo.hit) {
  54981. results.push(pickInfo);
  54982. }
  54983. }
  54984. results.sort(this._comparePickingInfo);
  54985. return results;
  54986. };
  54987. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54988. if (pickingInfoA.distance < pickingInfoB.distance) {
  54989. return -1;
  54990. }
  54991. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54992. return 1;
  54993. }
  54994. else {
  54995. return 0;
  54996. }
  54997. };
  54998. /**
  54999. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55000. * @param sega the first point of the segment to test the intersection against
  55001. * @param segb the second point of the segment to test the intersection against
  55002. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55003. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55004. */
  55005. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55006. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55007. var u = segb.subtract(sega);
  55008. var v = rsegb.subtract(this.origin);
  55009. var w = sega.subtract(this.origin);
  55010. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55011. var b = BABYLON.Vector3.Dot(u, v);
  55012. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55013. var d = BABYLON.Vector3.Dot(u, w);
  55014. var e = BABYLON.Vector3.Dot(v, w);
  55015. var D = a * c - b * b; // always >= 0
  55016. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55017. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55018. // compute the line parameters of the two closest points
  55019. if (D < Ray.smallnum) { // the lines are almost parallel
  55020. sN = 0.0; // force using point P0 on segment S1
  55021. sD = 1.0; // to prevent possible division by 0.0 later
  55022. tN = e;
  55023. tD = c;
  55024. }
  55025. else { // get the closest points on the infinite lines
  55026. sN = (b * e - c * d);
  55027. tN = (a * e - b * d);
  55028. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55029. sN = 0.0;
  55030. tN = e;
  55031. tD = c;
  55032. }
  55033. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55034. sN = sD;
  55035. tN = e + b;
  55036. tD = c;
  55037. }
  55038. }
  55039. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55040. tN = 0.0;
  55041. // recompute sc for this edge
  55042. if (-d < 0.0) {
  55043. sN = 0.0;
  55044. }
  55045. else if (-d > a)
  55046. sN = sD;
  55047. else {
  55048. sN = -d;
  55049. sD = a;
  55050. }
  55051. }
  55052. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55053. tN = tD;
  55054. // recompute sc for this edge
  55055. if ((-d + b) < 0.0) {
  55056. sN = 0;
  55057. }
  55058. else if ((-d + b) > a) {
  55059. sN = sD;
  55060. }
  55061. else {
  55062. sN = (-d + b);
  55063. sD = a;
  55064. }
  55065. }
  55066. // finally do the division to get sc and tc
  55067. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55068. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55069. // get the difference of the two closest points
  55070. var qtc = v.multiplyByFloats(tc, tc, tc);
  55071. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55072. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55073. if (isIntersected) {
  55074. return qtc.length();
  55075. }
  55076. return -1;
  55077. };
  55078. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55079. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55080. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55081. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55082. this.direction.normalize();
  55083. return this;
  55084. };
  55085. // Statics
  55086. Ray.Zero = function () {
  55087. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55088. };
  55089. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55090. var result = Ray.Zero();
  55091. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55092. };
  55093. /**
  55094. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  55095. * transformed to the given world matrix.
  55096. * @param origin The origin point
  55097. * @param end The end point
  55098. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55099. */
  55100. Ray.CreateNewFromTo = function (origin, end, world) {
  55101. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55102. var direction = end.subtract(origin);
  55103. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55104. direction.normalize();
  55105. return Ray.Transform(new Ray(origin, direction, length), world);
  55106. };
  55107. Ray.Transform = function (ray, matrix) {
  55108. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55109. Ray.TransformToRef(ray, matrix, result);
  55110. return result;
  55111. };
  55112. Ray.TransformToRef = function (ray, matrix, result) {
  55113. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55114. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55115. result.length = ray.length;
  55116. var dir = result.direction;
  55117. var len = dir.length();
  55118. if (!(len === 0 || len === 1)) {
  55119. var num = 1.0 / len;
  55120. dir.x *= num;
  55121. dir.y *= num;
  55122. dir.z *= num;
  55123. result.length *= len;
  55124. }
  55125. };
  55126. Ray.smallnum = 0.00000001;
  55127. Ray.rayl = 10e8;
  55128. return Ray;
  55129. }());
  55130. BABYLON.Ray = Ray;
  55131. })(BABYLON || (BABYLON = {}));
  55132. //# sourceMappingURL=babylon.ray.js.map
  55133. var BABYLON;
  55134. (function (BABYLON) {
  55135. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55136. if (boxMin.x > sphereCenter.x + sphereRadius)
  55137. return false;
  55138. if (sphereCenter.x - sphereRadius > boxMax.x)
  55139. return false;
  55140. if (boxMin.y > sphereCenter.y + sphereRadius)
  55141. return false;
  55142. if (sphereCenter.y - sphereRadius > boxMax.y)
  55143. return false;
  55144. if (boxMin.z > sphereCenter.z + sphereRadius)
  55145. return false;
  55146. if (sphereCenter.z - sphereRadius > boxMax.z)
  55147. return false;
  55148. return true;
  55149. };
  55150. var getLowestRoot = (function () {
  55151. var result = { root: 0, found: false };
  55152. return function (a, b, c, maxR) {
  55153. result.root = 0;
  55154. result.found = false;
  55155. var determinant = b * b - 4.0 * a * c;
  55156. if (determinant < 0)
  55157. return result;
  55158. var sqrtD = Math.sqrt(determinant);
  55159. var r1 = (-b - sqrtD) / (2.0 * a);
  55160. var r2 = (-b + sqrtD) / (2.0 * a);
  55161. if (r1 > r2) {
  55162. var temp = r2;
  55163. r2 = r1;
  55164. r1 = temp;
  55165. }
  55166. if (r1 > 0 && r1 < maxR) {
  55167. result.root = r1;
  55168. result.found = true;
  55169. return result;
  55170. }
  55171. if (r2 > 0 && r2 < maxR) {
  55172. result.root = r2;
  55173. result.found = true;
  55174. return result;
  55175. }
  55176. return result;
  55177. };
  55178. })();
  55179. var Collider = /** @class */ (function () {
  55180. function Collider() {
  55181. this._collisionPoint = BABYLON.Vector3.Zero();
  55182. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55183. this._tempVector = BABYLON.Vector3.Zero();
  55184. this._tempVector2 = BABYLON.Vector3.Zero();
  55185. this._tempVector3 = BABYLON.Vector3.Zero();
  55186. this._tempVector4 = BABYLON.Vector3.Zero();
  55187. this._edge = BABYLON.Vector3.Zero();
  55188. this._baseToVertex = BABYLON.Vector3.Zero();
  55189. this._destinationPoint = BABYLON.Vector3.Zero();
  55190. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55191. this._displacementVector = BABYLON.Vector3.Zero();
  55192. this._radius = BABYLON.Vector3.One();
  55193. this._retry = 0;
  55194. this._basePointWorld = BABYLON.Vector3.Zero();
  55195. this._velocityWorld = BABYLON.Vector3.Zero();
  55196. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55197. this._collisionMask = -1;
  55198. }
  55199. Object.defineProperty(Collider.prototype, "collisionMask", {
  55200. get: function () {
  55201. return this._collisionMask;
  55202. },
  55203. set: function (mask) {
  55204. this._collisionMask = !isNaN(mask) ? mask : -1;
  55205. },
  55206. enumerable: true,
  55207. configurable: true
  55208. });
  55209. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55210. /**
  55211. * Gets the plane normal used to compute the sliding response (in local space)
  55212. */
  55213. get: function () {
  55214. return this._slidePlaneNormal;
  55215. },
  55216. enumerable: true,
  55217. configurable: true
  55218. });
  55219. // Methods
  55220. Collider.prototype._initialize = function (source, dir, e) {
  55221. this._velocity = dir;
  55222. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55223. this._basePoint = source;
  55224. source.multiplyToRef(this._radius, this._basePointWorld);
  55225. dir.multiplyToRef(this._radius, this._velocityWorld);
  55226. this._velocityWorldLength = this._velocityWorld.length();
  55227. this._epsilon = e;
  55228. this.collisionFound = false;
  55229. };
  55230. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55231. pa.subtractToRef(point, this._tempVector);
  55232. pb.subtractToRef(point, this._tempVector2);
  55233. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55234. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55235. if (d < 0)
  55236. return false;
  55237. pc.subtractToRef(point, this._tempVector3);
  55238. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55239. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55240. if (d < 0)
  55241. return false;
  55242. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55243. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55244. return d >= 0;
  55245. };
  55246. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55247. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55248. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55249. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55250. return false;
  55251. }
  55252. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55253. return false;
  55254. return true;
  55255. };
  55256. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55257. var t0;
  55258. var embeddedInPlane = false;
  55259. //defensive programming, actually not needed.
  55260. if (!trianglePlaneArray) {
  55261. trianglePlaneArray = [];
  55262. }
  55263. if (!trianglePlaneArray[faceIndex]) {
  55264. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55265. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55266. }
  55267. var trianglePlane = trianglePlaneArray[faceIndex];
  55268. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55269. return;
  55270. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55271. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55272. if (normalDotVelocity == 0) {
  55273. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55274. return;
  55275. embeddedInPlane = true;
  55276. t0 = 0;
  55277. }
  55278. else {
  55279. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55280. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55281. if (t0 > t1) {
  55282. var temp = t1;
  55283. t1 = t0;
  55284. t0 = temp;
  55285. }
  55286. if (t0 > 1.0 || t1 < 0.0)
  55287. return;
  55288. if (t0 < 0)
  55289. t0 = 0;
  55290. if (t0 > 1.0)
  55291. t0 = 1.0;
  55292. }
  55293. this._collisionPoint.copyFromFloats(0, 0, 0);
  55294. var found = false;
  55295. var t = 1.0;
  55296. if (!embeddedInPlane) {
  55297. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55298. this._velocity.scaleToRef(t0, this._tempVector);
  55299. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55300. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55301. found = true;
  55302. t = t0;
  55303. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55304. }
  55305. }
  55306. if (!found) {
  55307. var velocitySquaredLength = this._velocity.lengthSquared();
  55308. var a = velocitySquaredLength;
  55309. this._basePoint.subtractToRef(p1, this._tempVector);
  55310. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55311. var c = this._tempVector.lengthSquared() - 1.0;
  55312. var lowestRoot = getLowestRoot(a, b, c, t);
  55313. if (lowestRoot.found) {
  55314. t = lowestRoot.root;
  55315. found = true;
  55316. this._collisionPoint.copyFrom(p1);
  55317. }
  55318. this._basePoint.subtractToRef(p2, this._tempVector);
  55319. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55320. c = this._tempVector.lengthSquared() - 1.0;
  55321. lowestRoot = getLowestRoot(a, b, c, t);
  55322. if (lowestRoot.found) {
  55323. t = lowestRoot.root;
  55324. found = true;
  55325. this._collisionPoint.copyFrom(p2);
  55326. }
  55327. this._basePoint.subtractToRef(p3, this._tempVector);
  55328. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55329. c = this._tempVector.lengthSquared() - 1.0;
  55330. lowestRoot = getLowestRoot(a, b, c, t);
  55331. if (lowestRoot.found) {
  55332. t = lowestRoot.root;
  55333. found = true;
  55334. this._collisionPoint.copyFrom(p3);
  55335. }
  55336. p2.subtractToRef(p1, this._edge);
  55337. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55338. var edgeSquaredLength = this._edge.lengthSquared();
  55339. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55340. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55341. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55342. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55343. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55344. lowestRoot = getLowestRoot(a, b, c, t);
  55345. if (lowestRoot.found) {
  55346. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55347. if (f >= 0.0 && f <= 1.0) {
  55348. t = lowestRoot.root;
  55349. found = true;
  55350. this._edge.scaleInPlace(f);
  55351. p1.addToRef(this._edge, this._collisionPoint);
  55352. }
  55353. }
  55354. p3.subtractToRef(p2, this._edge);
  55355. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55356. edgeSquaredLength = this._edge.lengthSquared();
  55357. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55358. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55359. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55360. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55361. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55362. lowestRoot = getLowestRoot(a, b, c, t);
  55363. if (lowestRoot.found) {
  55364. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55365. if (f >= 0.0 && f <= 1.0) {
  55366. t = lowestRoot.root;
  55367. found = true;
  55368. this._edge.scaleInPlace(f);
  55369. p2.addToRef(this._edge, this._collisionPoint);
  55370. }
  55371. }
  55372. p1.subtractToRef(p3, this._edge);
  55373. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55374. edgeSquaredLength = this._edge.lengthSquared();
  55375. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55376. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55377. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55378. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55379. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55380. lowestRoot = getLowestRoot(a, b, c, t);
  55381. if (lowestRoot.found) {
  55382. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55383. if (f >= 0.0 && f <= 1.0) {
  55384. t = lowestRoot.root;
  55385. found = true;
  55386. this._edge.scaleInPlace(f);
  55387. p3.addToRef(this._edge, this._collisionPoint);
  55388. }
  55389. }
  55390. }
  55391. if (found) {
  55392. var distToCollision = t * this._velocity.length();
  55393. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55394. if (!this.intersectionPoint) {
  55395. this.intersectionPoint = this._collisionPoint.clone();
  55396. }
  55397. else {
  55398. this.intersectionPoint.copyFrom(this._collisionPoint);
  55399. }
  55400. this._nearestDistance = distToCollision;
  55401. this.collisionFound = true;
  55402. }
  55403. }
  55404. };
  55405. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55406. for (var i = indexStart; i < indexEnd; i += 3) {
  55407. var p1 = pts[indices[i] - decal];
  55408. var p2 = pts[indices[i + 1] - decal];
  55409. var p3 = pts[indices[i + 2] - decal];
  55410. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55411. }
  55412. };
  55413. Collider.prototype._getResponse = function (pos, vel) {
  55414. pos.addToRef(vel, this._destinationPoint);
  55415. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55416. this._basePoint.addToRef(vel, pos);
  55417. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55418. this._slidePlaneNormal.normalize();
  55419. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55420. pos.addInPlace(this._displacementVector);
  55421. this.intersectionPoint.addInPlace(this._displacementVector);
  55422. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55423. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55424. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55425. };
  55426. return Collider;
  55427. }());
  55428. BABYLON.Collider = Collider;
  55429. })(BABYLON || (BABYLON = {}));
  55430. //# sourceMappingURL=babylon.collider.js.map
  55431. var BABYLON;
  55432. (function (BABYLON) {
  55433. //WebWorker code will be inserted to this variable.
  55434. BABYLON.CollisionWorker = "";
  55435. /** Defines supported task for worker process */
  55436. var WorkerTaskType;
  55437. (function (WorkerTaskType) {
  55438. /** Initialization */
  55439. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55440. /** Update of geometry */
  55441. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55442. /** Evaluate collision */
  55443. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55444. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55445. /** Defines kind of replies returned by worker */
  55446. var WorkerReplyType;
  55447. (function (WorkerReplyType) {
  55448. /** Success */
  55449. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55450. /** Unkown error */
  55451. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55452. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55453. var CollisionCoordinatorWorker = /** @class */ (function () {
  55454. function CollisionCoordinatorWorker() {
  55455. var _this = this;
  55456. this._scaledPosition = BABYLON.Vector3.Zero();
  55457. this._scaledVelocity = BABYLON.Vector3.Zero();
  55458. this.onMeshUpdated = function (transformNode) {
  55459. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55460. };
  55461. this.onGeometryUpdated = function (geometry) {
  55462. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55463. };
  55464. this._afterRender = function () {
  55465. if (!_this._init)
  55466. return;
  55467. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55468. return;
  55469. }
  55470. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55471. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55472. if (_this._runningUpdated > 4) {
  55473. return;
  55474. }
  55475. ++_this._runningUpdated;
  55476. var payload = {
  55477. updatedMeshes: _this._addUpdateMeshesList,
  55478. updatedGeometries: _this._addUpdateGeometriesList,
  55479. removedGeometries: _this._toRemoveGeometryArray,
  55480. removedMeshes: _this._toRemoveMeshesArray
  55481. };
  55482. var message = {
  55483. payload: payload,
  55484. taskType: WorkerTaskType.UPDATE
  55485. };
  55486. var serializable = [];
  55487. for (var id in payload.updatedGeometries) {
  55488. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55489. //prepare transferables
  55490. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55491. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55492. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55493. }
  55494. }
  55495. _this._worker.postMessage(message, serializable);
  55496. _this._addUpdateMeshesList = {};
  55497. _this._addUpdateGeometriesList = {};
  55498. _this._toRemoveGeometryArray = [];
  55499. _this._toRemoveMeshesArray = [];
  55500. };
  55501. this._onMessageFromWorker = function (e) {
  55502. var returnData = e.data;
  55503. if (returnData.error != WorkerReplyType.SUCCESS) {
  55504. //TODO what errors can be returned from the worker?
  55505. BABYLON.Tools.Warn("error returned from worker!");
  55506. return;
  55507. }
  55508. switch (returnData.taskType) {
  55509. case WorkerTaskType.INIT:
  55510. _this._init = true;
  55511. //Update the worked with ALL of the scene's current state
  55512. _this._scene.meshes.forEach(function (mesh) {
  55513. _this.onMeshAdded(mesh);
  55514. });
  55515. _this._scene.getGeometries().forEach(function (geometry) {
  55516. _this.onGeometryAdded(geometry);
  55517. });
  55518. break;
  55519. case WorkerTaskType.UPDATE:
  55520. _this._runningUpdated--;
  55521. break;
  55522. case WorkerTaskType.COLLIDE:
  55523. var returnPayload = returnData.payload;
  55524. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55525. return;
  55526. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55527. if (callback) {
  55528. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55529. if (mesh) {
  55530. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55531. }
  55532. }
  55533. //cleanup
  55534. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55535. break;
  55536. }
  55537. };
  55538. this._collisionsCallbackArray = [];
  55539. this._init = false;
  55540. this._runningUpdated = 0;
  55541. this._addUpdateMeshesList = {};
  55542. this._addUpdateGeometriesList = {};
  55543. this._toRemoveGeometryArray = [];
  55544. this._toRemoveMeshesArray = [];
  55545. }
  55546. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55547. if (!this._init)
  55548. return;
  55549. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55550. return;
  55551. position.divideToRef(collider._radius, this._scaledPosition);
  55552. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55553. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55554. var payload = {
  55555. collider: {
  55556. position: this._scaledPosition.asArray(),
  55557. velocity: this._scaledVelocity.asArray(),
  55558. radius: collider._radius.asArray()
  55559. },
  55560. collisionId: collisionIndex,
  55561. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55562. maximumRetry: maximumRetry
  55563. };
  55564. var message = {
  55565. payload: payload,
  55566. taskType: WorkerTaskType.COLLIDE
  55567. };
  55568. this._worker.postMessage(message);
  55569. };
  55570. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55571. this._scene = scene;
  55572. this._scene.registerAfterRender(this._afterRender);
  55573. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55574. this._worker = new Worker(workerUrl);
  55575. this._worker.onmessage = this._onMessageFromWorker;
  55576. var message = {
  55577. payload: {},
  55578. taskType: WorkerTaskType.INIT
  55579. };
  55580. this._worker.postMessage(message);
  55581. };
  55582. CollisionCoordinatorWorker.prototype.destroy = function () {
  55583. this._scene.unregisterAfterRender(this._afterRender);
  55584. this._worker.terminate();
  55585. };
  55586. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55587. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55588. this.onMeshUpdated(mesh);
  55589. };
  55590. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55591. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55592. };
  55593. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55594. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55595. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55596. this.onGeometryUpdated(geometry);
  55597. };
  55598. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55599. this._toRemoveGeometryArray.push(geometry.id);
  55600. };
  55601. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55602. var submeshes = [];
  55603. if (mesh.subMeshes) {
  55604. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55605. var boundingInfo = sm.getBoundingInfo();
  55606. return {
  55607. position: idx,
  55608. verticesStart: sm.verticesStart,
  55609. verticesCount: sm.verticesCount,
  55610. indexStart: sm.indexStart,
  55611. indexCount: sm.indexCount,
  55612. hasMaterial: !!sm.getMaterial(),
  55613. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55614. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55615. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55616. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55617. };
  55618. });
  55619. }
  55620. var geometryId = null;
  55621. if (mesh instanceof BABYLON.Mesh) {
  55622. var geometry = mesh.geometry;
  55623. geometryId = geometry ? geometry.id : null;
  55624. }
  55625. else if (mesh instanceof BABYLON.InstancedMesh) {
  55626. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55627. geometryId = geometry ? geometry.id : null;
  55628. }
  55629. var boundingInfo = mesh.getBoundingInfo();
  55630. return {
  55631. uniqueId: mesh.uniqueId,
  55632. id: mesh.id,
  55633. name: mesh.name,
  55634. geometryId: geometryId,
  55635. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55636. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55637. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55638. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55639. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55640. subMeshes: submeshes,
  55641. checkCollisions: mesh.checkCollisions
  55642. };
  55643. };
  55644. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55645. return {
  55646. id: geometry.id,
  55647. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55648. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55649. indices: new Uint32Array(geometry.getIndices() || []),
  55650. };
  55651. };
  55652. return CollisionCoordinatorWorker;
  55653. }());
  55654. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55655. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55656. function CollisionCoordinatorLegacy() {
  55657. this._scaledPosition = BABYLON.Vector3.Zero();
  55658. this._scaledVelocity = BABYLON.Vector3.Zero();
  55659. this._finalPosition = BABYLON.Vector3.Zero();
  55660. }
  55661. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55662. position.divideToRef(collider._radius, this._scaledPosition);
  55663. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55664. collider.collidedMesh = null;
  55665. collider._retry = 0;
  55666. collider._initialVelocity = this._scaledVelocity;
  55667. collider._initialPosition = this._scaledPosition;
  55668. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55669. this._finalPosition.multiplyInPlace(collider._radius);
  55670. //run the callback
  55671. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55672. };
  55673. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55674. this._scene = scene;
  55675. };
  55676. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55677. //Legacy need no destruction method.
  55678. };
  55679. //No update in legacy mode
  55680. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55681. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55682. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55683. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55684. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55685. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55686. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55687. if (excludedMesh === void 0) { excludedMesh = null; }
  55688. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55689. if (collider._retry >= maximumRetry) {
  55690. finalPosition.copyFrom(position);
  55691. return;
  55692. }
  55693. // Check if this is a mesh else camera or -1
  55694. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55695. collider._initialize(position, velocity, closeDistance);
  55696. // Check all meshes
  55697. for (var index = 0; index < this._scene.meshes.length; index++) {
  55698. var mesh = this._scene.meshes[index];
  55699. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55700. mesh._checkCollision(collider);
  55701. }
  55702. }
  55703. if (!collider.collisionFound) {
  55704. position.addToRef(velocity, finalPosition);
  55705. return;
  55706. }
  55707. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55708. collider._getResponse(position, velocity);
  55709. }
  55710. if (velocity.length() <= closeDistance) {
  55711. finalPosition.copyFrom(position);
  55712. return;
  55713. }
  55714. collider._retry++;
  55715. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55716. };
  55717. return CollisionCoordinatorLegacy;
  55718. }());
  55719. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55720. })(BABYLON || (BABYLON = {}));
  55721. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55722. var BABYLON;
  55723. (function (BABYLON) {
  55724. /**
  55725. * A particle represents one of the element emitted by a particle system.
  55726. * This is mainly define by its coordinates, direction, velocity and age.
  55727. */
  55728. var Particle = /** @class */ (function () {
  55729. /**
  55730. * Creates a new instance Particle
  55731. * @param particleSystem the particle system the particle belongs to
  55732. */
  55733. function Particle(
  55734. /**
  55735. * particleSystem the particle system the particle belongs to.
  55736. */
  55737. particleSystem) {
  55738. this.particleSystem = particleSystem;
  55739. /**
  55740. * The world position of the particle in the scene.
  55741. */
  55742. this.position = BABYLON.Vector3.Zero();
  55743. /**
  55744. * The world direction of the particle in the scene.
  55745. */
  55746. this.direction = BABYLON.Vector3.Zero();
  55747. /**
  55748. * The color of the particle.
  55749. */
  55750. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55751. /**
  55752. * The color change of the particle per step.
  55753. */
  55754. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55755. /**
  55756. * Defines how long will the life of the particle be.
  55757. */
  55758. this.lifeTime = 1.0;
  55759. /**
  55760. * The current age of the particle.
  55761. */
  55762. this.age = 0;
  55763. /**
  55764. * The current size of the particle.
  55765. */
  55766. this.size = 0;
  55767. /**
  55768. * The current angle of the particle.
  55769. */
  55770. this.angle = 0;
  55771. /**
  55772. * Defines how fast is the angle changing.
  55773. */
  55774. this.angularSpeed = 0;
  55775. /**
  55776. * Defines the cell index used by the particle to be rendered from a sprite.
  55777. */
  55778. this.cellIndex = 0;
  55779. this._currentFrameCounter = 0;
  55780. if (!this.particleSystem.isAnimationSheetEnabled) {
  55781. return;
  55782. }
  55783. this.updateCellInfoFromSystem();
  55784. }
  55785. Particle.prototype.updateCellInfoFromSystem = function () {
  55786. this.cellIndex = this.particleSystem.startSpriteCellID;
  55787. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55788. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55789. }
  55790. else {
  55791. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55792. }
  55793. };
  55794. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55795. // (ageOffset / scaledUpdateSpeed) / available cells
  55796. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55797. this._currentFrameCounter += scaledUpdateSpeed;
  55798. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55799. this._currentFrameCounter = 0;
  55800. this.cellIndex++;
  55801. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55802. this.cellIndex = this.particleSystem.endSpriteCellID;
  55803. }
  55804. }
  55805. };
  55806. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55807. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55808. this.cellIndex++;
  55809. this._currentFrameCounter = 0;
  55810. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55811. if (this.particleSystem.spriteCellLoop) {
  55812. this.cellIndex = this.particleSystem.startSpriteCellID;
  55813. }
  55814. else {
  55815. this.cellIndex = this.particleSystem.endSpriteCellID;
  55816. }
  55817. }
  55818. }
  55819. else {
  55820. this._currentFrameCounter++;
  55821. }
  55822. };
  55823. /**
  55824. * Copy the properties of particle to another one.
  55825. * @param other the particle to copy the information to.
  55826. */
  55827. Particle.prototype.copyTo = function (other) {
  55828. other.position.copyFrom(this.position);
  55829. other.direction.copyFrom(this.direction);
  55830. other.color.copyFrom(this.color);
  55831. other.colorStep.copyFrom(this.colorStep);
  55832. other.lifeTime = this.lifeTime;
  55833. other.age = this.age;
  55834. other.size = this.size;
  55835. other.angle = this.angle;
  55836. other.angularSpeed = this.angularSpeed;
  55837. other.particleSystem = this.particleSystem;
  55838. other.cellIndex = this.cellIndex;
  55839. };
  55840. return Particle;
  55841. }());
  55842. BABYLON.Particle = Particle;
  55843. })(BABYLON || (BABYLON = {}));
  55844. //# sourceMappingURL=babylon.particle.js.map
  55845. var BABYLON;
  55846. (function (BABYLON) {
  55847. /**
  55848. * This represents a particle system in Babylon.
  55849. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  55850. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55851. * @example https://doc.babylonjs.com/babylon101/particles
  55852. */
  55853. var ParticleSystem = /** @class */ (function () {
  55854. /**
  55855. * Instantiates a particle system.
  55856. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  55857. * @param name The name of the particle system
  55858. * @param capacity The max number of particles alive at the same time
  55859. * @param scene The scene the particle system belongs to
  55860. * @param customEffect a custom effect used to change the way particles are rendered by default
  55861. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55862. * @param epsilon Offset used to render the particles
  55863. */
  55864. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55865. if (customEffect === void 0) { customEffect = null; }
  55866. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55867. if (epsilon === void 0) { epsilon = 0.01; }
  55868. var _this = this;
  55869. /**
  55870. * List of animations used by the particle system.
  55871. */
  55872. this.animations = [];
  55873. /**
  55874. * The rendering group used by the Particle system to chose when to render.
  55875. */
  55876. this.renderingGroupId = 0;
  55877. /**
  55878. * The emitter represents the Mesh or position we are attaching the particle system to.
  55879. */
  55880. this.emitter = null;
  55881. /**
  55882. * The maximum number of particles to emit per frame
  55883. */
  55884. this.emitRate = 10;
  55885. /**
  55886. * If you want to launch only a few particles at once, that can be done, as well.
  55887. */
  55888. this.manualEmitCount = -1;
  55889. /**
  55890. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55891. */
  55892. this.updateSpeed = 0.01;
  55893. /**
  55894. * The amount of time the particle system is running (depends of the overall update speed).
  55895. */
  55896. this.targetStopDuration = 0;
  55897. /**
  55898. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55899. */
  55900. this.disposeOnStop = false;
  55901. /**
  55902. * Minimum power of emitting particles.
  55903. */
  55904. this.minEmitPower = 1;
  55905. /**
  55906. * Maximum power of emitting particles.
  55907. */
  55908. this.maxEmitPower = 1;
  55909. /**
  55910. * Minimum life time of emitting particles.
  55911. */
  55912. this.minLifeTime = 1;
  55913. /**
  55914. * Maximum life time of emitting particles.
  55915. */
  55916. this.maxLifeTime = 1;
  55917. /**
  55918. * Minimum Size of emitting particles.
  55919. */
  55920. this.minSize = 1;
  55921. /**
  55922. * Maximum Size of emitting particles.
  55923. */
  55924. this.maxSize = 1;
  55925. /**
  55926. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55927. */
  55928. this.minAngularSpeed = 0;
  55929. /**
  55930. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55931. */
  55932. this.maxAngularSpeed = 0;
  55933. /**
  55934. * The layer mask we are rendering the particles through.
  55935. */
  55936. this.layerMask = 0x0FFFFFFF;
  55937. /**
  55938. * This can help using your own shader to render the particle system.
  55939. * The according effect will be created
  55940. */
  55941. this.customShader = null;
  55942. /**
  55943. * By default particle system starts as soon as they are created. This prevents the
  55944. * automatic start to happen and let you decide when to start emitting particles.
  55945. */
  55946. this.preventAutoStart = false;
  55947. /**
  55948. * Callback triggered when the particle animation is ending.
  55949. */
  55950. this.onAnimationEnd = null;
  55951. /**
  55952. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55953. */
  55954. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55955. /**
  55956. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55957. * to override the particles.
  55958. */
  55959. this.forceDepthWrite = false;
  55960. /**
  55961. * You can use gravity if you want to give an orientation to your particles.
  55962. */
  55963. this.gravity = BABYLON.Vector3.Zero();
  55964. /**
  55965. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55966. */
  55967. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55968. /**
  55969. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55970. */
  55971. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55972. /**
  55973. * Color the particle will have at the end of its lifetime.
  55974. */
  55975. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55976. /**
  55977. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55978. */
  55979. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55980. /**
  55981. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55982. */
  55983. this.spriteCellLoop = true;
  55984. /**
  55985. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55986. */
  55987. this.spriteCellChangeSpeed = 0;
  55988. /**
  55989. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55990. */
  55991. this.startSpriteCellID = 0;
  55992. /**
  55993. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55994. */
  55995. this.endSpriteCellID = 0;
  55996. /**
  55997. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55998. */
  55999. this.spriteCellWidth = 0;
  56000. /**
  56001. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56002. */
  56003. this.spriteCellHeight = 0;
  56004. /**
  56005. * An event triggered when the system is disposed.
  56006. */
  56007. this.onDisposeObservable = new BABYLON.Observable();
  56008. this._particles = new Array();
  56009. this._stockParticles = new Array();
  56010. this._newPartsExcess = 0;
  56011. this._vertexBuffers = {};
  56012. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56013. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56014. this._scaledDirection = BABYLON.Vector3.Zero();
  56015. this._scaledGravity = BABYLON.Vector3.Zero();
  56016. this._currentRenderId = -1;
  56017. this._started = false;
  56018. this._stopped = false;
  56019. this._actualFrame = 0;
  56020. this._vertexBufferSize = 11;
  56021. // start of sub system methods
  56022. /**
  56023. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56024. * Its lifetime will start back at 0.
  56025. */
  56026. this.recycleParticle = function (particle) {
  56027. var lastParticle = _this._particles.pop();
  56028. if (lastParticle !== particle) {
  56029. lastParticle.copyTo(particle);
  56030. }
  56031. _this._stockParticles.push(lastParticle);
  56032. };
  56033. this._createParticle = function () {
  56034. var particle;
  56035. if (_this._stockParticles.length !== 0) {
  56036. particle = _this._stockParticles.pop();
  56037. particle.age = 0;
  56038. particle.cellIndex = _this.startSpriteCellID;
  56039. }
  56040. else {
  56041. particle = new BABYLON.Particle(_this);
  56042. }
  56043. return particle;
  56044. };
  56045. this._emitFromParticle = function (particle) {
  56046. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56047. return;
  56048. }
  56049. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56050. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56051. subSystem._rootParticleSystem = _this;
  56052. _this.activeSubSystems.push(subSystem);
  56053. subSystem.start();
  56054. };
  56055. this._appendParticleVertexes = null;
  56056. this.id = name;
  56057. this.name = name;
  56058. this._capacity = capacity;
  56059. this._epsilon = epsilon;
  56060. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56061. if (isAnimationSheetEnabled) {
  56062. this._vertexBufferSize = 12;
  56063. }
  56064. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56065. this._customEffect = customEffect;
  56066. scene.particleSystems.push(this);
  56067. this._createIndexBuffer();
  56068. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56069. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56070. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56071. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56072. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56073. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56074. if (this._isAnimationSheetEnabled) {
  56075. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56076. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56077. }
  56078. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56079. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56080. this._vertexBuffers["options"] = options;
  56081. // Default emitter type
  56082. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56083. this.updateFunction = function (particles) {
  56084. for (var index = 0; index < particles.length; index++) {
  56085. var particle = particles[index];
  56086. particle.age += _this._scaledUpdateSpeed;
  56087. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56088. _this._emitFromParticle(particle);
  56089. _this.recycleParticle(particle);
  56090. index--;
  56091. continue;
  56092. }
  56093. else {
  56094. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56095. particle.color.addInPlace(_this._scaledColorStep);
  56096. if (particle.color.a < 0)
  56097. particle.color.a = 0;
  56098. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56099. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56100. particle.position.addInPlace(_this._scaledDirection);
  56101. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56102. particle.direction.addInPlace(_this._scaledGravity);
  56103. if (_this._isAnimationSheetEnabled) {
  56104. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56105. }
  56106. }
  56107. }
  56108. };
  56109. }
  56110. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56111. /**
  56112. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56113. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56114. */
  56115. get: function () {
  56116. if (this.particleEmitterType.direction1) {
  56117. return this.particleEmitterType.direction1;
  56118. }
  56119. return BABYLON.Vector3.Zero();
  56120. },
  56121. set: function (value) {
  56122. if (this.particleEmitterType.direction1) {
  56123. this.particleEmitterType.direction1 = value;
  56124. }
  56125. },
  56126. enumerable: true,
  56127. configurable: true
  56128. });
  56129. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56130. /**
  56131. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56132. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56133. */
  56134. get: function () {
  56135. if (this.particleEmitterType.direction2) {
  56136. return this.particleEmitterType.direction2;
  56137. }
  56138. return BABYLON.Vector3.Zero();
  56139. },
  56140. set: function (value) {
  56141. if (this.particleEmitterType.direction2) {
  56142. this.particleEmitterType.direction2 = value;
  56143. }
  56144. },
  56145. enumerable: true,
  56146. configurable: true
  56147. });
  56148. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56149. /**
  56150. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56151. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56152. */
  56153. get: function () {
  56154. if (this.particleEmitterType.minEmitBox) {
  56155. return this.particleEmitterType.minEmitBox;
  56156. }
  56157. return BABYLON.Vector3.Zero();
  56158. },
  56159. set: function (value) {
  56160. if (this.particleEmitterType.minEmitBox) {
  56161. this.particleEmitterType.minEmitBox = value;
  56162. }
  56163. },
  56164. enumerable: true,
  56165. configurable: true
  56166. });
  56167. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56168. /**
  56169. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56170. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56171. */
  56172. get: function () {
  56173. if (this.particleEmitterType.maxEmitBox) {
  56174. return this.particleEmitterType.maxEmitBox;
  56175. }
  56176. return BABYLON.Vector3.Zero();
  56177. },
  56178. set: function (value) {
  56179. if (this.particleEmitterType.maxEmitBox) {
  56180. this.particleEmitterType.maxEmitBox = value;
  56181. }
  56182. },
  56183. enumerable: true,
  56184. configurable: true
  56185. });
  56186. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56187. /**
  56188. * Sets a callback that will be triggered when the system is disposed.
  56189. */
  56190. set: function (callback) {
  56191. if (this._onDisposeObserver) {
  56192. this.onDisposeObservable.remove(this._onDisposeObserver);
  56193. }
  56194. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56195. },
  56196. enumerable: true,
  56197. configurable: true
  56198. });
  56199. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56200. /**
  56201. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56202. */
  56203. get: function () {
  56204. return this._isAnimationSheetEnabled;
  56205. },
  56206. enumerable: true,
  56207. configurable: true
  56208. });
  56209. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56210. //end of Sub-emitter
  56211. /**
  56212. * Gets the current list of active particles
  56213. */
  56214. get: function () {
  56215. return this._particles;
  56216. },
  56217. enumerable: true,
  56218. configurable: true
  56219. });
  56220. /**
  56221. * Returns the string "ParticleSystem"
  56222. * @returns a string containing the class name
  56223. */
  56224. ParticleSystem.prototype.getClassName = function () {
  56225. return "ParticleSystem";
  56226. };
  56227. ParticleSystem.prototype._createIndexBuffer = function () {
  56228. var indices = [];
  56229. var index = 0;
  56230. for (var count = 0; count < this._capacity; count++) {
  56231. indices.push(index);
  56232. indices.push(index + 1);
  56233. indices.push(index + 2);
  56234. indices.push(index);
  56235. indices.push(index + 2);
  56236. indices.push(index + 3);
  56237. index += 4;
  56238. }
  56239. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56240. };
  56241. /**
  56242. * Gets the maximum number of particles active at the same time.
  56243. * @returns The max number of active particles.
  56244. */
  56245. ParticleSystem.prototype.getCapacity = function () {
  56246. return this._capacity;
  56247. };
  56248. /**
  56249. * Gets Wether there are still active particles in the system.
  56250. * @returns True if it is alive, otherwise false.
  56251. */
  56252. ParticleSystem.prototype.isAlive = function () {
  56253. return this._alive;
  56254. };
  56255. /**
  56256. * Gets Wether the system has been started.
  56257. * @returns True if it has been started, otherwise false.
  56258. */
  56259. ParticleSystem.prototype.isStarted = function () {
  56260. return this._started;
  56261. };
  56262. /**
  56263. * Starts the particle system and begins to emit.
  56264. */
  56265. ParticleSystem.prototype.start = function () {
  56266. this._started = true;
  56267. this._stopped = false;
  56268. this._actualFrame = 0;
  56269. if (this.subEmitters && this.subEmitters.length != 0) {
  56270. this.activeSubSystems = new Array();
  56271. }
  56272. };
  56273. /**
  56274. * Stops the particle system.
  56275. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  56276. */
  56277. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56278. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56279. this._stopped = true;
  56280. if (stopSubEmitters) {
  56281. this._stopSubEmitters();
  56282. }
  56283. };
  56284. // animation sheet
  56285. /**
  56286. * Remove all active particles
  56287. */
  56288. ParticleSystem.prototype.reset = function () {
  56289. this._stockParticles = [];
  56290. this._particles = [];
  56291. };
  56292. /**
  56293. * @hidden (for internal use only)
  56294. */
  56295. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56296. var offset = index * this._vertexBufferSize;
  56297. this._vertexData[offset] = particle.position.x;
  56298. this._vertexData[offset + 1] = particle.position.y;
  56299. this._vertexData[offset + 2] = particle.position.z;
  56300. this._vertexData[offset + 3] = particle.color.r;
  56301. this._vertexData[offset + 4] = particle.color.g;
  56302. this._vertexData[offset + 5] = particle.color.b;
  56303. this._vertexData[offset + 6] = particle.color.a;
  56304. this._vertexData[offset + 7] = particle.angle;
  56305. this._vertexData[offset + 8] = particle.size;
  56306. this._vertexData[offset + 9] = offsetX;
  56307. this._vertexData[offset + 10] = offsetY;
  56308. };
  56309. /**
  56310. * @hidden (for internal use only)
  56311. */
  56312. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56313. if (offsetX === 0)
  56314. offsetX = this._epsilon;
  56315. else if (offsetX === 1)
  56316. offsetX = 1 - this._epsilon;
  56317. if (offsetY === 0)
  56318. offsetY = this._epsilon;
  56319. else if (offsetY === 1)
  56320. offsetY = 1 - this._epsilon;
  56321. var offset = index * this._vertexBufferSize;
  56322. this._vertexData[offset] = particle.position.x;
  56323. this._vertexData[offset + 1] = particle.position.y;
  56324. this._vertexData[offset + 2] = particle.position.z;
  56325. this._vertexData[offset + 3] = particle.color.r;
  56326. this._vertexData[offset + 4] = particle.color.g;
  56327. this._vertexData[offset + 5] = particle.color.b;
  56328. this._vertexData[offset + 6] = particle.color.a;
  56329. this._vertexData[offset + 7] = particle.angle;
  56330. this._vertexData[offset + 8] = particle.size;
  56331. this._vertexData[offset + 9] = offsetX;
  56332. this._vertexData[offset + 10] = offsetY;
  56333. this._vertexData[offset + 11] = particle.cellIndex;
  56334. };
  56335. ParticleSystem.prototype._stopSubEmitters = function () {
  56336. if (!this.activeSubSystems) {
  56337. return;
  56338. }
  56339. this.activeSubSystems.forEach(function (subSystem) {
  56340. subSystem.stop(true);
  56341. });
  56342. this.activeSubSystems = new Array();
  56343. };
  56344. ParticleSystem.prototype._removeFromRoot = function () {
  56345. if (!this._rootParticleSystem) {
  56346. return;
  56347. }
  56348. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56349. if (index !== -1) {
  56350. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56351. }
  56352. };
  56353. // end of sub system methods
  56354. ParticleSystem.prototype._update = function (newParticles) {
  56355. // Update current
  56356. this._alive = this._particles.length > 0;
  56357. this.updateFunction(this._particles);
  56358. // Add new ones
  56359. var worldMatrix;
  56360. if (this.emitter.position) {
  56361. var emitterMesh = this.emitter;
  56362. worldMatrix = emitterMesh.getWorldMatrix();
  56363. }
  56364. else {
  56365. var emitterPosition = this.emitter;
  56366. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56367. }
  56368. var particle;
  56369. for (var index = 0; index < newParticles; index++) {
  56370. if (this._particles.length === this._capacity) {
  56371. break;
  56372. }
  56373. particle = this._createParticle();
  56374. this._particles.push(particle);
  56375. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56376. if (this.startPositionFunction) {
  56377. this.startPositionFunction(worldMatrix, particle.position, particle);
  56378. }
  56379. else {
  56380. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56381. }
  56382. if (this.startDirectionFunction) {
  56383. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56384. }
  56385. else {
  56386. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56387. }
  56388. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56389. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56390. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56391. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56392. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56393. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56394. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56395. }
  56396. };
  56397. ParticleSystem.prototype._getEffect = function () {
  56398. if (this._customEffect) {
  56399. return this._customEffect;
  56400. }
  56401. ;
  56402. var defines = [];
  56403. if (this._scene.clipPlane) {
  56404. defines.push("#define CLIPPLANE");
  56405. }
  56406. if (this._isAnimationSheetEnabled) {
  56407. defines.push("#define ANIMATESHEET");
  56408. }
  56409. // Effect
  56410. var join = defines.join("\n");
  56411. if (this._cachedDefines !== join) {
  56412. this._cachedDefines = join;
  56413. var attributesNamesOrOptions;
  56414. var effectCreationOption;
  56415. if (this._isAnimationSheetEnabled) {
  56416. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56417. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56418. }
  56419. else {
  56420. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56421. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56422. }
  56423. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56424. }
  56425. return this._effect;
  56426. };
  56427. /**
  56428. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56429. */
  56430. ParticleSystem.prototype.animate = function () {
  56431. if (!this._started)
  56432. return;
  56433. var effect = this._getEffect();
  56434. // Check
  56435. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56436. return;
  56437. if (this._currentRenderId === this._scene.getRenderId()) {
  56438. return;
  56439. }
  56440. this._currentRenderId = this._scene.getRenderId();
  56441. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56442. // determine the number of particles we need to create
  56443. var newParticles;
  56444. if (this.manualEmitCount > -1) {
  56445. newParticles = this.manualEmitCount;
  56446. this._newPartsExcess = 0;
  56447. this.manualEmitCount = 0;
  56448. }
  56449. else {
  56450. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56451. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56452. }
  56453. if (this._newPartsExcess > 1.0) {
  56454. newParticles += this._newPartsExcess >> 0;
  56455. this._newPartsExcess -= this._newPartsExcess >> 0;
  56456. }
  56457. this._alive = false;
  56458. if (!this._stopped) {
  56459. this._actualFrame += this._scaledUpdateSpeed;
  56460. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56461. this.stop();
  56462. }
  56463. else {
  56464. newParticles = 0;
  56465. }
  56466. this._update(newParticles);
  56467. // Stopped?
  56468. if (this._stopped) {
  56469. if (!this._alive) {
  56470. this._started = false;
  56471. if (this.onAnimationEnd) {
  56472. this.onAnimationEnd();
  56473. }
  56474. if (this.disposeOnStop) {
  56475. this._scene._toBeDisposed.push(this);
  56476. }
  56477. }
  56478. }
  56479. // Animation sheet
  56480. if (this._isAnimationSheetEnabled) {
  56481. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56482. }
  56483. else {
  56484. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56485. }
  56486. // Update VBO
  56487. var offset = 0;
  56488. for (var index = 0; index < this._particles.length; index++) {
  56489. var particle = this._particles[index];
  56490. this._appendParticleVertexes(offset, particle);
  56491. offset += 4;
  56492. }
  56493. if (this._vertexBuffer) {
  56494. this._vertexBuffer.update(this._vertexData);
  56495. }
  56496. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56497. this.stop();
  56498. }
  56499. };
  56500. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56501. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56502. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56503. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56504. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56505. };
  56506. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56507. this._appendParticleVertex(offset++, particle, 0, 0);
  56508. this._appendParticleVertex(offset++, particle, 1, 0);
  56509. this._appendParticleVertex(offset++, particle, 1, 1);
  56510. this._appendParticleVertex(offset++, particle, 0, 1);
  56511. };
  56512. /**
  56513. * Rebuilds the particle system.
  56514. */
  56515. ParticleSystem.prototype.rebuild = function () {
  56516. this._createIndexBuffer();
  56517. if (this._vertexBuffer) {
  56518. this._vertexBuffer._rebuild();
  56519. }
  56520. };
  56521. /**
  56522. * Is this system ready to be used/rendered
  56523. * @return true if the system is ready
  56524. */
  56525. ParticleSystem.prototype.isReady = function () {
  56526. var effect = this._getEffect();
  56527. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56528. return false;
  56529. }
  56530. return true;
  56531. };
  56532. /**
  56533. * Renders the particle system in its current state.
  56534. * @returns the current number of particles
  56535. */
  56536. ParticleSystem.prototype.render = function () {
  56537. var effect = this._getEffect();
  56538. // Check
  56539. if (!this.isReady() || !this._particles.length) {
  56540. return 0;
  56541. }
  56542. var engine = this._scene.getEngine();
  56543. // Render
  56544. engine.enableEffect(effect);
  56545. engine.setState(false);
  56546. var viewMatrix = this._scene.getViewMatrix();
  56547. effect.setTexture("diffuseSampler", this.particleTexture);
  56548. effect.setMatrix("view", viewMatrix);
  56549. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56550. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56551. var baseSize = this.particleTexture.getBaseSize();
  56552. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56553. }
  56554. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56555. if (this._scene.clipPlane) {
  56556. var clipPlane = this._scene.clipPlane;
  56557. var invView = viewMatrix.clone();
  56558. invView.invert();
  56559. effect.setMatrix("invView", invView);
  56560. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56561. }
  56562. // VBOs
  56563. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56564. // Draw order
  56565. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56566. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56567. }
  56568. else {
  56569. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56570. }
  56571. if (this.forceDepthWrite) {
  56572. engine.setDepthWrite(true);
  56573. }
  56574. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56575. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56576. return this._particles.length;
  56577. };
  56578. /**
  56579. * Disposes the particle system and free the associated resources
  56580. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56581. */
  56582. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56583. if (disposeTexture === void 0) { disposeTexture = true; }
  56584. if (this._vertexBuffer) {
  56585. this._vertexBuffer.dispose();
  56586. this._vertexBuffer = null;
  56587. }
  56588. if (this._indexBuffer) {
  56589. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56590. this._indexBuffer = null;
  56591. }
  56592. if (disposeTexture && this.particleTexture) {
  56593. this.particleTexture.dispose();
  56594. this.particleTexture = null;
  56595. }
  56596. this._removeFromRoot();
  56597. // Remove from scene
  56598. var index = this._scene.particleSystems.indexOf(this);
  56599. if (index > -1) {
  56600. this._scene.particleSystems.splice(index, 1);
  56601. }
  56602. // Callback
  56603. this.onDisposeObservable.notifyObservers(this);
  56604. this.onDisposeObservable.clear();
  56605. };
  56606. /**
  56607. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56608. * @param radius The radius of the sphere to emit from
  56609. * @returns the emitter
  56610. */
  56611. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56612. if (radius === void 0) { radius = 1; }
  56613. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56614. this.particleEmitterType = particleEmitter;
  56615. return particleEmitter;
  56616. };
  56617. /**
  56618. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56619. * @param radius The radius of the sphere to emit from
  56620. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56621. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56622. * @returns the emitter
  56623. */
  56624. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56625. if (radius === void 0) { radius = 1; }
  56626. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56627. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56628. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56629. this.particleEmitterType = particleEmitter;
  56630. return particleEmitter;
  56631. };
  56632. /**
  56633. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56634. * @param radius The radius of the cone to emit from
  56635. * @param angle The base angle of the cone
  56636. * @returns the emitter
  56637. */
  56638. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56639. if (radius === void 0) { radius = 1; }
  56640. if (angle === void 0) { angle = Math.PI / 4; }
  56641. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56642. this.particleEmitterType = particleEmitter;
  56643. return particleEmitter;
  56644. };
  56645. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56646. /**
  56647. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56648. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56649. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56650. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56651. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56652. * @returns the emitter
  56653. */
  56654. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56655. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56656. this.particleEmitterType = particleEmitter;
  56657. this.direction1 = direction1;
  56658. this.direction2 = direction2;
  56659. this.minEmitBox = minEmitBox;
  56660. this.maxEmitBox = maxEmitBox;
  56661. return particleEmitter;
  56662. };
  56663. // Clone
  56664. /**
  56665. * Clones the particle system.
  56666. * @param name The name of the cloned object
  56667. * @param newEmitter The new emitter to use
  56668. * @returns the cloned particle system
  56669. */
  56670. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56671. var custom = null;
  56672. var program = null;
  56673. if (this.customShader != null) {
  56674. program = this.customShader;
  56675. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56676. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56677. }
  56678. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56679. result.customShader = program;
  56680. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56681. if (newEmitter === undefined) {
  56682. newEmitter = this.emitter;
  56683. }
  56684. result.emitter = newEmitter;
  56685. if (this.particleTexture) {
  56686. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56687. }
  56688. if (!this.preventAutoStart) {
  56689. result.start();
  56690. }
  56691. return result;
  56692. };
  56693. /**
  56694. * Serializes the particle system to a JSON object.
  56695. * @returns the JSON object
  56696. */
  56697. ParticleSystem.prototype.serialize = function () {
  56698. var serializationObject = {};
  56699. serializationObject.name = this.name;
  56700. serializationObject.id = this.id;
  56701. // Emitter
  56702. if (this.emitter.position) {
  56703. var emitterMesh = this.emitter;
  56704. serializationObject.emitterId = emitterMesh.id;
  56705. }
  56706. else {
  56707. var emitterPosition = this.emitter;
  56708. serializationObject.emitter = emitterPosition.asArray();
  56709. }
  56710. serializationObject.capacity = this.getCapacity();
  56711. if (this.particleTexture) {
  56712. serializationObject.textureName = this.particleTexture.name;
  56713. }
  56714. // Animations
  56715. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56716. // Particle system
  56717. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56718. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56719. serializationObject.minSize = this.minSize;
  56720. serializationObject.maxSize = this.maxSize;
  56721. serializationObject.minEmitPower = this.minEmitPower;
  56722. serializationObject.maxEmitPower = this.maxEmitPower;
  56723. serializationObject.minLifeTime = this.minLifeTime;
  56724. serializationObject.maxLifeTime = this.maxLifeTime;
  56725. serializationObject.emitRate = this.emitRate;
  56726. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56727. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56728. serializationObject.gravity = this.gravity.asArray();
  56729. serializationObject.direction1 = this.direction1.asArray();
  56730. serializationObject.direction2 = this.direction2.asArray();
  56731. serializationObject.color1 = this.color1.asArray();
  56732. serializationObject.color2 = this.color2.asArray();
  56733. serializationObject.colorDead = this.colorDead.asArray();
  56734. serializationObject.updateSpeed = this.updateSpeed;
  56735. serializationObject.targetStopDuration = this.targetStopDuration;
  56736. serializationObject.textureMask = this.textureMask.asArray();
  56737. serializationObject.blendMode = this.blendMode;
  56738. serializationObject.customShader = this.customShader;
  56739. serializationObject.preventAutoStart = this.preventAutoStart;
  56740. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56741. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56742. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56743. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56744. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56745. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56746. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56747. // Emitter
  56748. if (this.particleEmitterType) {
  56749. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56750. }
  56751. return serializationObject;
  56752. };
  56753. /**
  56754. * Parses a JSON object to create a particle system.
  56755. * @param parsedParticleSystem The JSON object to parse
  56756. * @param scene The scene to create the particle system in
  56757. * @param rootUrl The root url to use to load external dependencies like texture
  56758. * @returns the Parsed particle system
  56759. */
  56760. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56761. var name = parsedParticleSystem.name;
  56762. var custom = null;
  56763. var program = null;
  56764. if (parsedParticleSystem.customShader) {
  56765. program = parsedParticleSystem.customShader;
  56766. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56767. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56768. }
  56769. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56770. particleSystem.customShader = program;
  56771. if (parsedParticleSystem.id) {
  56772. particleSystem.id = parsedParticleSystem.id;
  56773. }
  56774. // Auto start
  56775. if (parsedParticleSystem.preventAutoStart) {
  56776. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56777. }
  56778. // Texture
  56779. if (parsedParticleSystem.textureName) {
  56780. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56781. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56782. }
  56783. // Emitter
  56784. if (parsedParticleSystem.emitterId) {
  56785. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56786. }
  56787. else {
  56788. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56789. }
  56790. // Animations
  56791. if (parsedParticleSystem.animations) {
  56792. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56793. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56794. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56795. }
  56796. }
  56797. if (parsedParticleSystem.autoAnimate) {
  56798. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56799. }
  56800. // Particle system
  56801. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56802. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56803. particleSystem.minSize = parsedParticleSystem.minSize;
  56804. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56805. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56806. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56807. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56808. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56809. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56810. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56811. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56812. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56813. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56814. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56815. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56816. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56817. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56818. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56819. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56820. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56821. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56822. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56823. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56824. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56825. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56826. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56827. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56828. if (!particleSystem.preventAutoStart) {
  56829. particleSystem.start();
  56830. }
  56831. return particleSystem;
  56832. };
  56833. /**
  56834. * Source color is added to the destination color without alpha affecting the result.
  56835. */
  56836. ParticleSystem.BLENDMODE_ONEONE = 0;
  56837. /**
  56838. * Blend current color and particle color using particle’s alpha.
  56839. */
  56840. ParticleSystem.BLENDMODE_STANDARD = 1;
  56841. return ParticleSystem;
  56842. }());
  56843. BABYLON.ParticleSystem = ParticleSystem;
  56844. })(BABYLON || (BABYLON = {}));
  56845. //# sourceMappingURL=babylon.particleSystem.js.map
  56846. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56847. var BABYLON;
  56848. (function (BABYLON) {
  56849. /**
  56850. * Particle emitter emitting particles from the inside of a box.
  56851. * It emits the particles randomly between 2 given directions.
  56852. */
  56853. var BoxParticleEmitter = /** @class */ (function () {
  56854. /**
  56855. * Creates a new instance BoxParticleEmitter
  56856. */
  56857. function BoxParticleEmitter() {
  56858. /**
  56859. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56860. */
  56861. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56862. /**
  56863. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56864. */
  56865. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56866. /**
  56867. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56868. */
  56869. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56870. /**
  56871. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56872. */
  56873. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56874. }
  56875. /**
  56876. * Called by the particle System when the direction is computed for the created particle.
  56877. * @param emitPower is the power of the particle (speed)
  56878. * @param worldMatrix is the world matrix of the particle system
  56879. * @param directionToUpdate is the direction vector to update with the result
  56880. * @param particle is the particle we are computed the direction for
  56881. */
  56882. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56883. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56884. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56885. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56886. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56887. };
  56888. /**
  56889. * Called by the particle System when the position is computed for the created particle.
  56890. * @param worldMatrix is the world matrix of the particle system
  56891. * @param positionToUpdate is the position vector to update with the result
  56892. * @param particle is the particle we are computed the position for
  56893. */
  56894. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56895. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56896. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56897. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56898. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56899. };
  56900. /**
  56901. * Clones the current emitter and returns a copy of it
  56902. * @returns the new emitter
  56903. */
  56904. BoxParticleEmitter.prototype.clone = function () {
  56905. var newOne = new BoxParticleEmitter();
  56906. BABYLON.Tools.DeepCopy(this, newOne);
  56907. return newOne;
  56908. };
  56909. /**
  56910. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56911. * @param effect defines the update shader
  56912. */
  56913. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56914. effect.setVector3("direction1", this.direction1);
  56915. effect.setVector3("direction2", this.direction2);
  56916. effect.setVector3("minEmitBox", this.minEmitBox);
  56917. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56918. };
  56919. /**
  56920. * Returns a string to use to update the GPU particles update shader
  56921. * @returns a string containng the defines string
  56922. */
  56923. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56924. return "#define BOXEMITTER";
  56925. };
  56926. /**
  56927. * Returns the string "BoxEmitter"
  56928. * @returns a string containing the class name
  56929. */
  56930. BoxParticleEmitter.prototype.getClassName = function () {
  56931. return "BoxEmitter";
  56932. };
  56933. /**
  56934. * Serializes the particle system to a JSON object.
  56935. * @returns the JSON object
  56936. */
  56937. BoxParticleEmitter.prototype.serialize = function () {
  56938. var serializationObject = {};
  56939. serializationObject.type = this.getClassName();
  56940. serializationObject.direction1 = this.direction1.asArray();
  56941. serializationObject.direction2 = this.direction2.asArray();
  56942. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56943. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56944. return serializationObject;
  56945. };
  56946. /**
  56947. * Parse properties from a JSON object
  56948. * @param serializationObject defines the JSON object
  56949. */
  56950. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56951. this.direction1.copyFrom(serializationObject.direction1);
  56952. this.direction2.copyFrom(serializationObject.direction2);
  56953. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56954. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56955. };
  56956. return BoxParticleEmitter;
  56957. }());
  56958. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56959. })(BABYLON || (BABYLON = {}));
  56960. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56961. var BABYLON;
  56962. (function (BABYLON) {
  56963. /**
  56964. * Particle emitter emitting particles from the inside of a cone.
  56965. * It emits the particles alongside the cone volume from the base to the particle.
  56966. * The emission direction might be randomized.
  56967. */
  56968. var ConeParticleEmitter = /** @class */ (function () {
  56969. /**
  56970. * Creates a new instance ConeParticleEmitter
  56971. * @param radius the radius of the emission cone (1 by default)
  56972. * @param angles the cone base angle (PI by default)
  56973. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56974. */
  56975. function ConeParticleEmitter(radius,
  56976. /**
  56977. * The radius of the emission cone.
  56978. */
  56979. angle,
  56980. /**
  56981. * The cone base angle.
  56982. */
  56983. directionRandomizer) {
  56984. if (radius === void 0) { radius = 1; }
  56985. if (angle === void 0) { angle = Math.PI; }
  56986. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56987. this.angle = angle;
  56988. this.directionRandomizer = directionRandomizer;
  56989. this.radius = radius;
  56990. }
  56991. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56992. /**
  56993. * Gets the radius of the emission cone.
  56994. */
  56995. get: function () {
  56996. return this._radius;
  56997. },
  56998. /**
  56999. * Sets the radius of the emission cone.
  57000. */
  57001. set: function (value) {
  57002. this._radius = value;
  57003. if (this.angle !== 0) {
  57004. this._height = value / Math.tan(this.angle / 2);
  57005. }
  57006. else {
  57007. this._height = 1;
  57008. }
  57009. },
  57010. enumerable: true,
  57011. configurable: true
  57012. });
  57013. /**
  57014. * Called by the particle System when the direction is computed for the created particle.
  57015. * @param emitPower is the power of the particle (speed)
  57016. * @param worldMatrix is the world matrix of the particle system
  57017. * @param directionToUpdate is the direction vector to update with the result
  57018. * @param particle is the particle we are computed the direction for
  57019. */
  57020. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57021. if (this.angle === 0) {
  57022. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57023. }
  57024. else {
  57025. // measure the direction Vector from the emitter to the particle.
  57026. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57027. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57028. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57029. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57030. direction.x += randX;
  57031. direction.y += randY;
  57032. direction.z += randZ;
  57033. direction.normalize();
  57034. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57035. }
  57036. };
  57037. /**
  57038. * Called by the particle System when the position is computed for the created particle.
  57039. * @param worldMatrix is the world matrix of the particle system
  57040. * @param positionToUpdate is the position vector to update with the result
  57041. * @param particle is the particle we are computed the position for
  57042. */
  57043. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57044. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57045. var h = BABYLON.Scalar.RandomRange(0, 1);
  57046. // Better distribution in a cone at normal angles.
  57047. h = 1 - h * h;
  57048. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57049. radius = radius * h;
  57050. var randX = radius * Math.sin(s);
  57051. var randZ = radius * Math.cos(s);
  57052. var randY = h * this._height;
  57053. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57054. };
  57055. /**
  57056. * Clones the current emitter and returns a copy of it
  57057. * @returns the new emitter
  57058. */
  57059. ConeParticleEmitter.prototype.clone = function () {
  57060. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57061. BABYLON.Tools.DeepCopy(this, newOne);
  57062. return newOne;
  57063. };
  57064. /**
  57065. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57066. * @param effect defines the update shader
  57067. */
  57068. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57069. effect.setFloat("radius", this.radius);
  57070. effect.setFloat("angle", this.angle);
  57071. effect.setFloat("height", this._height);
  57072. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57073. };
  57074. /**
  57075. * Returns a string to use to update the GPU particles update shader
  57076. * @returns a string containng the defines string
  57077. */
  57078. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57079. return "#define CONEEMITTER";
  57080. };
  57081. /**
  57082. * Returns the string "BoxEmitter"
  57083. * @returns a string containing the class name
  57084. */
  57085. ConeParticleEmitter.prototype.getClassName = function () {
  57086. return "ConeEmitter";
  57087. };
  57088. /**
  57089. * Serializes the particle system to a JSON object.
  57090. * @returns the JSON object
  57091. */
  57092. ConeParticleEmitter.prototype.serialize = function () {
  57093. var serializationObject = {};
  57094. serializationObject.type = this.getClassName();
  57095. serializationObject.radius = this.radius;
  57096. serializationObject.angle = this.angle;
  57097. serializationObject.directionRandomizer = this.directionRandomizer;
  57098. return serializationObject;
  57099. };
  57100. /**
  57101. * Parse properties from a JSON object
  57102. * @param serializationObject defines the JSON object
  57103. */
  57104. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57105. this.radius = serializationObject.radius;
  57106. this.angle = serializationObject.angle;
  57107. this.directionRandomizer = serializationObject.directionRandomizer;
  57108. };
  57109. return ConeParticleEmitter;
  57110. }());
  57111. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57112. })(BABYLON || (BABYLON = {}));
  57113. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57114. var BABYLON;
  57115. (function (BABYLON) {
  57116. /**
  57117. * Particle emitter emitting particles from the inside of a sphere.
  57118. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57119. */
  57120. var SphereParticleEmitter = /** @class */ (function () {
  57121. /**
  57122. * Creates a new instance SphereParticleEmitter
  57123. * @param radius the radius of the emission sphere (1 by default)
  57124. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57125. */
  57126. function SphereParticleEmitter(
  57127. /**
  57128. * The radius of the emission sphere.
  57129. */
  57130. radius,
  57131. /**
  57132. * How much to randomize the particle direction [0-1].
  57133. */
  57134. directionRandomizer) {
  57135. if (radius === void 0) { radius = 1; }
  57136. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57137. this.radius = radius;
  57138. this.directionRandomizer = directionRandomizer;
  57139. }
  57140. /**
  57141. * Called by the particle System when the direction is computed for the created particle.
  57142. * @param emitPower is the power of the particle (speed)
  57143. * @param worldMatrix is the world matrix of the particle system
  57144. * @param directionToUpdate is the direction vector to update with the result
  57145. * @param particle is the particle we are computed the direction for
  57146. */
  57147. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57148. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57149. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57150. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57151. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57152. direction.x += randX;
  57153. direction.y += randY;
  57154. direction.z += randZ;
  57155. direction.normalize();
  57156. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57157. };
  57158. /**
  57159. * Called by the particle System when the position is computed for the created particle.
  57160. * @param worldMatrix is the world matrix of the particle system
  57161. * @param positionToUpdate is the position vector to update with the result
  57162. * @param particle is the particle we are computed the position for
  57163. */
  57164. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57165. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57166. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57167. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57168. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57169. var randY = randRadius * Math.cos(theta);
  57170. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57171. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57172. };
  57173. /**
  57174. * Clones the current emitter and returns a copy of it
  57175. * @returns the new emitter
  57176. */
  57177. SphereParticleEmitter.prototype.clone = function () {
  57178. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57179. BABYLON.Tools.DeepCopy(this, newOne);
  57180. return newOne;
  57181. };
  57182. /**
  57183. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57184. * @param effect defines the update shader
  57185. */
  57186. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57187. effect.setFloat("radius", this.radius);
  57188. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57189. };
  57190. /**
  57191. * Returns a string to use to update the GPU particles update shader
  57192. * @returns a string containng the defines string
  57193. */
  57194. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57195. return "#define SPHEREEMITTER";
  57196. };
  57197. /**
  57198. * Returns the string "SphereParticleEmitter"
  57199. * @returns a string containing the class name
  57200. */
  57201. SphereParticleEmitter.prototype.getClassName = function () {
  57202. return "SphereParticleEmitter";
  57203. };
  57204. /**
  57205. * Serializes the particle system to a JSON object.
  57206. * @returns the JSON object
  57207. */
  57208. SphereParticleEmitter.prototype.serialize = function () {
  57209. var serializationObject = {};
  57210. serializationObject.type = this.getClassName();
  57211. serializationObject.radius = this.radius;
  57212. serializationObject.directionRandomizer = this.directionRandomizer;
  57213. return serializationObject;
  57214. };
  57215. /**
  57216. * Parse properties from a JSON object
  57217. * @param serializationObject defines the JSON object
  57218. */
  57219. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57220. this.radius = serializationObject.radius;
  57221. this.directionRandomizer = serializationObject.directionRandomizer;
  57222. };
  57223. return SphereParticleEmitter;
  57224. }());
  57225. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57226. /**
  57227. * Particle emitter emitting particles from the inside of a sphere.
  57228. * It emits the particles randomly between two vectors.
  57229. */
  57230. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57231. __extends(SphereDirectedParticleEmitter, _super);
  57232. /**
  57233. * Creates a new instance SphereDirectedParticleEmitter
  57234. * @param radius the radius of the emission sphere (1 by default)
  57235. * @param direction1 the min limit of the emission direction (up vector by default)
  57236. * @param direction2 the max limit of the emission direction (up vector by default)
  57237. */
  57238. function SphereDirectedParticleEmitter(radius,
  57239. /**
  57240. * The min limit of the emission direction.
  57241. */
  57242. direction1,
  57243. /**
  57244. * The max limit of the emission direction.
  57245. */
  57246. direction2) {
  57247. if (radius === void 0) { radius = 1; }
  57248. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57249. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57250. var _this = _super.call(this, radius) || this;
  57251. _this.direction1 = direction1;
  57252. _this.direction2 = direction2;
  57253. return _this;
  57254. }
  57255. /**
  57256. * Called by the particle System when the direction is computed for the created particle.
  57257. * @param emitPower is the power of the particle (speed)
  57258. * @param worldMatrix is the world matrix of the particle system
  57259. * @param directionToUpdate is the direction vector to update with the result
  57260. * @param particle is the particle we are computed the direction for
  57261. */
  57262. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57263. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57264. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57265. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57266. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57267. };
  57268. /**
  57269. * Clones the current emitter and returns a copy of it
  57270. * @returns the new emitter
  57271. */
  57272. SphereDirectedParticleEmitter.prototype.clone = function () {
  57273. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57274. BABYLON.Tools.DeepCopy(this, newOne);
  57275. return newOne;
  57276. };
  57277. /**
  57278. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57279. * @param effect defines the update shader
  57280. */
  57281. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57282. effect.setFloat("radius", this.radius);
  57283. effect.setVector3("direction1", this.direction1);
  57284. effect.setVector3("direction2", this.direction2);
  57285. };
  57286. /**
  57287. * Returns a string to use to update the GPU particles update shader
  57288. * @returns a string containng the defines string
  57289. */
  57290. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57291. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57292. };
  57293. /**
  57294. * Returns the string "SphereDirectedParticleEmitter"
  57295. * @returns a string containing the class name
  57296. */
  57297. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57298. return "SphereDirectedParticleEmitter";
  57299. };
  57300. /**
  57301. * Serializes the particle system to a JSON object.
  57302. * @returns the JSON object
  57303. */
  57304. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57305. var serializationObject = _super.prototype.serialize.call(this);
  57306. serializationObject.direction1 = this.direction1.asArray();
  57307. serializationObject.direction2 = this.direction2.asArray();
  57308. return serializationObject;
  57309. };
  57310. /**
  57311. * Parse properties from a JSON object
  57312. * @param serializationObject defines the JSON object
  57313. */
  57314. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57315. _super.prototype.parse.call(this, serializationObject);
  57316. this.direction1.copyFrom(serializationObject.direction1);
  57317. this.direction2.copyFrom(serializationObject.direction2);
  57318. };
  57319. return SphereDirectedParticleEmitter;
  57320. }(SphereParticleEmitter));
  57321. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57322. })(BABYLON || (BABYLON = {}));
  57323. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57324. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57325. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57326. s = arguments[i];
  57327. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57328. t[p] = s[p];
  57329. }
  57330. return t;
  57331. };
  57332. var BABYLON;
  57333. (function (BABYLON) {
  57334. /**
  57335. * This represents a GPU particle system in Babylon
  57336. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57337. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57338. */
  57339. var GPUParticleSystem = /** @class */ (function () {
  57340. /**
  57341. * Instantiates a GPU particle system.
  57342. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  57343. * @param name The name of the particle system
  57344. * @param capacity The max number of particles alive at the same time
  57345. * @param scene The scene the particle system belongs to
  57346. */
  57347. function GPUParticleSystem(name, options, scene) {
  57348. /**
  57349. * The emitter represents the Mesh or position we are attaching the particle system to.
  57350. */
  57351. this.emitter = null;
  57352. /**
  57353. * The rendering group used by the Particle system to chose when to render.
  57354. */
  57355. this.renderingGroupId = 0;
  57356. /**
  57357. * The layer mask we are rendering the particles through.
  57358. */
  57359. this.layerMask = 0x0FFFFFFF;
  57360. this._targetIndex = 0;
  57361. this._currentRenderId = -1;
  57362. this._started = false;
  57363. this._stopped = false;
  57364. this._timeDelta = 0;
  57365. this._attributesStrideSize = 14;
  57366. this._actualFrame = 0;
  57367. /**
  57368. * List of animations used by the particle system.
  57369. */
  57370. this.animations = [];
  57371. /**
  57372. * An event triggered when the system is disposed.
  57373. */
  57374. this.onDisposeObservable = new BABYLON.Observable();
  57375. /**
  57376. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57377. */
  57378. this.updateSpeed = 0.01;
  57379. /**
  57380. * The amount of time the particle system is running (depends of the overall update speed).
  57381. */
  57382. this.targetStopDuration = 0;
  57383. /**
  57384. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57385. */
  57386. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57387. /**
  57388. * Minimum life time of emitting particles.
  57389. */
  57390. this.minLifeTime = 1;
  57391. /**
  57392. * Maximum life time of emitting particles.
  57393. */
  57394. this.maxLifeTime = 1;
  57395. /**
  57396. * Minimum Size of emitting particles.
  57397. */
  57398. this.minSize = 1;
  57399. /**
  57400. * Maximum Size of emitting particles.
  57401. */
  57402. this.maxSize = 1;
  57403. /**
  57404. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57405. */
  57406. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57407. /**
  57408. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57409. */
  57410. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57411. /**
  57412. * Color the particle will have at the end of its lifetime.
  57413. */
  57414. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57415. /**
  57416. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57417. */
  57418. this.emitRate = 100;
  57419. /**
  57420. * You can use gravity if you want to give an orientation to your particles.
  57421. */
  57422. this.gravity = BABYLON.Vector3.Zero();
  57423. /**
  57424. * Minimum power of emitting particles.
  57425. */
  57426. this.minEmitPower = 1;
  57427. /**
  57428. * Maximum power of emitting particles.
  57429. */
  57430. this.maxEmitPower = 1;
  57431. /**
  57432. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57433. * to override the particles.
  57434. */
  57435. this.forceDepthWrite = false;
  57436. this.id = name;
  57437. this.name = name;
  57438. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57439. this._engine = this._scene.getEngine();
  57440. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57441. this._capacity = fullOptions.capacity;
  57442. this._activeCount = fullOptions.capacity;
  57443. this._currentActiveCount = 0;
  57444. this._scene.particleSystems.push(this);
  57445. this._updateEffectOptions = {
  57446. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57447. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57448. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57449. uniformBuffersNames: [],
  57450. samplers: ["randomSampler"],
  57451. defines: "",
  57452. fallbacks: null,
  57453. onCompiled: null,
  57454. onError: null,
  57455. indexParameters: null,
  57456. maxSimultaneousLights: 0,
  57457. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57458. };
  57459. // Random data
  57460. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57461. var d = [];
  57462. for (var i = 0; i < maxTextureSize; ++i) {
  57463. d.push(Math.random());
  57464. d.push(Math.random());
  57465. d.push(Math.random());
  57466. d.push(Math.random());
  57467. }
  57468. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57469. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57470. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57471. this._randomTextureSize = maxTextureSize;
  57472. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57473. }
  57474. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57475. /**
  57476. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57477. */
  57478. get: function () {
  57479. if (!BABYLON.Engine.LastCreatedEngine) {
  57480. return false;
  57481. }
  57482. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57483. },
  57484. enumerable: true,
  57485. configurable: true
  57486. });
  57487. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57488. /**
  57489. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57490. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57491. */
  57492. get: function () {
  57493. if (this.particleEmitterType.direction1) {
  57494. return this.particleEmitterType.direction1;
  57495. }
  57496. return BABYLON.Vector3.Zero();
  57497. },
  57498. set: function (value) {
  57499. if (this.particleEmitterType.direction1) {
  57500. this.particleEmitterType.direction1 = value;
  57501. }
  57502. },
  57503. enumerable: true,
  57504. configurable: true
  57505. });
  57506. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57507. /**
  57508. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57509. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57510. */
  57511. get: function () {
  57512. if (this.particleEmitterType.direction2) {
  57513. return this.particleEmitterType.direction2;
  57514. }
  57515. return BABYLON.Vector3.Zero();
  57516. },
  57517. set: function (value) {
  57518. if (this.particleEmitterType.direction2) {
  57519. this.particleEmitterType.direction2 = value;
  57520. }
  57521. },
  57522. enumerable: true,
  57523. configurable: true
  57524. });
  57525. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57526. /**
  57527. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  57528. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57529. */
  57530. get: function () {
  57531. if (this.particleEmitterType.minEmitBox) {
  57532. return this.particleEmitterType.minEmitBox;
  57533. }
  57534. return BABYLON.Vector3.Zero();
  57535. },
  57536. set: function (value) {
  57537. if (this.particleEmitterType.minEmitBox) {
  57538. this.particleEmitterType.minEmitBox = value;
  57539. }
  57540. },
  57541. enumerable: true,
  57542. configurable: true
  57543. });
  57544. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57545. /**
  57546. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  57547. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57548. */
  57549. get: function () {
  57550. if (this.particleEmitterType.maxEmitBox) {
  57551. return this.particleEmitterType.maxEmitBox;
  57552. }
  57553. return BABYLON.Vector3.Zero();
  57554. },
  57555. set: function (value) {
  57556. if (this.particleEmitterType.maxEmitBox) {
  57557. this.particleEmitterType.maxEmitBox = value;
  57558. }
  57559. },
  57560. enumerable: true,
  57561. configurable: true
  57562. });
  57563. /**
  57564. * Gets the maximum number of particles active at the same time.
  57565. * @returns The max number of active particles.
  57566. */
  57567. GPUParticleSystem.prototype.getCapacity = function () {
  57568. return this._capacity;
  57569. };
  57570. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57571. /**
  57572. * Gets or set the number of active particles
  57573. */
  57574. get: function () {
  57575. return this._activeCount;
  57576. },
  57577. set: function (value) {
  57578. this._activeCount = Math.min(value, this._capacity);
  57579. },
  57580. enumerable: true,
  57581. configurable: true
  57582. });
  57583. /**
  57584. * Is this system ready to be used/rendered
  57585. * @return true if the system is ready
  57586. */
  57587. GPUParticleSystem.prototype.isReady = function () {
  57588. if (!this._updateEffect) {
  57589. this._recreateUpdateEffect();
  57590. this._recreateRenderEffect();
  57591. return false;
  57592. }
  57593. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57594. return false;
  57595. }
  57596. return true;
  57597. };
  57598. /**
  57599. * Gets Wether the system has been started.
  57600. * @returns True if it has been started, otherwise false.
  57601. */
  57602. GPUParticleSystem.prototype.isStarted = function () {
  57603. return this._started;
  57604. };
  57605. /**
  57606. * Starts the particle system and begins to emit.
  57607. */
  57608. GPUParticleSystem.prototype.start = function () {
  57609. this._started = true;
  57610. this._stopped = false;
  57611. };
  57612. /**
  57613. * Stops the particle system.
  57614. */
  57615. GPUParticleSystem.prototype.stop = function () {
  57616. this._stopped = true;
  57617. };
  57618. /**
  57619. * Remove all active particles
  57620. */
  57621. GPUParticleSystem.prototype.reset = function () {
  57622. this._releaseBuffers();
  57623. this._releaseVAOs();
  57624. this._currentActiveCount = 0;
  57625. this._targetIndex = 0;
  57626. };
  57627. /**
  57628. * Returns the string "GPUParticleSystem"
  57629. * @returns a string containing the class name
  57630. */
  57631. GPUParticleSystem.prototype.getClassName = function () {
  57632. return "GPUParticleSystem";
  57633. };
  57634. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57635. var updateVertexBuffers = {};
  57636. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57637. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57638. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57639. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57640. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57641. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57642. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57643. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57644. this._engine.bindArrayBuffer(null);
  57645. return vao;
  57646. };
  57647. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57648. var renderVertexBuffers = {};
  57649. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57650. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57651. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57652. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57653. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57654. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57655. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57656. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57657. this._engine.bindArrayBuffer(null);
  57658. return vao;
  57659. };
  57660. GPUParticleSystem.prototype._initialize = function (force) {
  57661. if (force === void 0) { force = false; }
  57662. if (this._buffer0 && !force) {
  57663. return;
  57664. }
  57665. var engine = this._scene.getEngine();
  57666. var data = new Array();
  57667. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57668. // position
  57669. data.push(0.0);
  57670. data.push(0.0);
  57671. data.push(0.0);
  57672. // Age and life
  57673. data.push(0.0); // create the particle as a dead one to create a new one at start
  57674. data.push(0.0);
  57675. // Seed
  57676. data.push(Math.random());
  57677. // Size
  57678. data.push(0.0);
  57679. // color
  57680. data.push(0.0);
  57681. data.push(0.0);
  57682. data.push(0.0);
  57683. data.push(0.0);
  57684. // direction
  57685. data.push(0.0);
  57686. data.push(0.0);
  57687. data.push(0.0);
  57688. }
  57689. // Sprite data
  57690. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57691. -0.5, 0.5, 0, 1,
  57692. -0.5, -0.5, 0, 0,
  57693. 0.5, -0.5, 1, 0]);
  57694. // Buffers
  57695. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57696. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57697. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57698. // Update VAO
  57699. this._updateVAO = [];
  57700. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57701. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57702. // Render VAO
  57703. this._renderVAO = [];
  57704. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57705. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57706. // Links
  57707. this._sourceBuffer = this._buffer0;
  57708. this._targetBuffer = this._buffer1;
  57709. };
  57710. /** @hidden */
  57711. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57712. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57713. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57714. return;
  57715. }
  57716. this._updateEffectOptions.defines = defines;
  57717. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57718. };
  57719. /** @hidden */
  57720. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57721. var defines = "";
  57722. if (this._scene.clipPlane) {
  57723. defines = "\n#define CLIPPLANE";
  57724. }
  57725. if (this._renderEffect && this._renderEffect.defines === defines) {
  57726. return;
  57727. }
  57728. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57729. };
  57730. /**
  57731. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57732. */
  57733. GPUParticleSystem.prototype.animate = function () {
  57734. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57735. this._actualFrame += this._timeDelta;
  57736. if (!this._stopped) {
  57737. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57738. this.stop();
  57739. }
  57740. }
  57741. };
  57742. /**
  57743. * Renders the particle system in its current state.
  57744. * @returns the current number of particles
  57745. */
  57746. GPUParticleSystem.prototype.render = function () {
  57747. if (!this._started) {
  57748. return 0;
  57749. }
  57750. this._recreateUpdateEffect();
  57751. this._recreateRenderEffect();
  57752. if (!this.isReady()) {
  57753. return 0;
  57754. }
  57755. if (this._currentRenderId === this._scene.getRenderId()) {
  57756. return 0;
  57757. }
  57758. this._currentRenderId = this._scene.getRenderId();
  57759. // Get everything ready to render
  57760. this._initialize();
  57761. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57762. // Enable update effect
  57763. this._engine.enableEffect(this._updateEffect);
  57764. this._engine.setState(false);
  57765. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57766. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57767. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57768. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57769. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57770. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57771. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57772. this._updateEffect.setDirectColor4("color1", this.color1);
  57773. this._updateEffect.setDirectColor4("color2", this.color2);
  57774. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57775. this._updateEffect.setVector3("gravity", this.gravity);
  57776. if (this.particleEmitterType) {
  57777. this.particleEmitterType.applyToShader(this._updateEffect);
  57778. }
  57779. var emitterWM;
  57780. if (this.emitter.position) {
  57781. var emitterMesh = this.emitter;
  57782. emitterWM = emitterMesh.getWorldMatrix();
  57783. }
  57784. else {
  57785. var emitterPosition = this.emitter;
  57786. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57787. }
  57788. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57789. // Bind source VAO
  57790. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57791. // Update
  57792. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57793. this._engine.setRasterizerState(false);
  57794. this._engine.beginTransformFeedback();
  57795. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57796. this._engine.endTransformFeedback();
  57797. this._engine.setRasterizerState(true);
  57798. this._engine.bindTransformFeedbackBuffer(null);
  57799. // Enable render effect
  57800. this._engine.enableEffect(this._renderEffect);
  57801. var viewMatrix = this._scene.getViewMatrix();
  57802. this._renderEffect.setMatrix("view", viewMatrix);
  57803. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57804. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57805. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57806. if (this._scene.clipPlane) {
  57807. var clipPlane = this._scene.clipPlane;
  57808. var invView = viewMatrix.clone();
  57809. invView.invert();
  57810. this._renderEffect.setMatrix("invView", invView);
  57811. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57812. }
  57813. // Draw order
  57814. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57815. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57816. }
  57817. else {
  57818. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57819. }
  57820. if (this.forceDepthWrite) {
  57821. this._engine.setDepthWrite(true);
  57822. }
  57823. // Bind source VAO
  57824. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57825. // Render
  57826. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57827. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57828. // Switch VAOs
  57829. this._targetIndex++;
  57830. if (this._targetIndex === 2) {
  57831. this._targetIndex = 0;
  57832. }
  57833. // Switch buffers
  57834. var tmpBuffer = this._sourceBuffer;
  57835. this._sourceBuffer = this._targetBuffer;
  57836. this._targetBuffer = tmpBuffer;
  57837. return this._currentActiveCount;
  57838. };
  57839. /**
  57840. * Rebuilds the particle system
  57841. */
  57842. GPUParticleSystem.prototype.rebuild = function () {
  57843. this._initialize(true);
  57844. };
  57845. GPUParticleSystem.prototype._releaseBuffers = function () {
  57846. if (this._buffer0) {
  57847. this._buffer0.dispose();
  57848. this._buffer0 = null;
  57849. }
  57850. if (this._buffer1) {
  57851. this._buffer1.dispose();
  57852. this._buffer1 = null;
  57853. }
  57854. if (this._spriteBuffer) {
  57855. this._spriteBuffer.dispose();
  57856. this._spriteBuffer = null;
  57857. }
  57858. };
  57859. GPUParticleSystem.prototype._releaseVAOs = function () {
  57860. if (!this._updateVAO) {
  57861. return;
  57862. }
  57863. for (var index = 0; index < this._updateVAO.length; index++) {
  57864. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57865. }
  57866. this._updateVAO = [];
  57867. for (var index = 0; index < this._renderVAO.length; index++) {
  57868. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57869. }
  57870. this._renderVAO = [];
  57871. };
  57872. /**
  57873. * Disposes the particle system and free the associated resources
  57874. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57875. */
  57876. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57877. if (disposeTexture === void 0) { disposeTexture = true; }
  57878. var index = this._scene.particleSystems.indexOf(this);
  57879. if (index > -1) {
  57880. this._scene.particleSystems.splice(index, 1);
  57881. }
  57882. this._releaseBuffers();
  57883. this._releaseVAOs();
  57884. if (this._randomTexture) {
  57885. this._randomTexture.dispose();
  57886. this._randomTexture = null;
  57887. }
  57888. if (disposeTexture && this.particleTexture) {
  57889. this.particleTexture.dispose();
  57890. this.particleTexture = null;
  57891. }
  57892. // Callback
  57893. this.onDisposeObservable.notifyObservers(this);
  57894. this.onDisposeObservable.clear();
  57895. };
  57896. /**
  57897. * Clones the particle system.
  57898. * @param name The name of the cloned object
  57899. * @param newEmitter The new emitter to use
  57900. * @returns the cloned particle system
  57901. */
  57902. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57903. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57904. BABYLON.Tools.DeepCopy(this, result);
  57905. if (newEmitter === undefined) {
  57906. newEmitter = this.emitter;
  57907. }
  57908. result.emitter = newEmitter;
  57909. if (this.particleTexture) {
  57910. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57911. }
  57912. return result;
  57913. };
  57914. /**
  57915. * Serializes the particle system to a JSON object.
  57916. * @returns the JSON object
  57917. */
  57918. GPUParticleSystem.prototype.serialize = function () {
  57919. var serializationObject = {};
  57920. serializationObject.name = this.name;
  57921. serializationObject.id = this.id;
  57922. // Emitter
  57923. if (this.emitter.position) {
  57924. var emitterMesh = this.emitter;
  57925. serializationObject.emitterId = emitterMesh.id;
  57926. }
  57927. else {
  57928. var emitterPosition = this.emitter;
  57929. serializationObject.emitter = emitterPosition.asArray();
  57930. }
  57931. serializationObject.capacity = this.getCapacity();
  57932. if (this.particleTexture) {
  57933. serializationObject.textureName = this.particleTexture.name;
  57934. }
  57935. // Animations
  57936. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57937. // Particle system
  57938. serializationObject.activeParticleCount = this.activeParticleCount;
  57939. serializationObject.randomTextureSize = this._randomTextureSize;
  57940. serializationObject.minSize = this.minSize;
  57941. serializationObject.maxSize = this.maxSize;
  57942. serializationObject.minEmitPower = this.minEmitPower;
  57943. serializationObject.maxEmitPower = this.maxEmitPower;
  57944. serializationObject.minLifeTime = this.minLifeTime;
  57945. serializationObject.maxLifeTime = this.maxLifeTime;
  57946. serializationObject.emitRate = this.emitRate;
  57947. serializationObject.gravity = this.gravity.asArray();
  57948. serializationObject.color1 = this.color1.asArray();
  57949. serializationObject.color2 = this.color2.asArray();
  57950. serializationObject.colorDead = this.colorDead.asArray();
  57951. serializationObject.updateSpeed = this.updateSpeed;
  57952. serializationObject.targetStopDuration = this.targetStopDuration;
  57953. serializationObject.blendMode = this.blendMode;
  57954. // Emitter
  57955. if (this.particleEmitterType) {
  57956. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57957. }
  57958. return serializationObject;
  57959. };
  57960. /**
  57961. * Parses a JSON object to create a GPU particle system.
  57962. * @param parsedParticleSystem The JSON object to parse
  57963. * @param scene The scene to create the particle system in
  57964. * @param rootUrl The root url to use to load external dependencies like texture
  57965. * @returns the parsed GPU particle system
  57966. */
  57967. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57968. var name = parsedParticleSystem.name;
  57969. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57970. if (parsedParticleSystem.id) {
  57971. particleSystem.id = parsedParticleSystem.id;
  57972. }
  57973. // Texture
  57974. if (parsedParticleSystem.textureName) {
  57975. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57976. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57977. }
  57978. // Emitter
  57979. if (parsedParticleSystem.emitterId) {
  57980. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57981. }
  57982. else {
  57983. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57984. }
  57985. // Animations
  57986. if (parsedParticleSystem.animations) {
  57987. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57988. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57989. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57990. }
  57991. }
  57992. // Particle system
  57993. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57994. particleSystem.minSize = parsedParticleSystem.minSize;
  57995. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57996. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57997. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57998. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57999. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58000. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58001. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58002. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58003. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58004. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58005. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58006. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58007. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58008. // Emitter
  58009. if (parsedParticleSystem.particleEmitterType) {
  58010. var emitterType = void 0;
  58011. switch (parsedParticleSystem.particleEmitterType.type) {
  58012. case "SphereEmitter":
  58013. emitterType = new BABYLON.SphereParticleEmitter();
  58014. break;
  58015. case "SphereDirectedParticleEmitter":
  58016. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58017. break;
  58018. case "ConeEmitter":
  58019. emitterType = new BABYLON.ConeParticleEmitter();
  58020. break;
  58021. case "BoxEmitter":
  58022. default:
  58023. emitterType = new BABYLON.BoxParticleEmitter();
  58024. break;
  58025. }
  58026. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58027. particleSystem.particleEmitterType = emitterType;
  58028. }
  58029. return particleSystem;
  58030. };
  58031. return GPUParticleSystem;
  58032. }());
  58033. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58034. })(BABYLON || (BABYLON = {}));
  58035. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58036. var BABYLON;
  58037. (function (BABYLON) {
  58038. /**
  58039. * Represents one particle of a solid particle system.
  58040. */
  58041. var SolidParticle = /** @class */ (function () {
  58042. /**
  58043. * Creates a Solid Particle object.
  58044. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58045. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58046. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58047. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58048. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58049. * @param shapeId (integer) is the model shape identifier in the SPS.
  58050. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58051. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58052. */
  58053. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58054. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58055. /**
  58056. * particle global index
  58057. */
  58058. this.idx = 0;
  58059. /**
  58060. * The color of the particle
  58061. */
  58062. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58063. /**
  58064. * The world space position of the particle.
  58065. */
  58066. this.position = BABYLON.Vector3.Zero();
  58067. /**
  58068. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58069. */
  58070. this.rotation = BABYLON.Vector3.Zero();
  58071. /**
  58072. * The scaling of the particle.
  58073. */
  58074. this.scaling = BABYLON.Vector3.One();
  58075. /**
  58076. * The uvs of the particle.
  58077. */
  58078. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58079. /**
  58080. * The current speed of the particle.
  58081. */
  58082. this.velocity = BABYLON.Vector3.Zero();
  58083. /**
  58084. * The pivot point in the particle local space.
  58085. */
  58086. this.pivot = BABYLON.Vector3.Zero();
  58087. /**
  58088. * Must the particle be translated from its pivot point in its local space ?
  58089. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58090. * Default : false
  58091. */
  58092. this.translateFromPivot = false;
  58093. /**
  58094. * Is the particle active or not ?
  58095. */
  58096. this.alive = true;
  58097. /**
  58098. * Is the particle visible or not ?
  58099. */
  58100. this.isVisible = true;
  58101. /**
  58102. * Index of this particle in the global "positions" array (Internal use)
  58103. */
  58104. this._pos = 0;
  58105. /**
  58106. * Index of this particle in the global "indices" array (Internal use)
  58107. */
  58108. this._ind = 0;
  58109. /**
  58110. * ModelShape id of this particle
  58111. */
  58112. this.shapeId = 0;
  58113. /**
  58114. * Index of the particle in its shape id (Internal use)
  58115. */
  58116. this.idxInShape = 0;
  58117. /**
  58118. * Still set as invisible in order to skip useless computations (Internal use)
  58119. */
  58120. this._stillInvisible = false;
  58121. /**
  58122. * Last computed particle rotation matrix
  58123. */
  58124. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58125. /**
  58126. * Parent particle Id, if any.
  58127. * Default null.
  58128. */
  58129. this.parentId = null;
  58130. /**
  58131. * Internal global position in the SPS.
  58132. */
  58133. this._globalPosition = BABYLON.Vector3.Zero();
  58134. this.idx = particleIndex;
  58135. this._pos = positionIndex;
  58136. this._ind = indiceIndex;
  58137. this._model = model;
  58138. this.shapeId = shapeId;
  58139. this.idxInShape = idxInShape;
  58140. this._sps = sps;
  58141. if (modelBoundingInfo) {
  58142. this._modelBoundingInfo = modelBoundingInfo;
  58143. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58144. }
  58145. }
  58146. Object.defineProperty(SolidParticle.prototype, "scale", {
  58147. /**
  58148. * Legacy support, changed scale to scaling
  58149. */
  58150. get: function () {
  58151. return this.scaling;
  58152. },
  58153. /**
  58154. * Legacy support, changed scale to scaling
  58155. */
  58156. set: function (scale) {
  58157. this.scaling = scale;
  58158. },
  58159. enumerable: true,
  58160. configurable: true
  58161. });
  58162. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58163. /**
  58164. * Legacy support, changed quaternion to rotationQuaternion
  58165. */
  58166. get: function () {
  58167. return this.rotationQuaternion;
  58168. },
  58169. /**
  58170. * Legacy support, changed quaternion to rotationQuaternion
  58171. */
  58172. set: function (q) {
  58173. this.rotationQuaternion = q;
  58174. },
  58175. enumerable: true,
  58176. configurable: true
  58177. });
  58178. /**
  58179. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58180. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58181. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58182. * @returns true if it intersects
  58183. */
  58184. SolidParticle.prototype.intersectsMesh = function (target) {
  58185. if (!this._boundingInfo || !target._boundingInfo) {
  58186. return false;
  58187. }
  58188. if (this._sps._bSphereOnly) {
  58189. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58190. }
  58191. return this._boundingInfo.intersects(target._boundingInfo, false);
  58192. };
  58193. return SolidParticle;
  58194. }());
  58195. BABYLON.SolidParticle = SolidParticle;
  58196. /**
  58197. * Represents the shape of the model used by one particle of a solid particle system.
  58198. * SPS internal tool, don't use it manually.
  58199. */
  58200. var ModelShape = /** @class */ (function () {
  58201. /**
  58202. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  58203. * SPS internal tool, don't use it manually.
  58204. * @hidden
  58205. */
  58206. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58207. /**
  58208. * length of the shape in the model indices array (internal use)
  58209. */
  58210. this._indicesLength = 0;
  58211. this.shapeID = id;
  58212. this._shape = shape;
  58213. this._indicesLength = indicesLength;
  58214. this._shapeUV = shapeUV;
  58215. this._positionFunction = posFunction;
  58216. this._vertexFunction = vtxFunction;
  58217. }
  58218. return ModelShape;
  58219. }());
  58220. BABYLON.ModelShape = ModelShape;
  58221. /**
  58222. * Represents a Depth Sorted Particle in the solid particle system.
  58223. */
  58224. var DepthSortedParticle = /** @class */ (function () {
  58225. function DepthSortedParticle() {
  58226. /**
  58227. * Index of the particle in the "indices" array
  58228. */
  58229. this.ind = 0;
  58230. /**
  58231. * Length of the particle shape in the "indices" array
  58232. */
  58233. this.indicesLength = 0;
  58234. /**
  58235. * Squared distance from the particle to the camera
  58236. */
  58237. this.sqDistance = 0.0;
  58238. }
  58239. return DepthSortedParticle;
  58240. }());
  58241. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58242. })(BABYLON || (BABYLON = {}));
  58243. //# sourceMappingURL=babylon.solidParticle.js.map
  58244. var BABYLON;
  58245. (function (BABYLON) {
  58246. /**
  58247. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58248. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  58249. * The SPS is also a particle system. It provides some methods to manage the particles.
  58250. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58251. *
  58252. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58253. */
  58254. var SolidParticleSystem = /** @class */ (function () {
  58255. /**
  58256. * Creates a SPS (Solid Particle System) object.
  58257. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58258. * @param scene (Scene) is the scene in which the SPS is added.
  58259. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58260. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58261. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58262. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58263. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58264. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58265. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58266. */
  58267. function SolidParticleSystem(name, scene, options) {
  58268. /**
  58269. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58270. * Example : var p = SPS.particles[i];
  58271. */
  58272. this.particles = new Array();
  58273. /**
  58274. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58275. */
  58276. this.nbParticles = 0;
  58277. /**
  58278. * If the particles must ever face the camera (default false). Useful for planar particles.
  58279. */
  58280. this.billboard = false;
  58281. /**
  58282. * Recompute normals when adding a shape
  58283. */
  58284. this.recomputeNormals = true;
  58285. /**
  58286. * This a counter ofr your own usage. It's not set by any SPS functions.
  58287. */
  58288. this.counter = 0;
  58289. /**
  58290. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58291. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58292. */
  58293. this.vars = {};
  58294. /**
  58295. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58296. */
  58297. this._bSphereOnly = false;
  58298. /**
  58299. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58300. */
  58301. this._bSphereRadiusFactor = 1.0;
  58302. this._positions = new Array();
  58303. this._indices = new Array();
  58304. this._normals = new Array();
  58305. this._colors = new Array();
  58306. this._uvs = new Array();
  58307. this._index = 0; // indices index
  58308. this._updatable = true;
  58309. this._pickable = false;
  58310. this._isVisibilityBoxLocked = false;
  58311. this._alwaysVisible = false;
  58312. this._depthSort = false;
  58313. this._shapeCounter = 0;
  58314. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58315. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58316. this._computeParticleColor = true;
  58317. this._computeParticleTexture = true;
  58318. this._computeParticleRotation = true;
  58319. this._computeParticleVertex = false;
  58320. this._computeBoundingBox = false;
  58321. this._depthSortParticles = true;
  58322. this._cam_axisZ = BABYLON.Vector3.Zero();
  58323. this._cam_axisY = BABYLON.Vector3.Zero();
  58324. this._cam_axisX = BABYLON.Vector3.Zero();
  58325. this._axisZ = BABYLON.Axis.Z;
  58326. this._camDir = BABYLON.Vector3.Zero();
  58327. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58328. this._rotMatrix = new BABYLON.Matrix();
  58329. this._invertMatrix = new BABYLON.Matrix();
  58330. this._rotated = BABYLON.Vector3.Zero();
  58331. this._quaternion = new BABYLON.Quaternion();
  58332. this._vertex = BABYLON.Vector3.Zero();
  58333. this._normal = BABYLON.Vector3.Zero();
  58334. this._yaw = 0.0;
  58335. this._pitch = 0.0;
  58336. this._roll = 0.0;
  58337. this._halfroll = 0.0;
  58338. this._halfpitch = 0.0;
  58339. this._halfyaw = 0.0;
  58340. this._sinRoll = 0.0;
  58341. this._cosRoll = 0.0;
  58342. this._sinPitch = 0.0;
  58343. this._cosPitch = 0.0;
  58344. this._sinYaw = 0.0;
  58345. this._cosYaw = 0.0;
  58346. this._mustUnrotateFixedNormals = false;
  58347. this._minimum = BABYLON.Vector3.Zero();
  58348. this._maximum = BABYLON.Vector3.Zero();
  58349. this._minBbox = BABYLON.Vector3.Zero();
  58350. this._maxBbox = BABYLON.Vector3.Zero();
  58351. this._particlesIntersect = false;
  58352. this._depthSortFunction = function (p1, p2) {
  58353. return (p2.sqDistance - p1.sqDistance);
  58354. };
  58355. this._needs32Bits = false;
  58356. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58357. this._scaledPivot = BABYLON.Vector3.Zero();
  58358. this._particleHasParent = false;
  58359. this.name = name;
  58360. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58361. this._camera = scene.activeCamera;
  58362. this._pickable = options ? options.isPickable : false;
  58363. this._depthSort = options ? options.enableDepthSort : false;
  58364. this._particlesIntersect = options ? options.particleIntersection : false;
  58365. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58366. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58367. if (options && options.updatable) {
  58368. this._updatable = options.updatable;
  58369. }
  58370. else {
  58371. this._updatable = true;
  58372. }
  58373. if (this._pickable) {
  58374. this.pickedParticles = [];
  58375. }
  58376. if (this._depthSort) {
  58377. this.depthSortedParticles = [];
  58378. }
  58379. }
  58380. /**
  58381. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58382. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58383. * @returns the created mesh
  58384. */
  58385. SolidParticleSystem.prototype.buildMesh = function () {
  58386. if (this.nbParticles === 0) {
  58387. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58388. this.addShape(triangle, 1);
  58389. triangle.dispose();
  58390. }
  58391. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58392. this._positions32 = new Float32Array(this._positions);
  58393. this._uvs32 = new Float32Array(this._uvs);
  58394. this._colors32 = new Float32Array(this._colors);
  58395. if (this.recomputeNormals) {
  58396. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58397. }
  58398. this._normals32 = new Float32Array(this._normals);
  58399. this._fixedNormal32 = new Float32Array(this._normals);
  58400. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58401. this._unrotateFixedNormals();
  58402. }
  58403. var vertexData = new BABYLON.VertexData();
  58404. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58405. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58406. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58407. if (this._uvs32.length > 0) {
  58408. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58409. }
  58410. if (this._colors32.length > 0) {
  58411. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58412. }
  58413. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58414. vertexData.applyToMesh(mesh, this._updatable);
  58415. this.mesh = mesh;
  58416. this.mesh.isPickable = this._pickable;
  58417. // free memory
  58418. if (!this._depthSort) {
  58419. this._indices = null;
  58420. }
  58421. this._positions = null;
  58422. this._normals = null;
  58423. this._uvs = null;
  58424. this._colors = null;
  58425. if (!this._updatable) {
  58426. this.particles.length = 0;
  58427. }
  58428. return mesh;
  58429. };
  58430. /**
  58431. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58432. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58433. * Thus the particles generated from `digest()` have their property `position` set yet.
  58434. * @param mesh ( Mesh ) is the mesh to be digested
  58435. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  58436. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58437. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58438. * @returns the current SPS
  58439. */
  58440. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58441. var size = (options && options.facetNb) || 1;
  58442. var number = (options && options.number) || 0;
  58443. var delta = (options && options.delta) || 0;
  58444. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58445. var meshInd = mesh.getIndices();
  58446. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58447. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58448. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58449. var f = 0; // facet counter
  58450. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58451. // compute size from number
  58452. if (number) {
  58453. number = (number > totalFacets) ? totalFacets : number;
  58454. size = Math.round(totalFacets / number);
  58455. delta = 0;
  58456. }
  58457. else {
  58458. size = (size > totalFacets) ? totalFacets : size;
  58459. }
  58460. var facetPos = []; // submesh positions
  58461. var facetInd = []; // submesh indices
  58462. var facetUV = []; // submesh UV
  58463. var facetCol = []; // submesh colors
  58464. var barycenter = BABYLON.Vector3.Zero();
  58465. var sizeO = size;
  58466. while (f < totalFacets) {
  58467. size = sizeO + Math.floor((1 + delta) * Math.random());
  58468. if (f > totalFacets - size) {
  58469. size = totalFacets - f;
  58470. }
  58471. // reset temp arrays
  58472. facetPos.length = 0;
  58473. facetInd.length = 0;
  58474. facetUV.length = 0;
  58475. facetCol.length = 0;
  58476. // iterate over "size" facets
  58477. var fi = 0;
  58478. for (var j = f * 3; j < (f + size) * 3; j++) {
  58479. facetInd.push(fi);
  58480. var i = meshInd[j];
  58481. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58482. if (meshUV) {
  58483. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58484. }
  58485. if (meshCol) {
  58486. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58487. }
  58488. fi++;
  58489. }
  58490. // create a model shape for each single particle
  58491. var idx = this.nbParticles;
  58492. var shape = this._posToShape(facetPos);
  58493. var shapeUV = this._uvsToShapeUV(facetUV);
  58494. // compute the barycenter of the shape
  58495. var v;
  58496. for (v = 0; v < shape.length; v++) {
  58497. barycenter.addInPlace(shape[v]);
  58498. }
  58499. barycenter.scaleInPlace(1 / shape.length);
  58500. // shift the shape from its barycenter to the origin
  58501. for (v = 0; v < shape.length; v++) {
  58502. shape[v].subtractInPlace(barycenter);
  58503. }
  58504. var bInfo;
  58505. if (this._particlesIntersect) {
  58506. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58507. }
  58508. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58509. // add the particle in the SPS
  58510. var currentPos = this._positions.length;
  58511. var currentInd = this._indices.length;
  58512. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58513. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58514. // initialize the particle position
  58515. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58516. this._index += shape.length;
  58517. idx++;
  58518. this.nbParticles++;
  58519. this._shapeCounter++;
  58520. f += size;
  58521. }
  58522. return this;
  58523. };
  58524. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58525. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58526. var index = 0;
  58527. var idx = 0;
  58528. for (var p = 0; p < this.particles.length; p++) {
  58529. this._particle = this.particles[p];
  58530. this._shape = this._particle._model._shape;
  58531. if (this._particle.rotationQuaternion) {
  58532. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58533. }
  58534. else {
  58535. this._yaw = this._particle.rotation.y;
  58536. this._pitch = this._particle.rotation.x;
  58537. this._roll = this._particle.rotation.z;
  58538. this._quaternionRotationYPR();
  58539. }
  58540. this._quaternionToRotationMatrix();
  58541. this._rotMatrix.invertToRef(this._invertMatrix);
  58542. for (var pt = 0; pt < this._shape.length; pt++) {
  58543. idx = index + pt * 3;
  58544. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58545. this._fixedNormal32[idx] = this._normal.x;
  58546. this._fixedNormal32[idx + 1] = this._normal.y;
  58547. this._fixedNormal32[idx + 2] = this._normal.z;
  58548. }
  58549. index = idx + 3;
  58550. }
  58551. };
  58552. //reset copy
  58553. SolidParticleSystem.prototype._resetCopy = function () {
  58554. this._copy.position.x = 0;
  58555. this._copy.position.y = 0;
  58556. this._copy.position.z = 0;
  58557. this._copy.rotation.x = 0;
  58558. this._copy.rotation.y = 0;
  58559. this._copy.rotation.z = 0;
  58560. this._copy.rotationQuaternion = null;
  58561. this._copy.scaling.x = 1.0;
  58562. this._copy.scaling.y = 1.0;
  58563. this._copy.scaling.z = 1.0;
  58564. this._copy.uvs.x = 0;
  58565. this._copy.uvs.y = 0;
  58566. this._copy.uvs.z = 1.0;
  58567. this._copy.uvs.w = 1.0;
  58568. this._copy.color = null;
  58569. this._copy.translateFromPivot = false;
  58570. };
  58571. // _meshBuilder : inserts the shape model in the global SPS mesh
  58572. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58573. var i;
  58574. var u = 0;
  58575. var c = 0;
  58576. var n = 0;
  58577. this._resetCopy();
  58578. if (options && options.positionFunction) { // call to custom positionFunction
  58579. options.positionFunction(this._copy, idx, idxInShape);
  58580. this._mustUnrotateFixedNormals = true;
  58581. }
  58582. if (this._copy.rotationQuaternion) {
  58583. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58584. }
  58585. else {
  58586. this._yaw = this._copy.rotation.y;
  58587. this._pitch = this._copy.rotation.x;
  58588. this._roll = this._copy.rotation.z;
  58589. this._quaternionRotationYPR();
  58590. }
  58591. this._quaternionToRotationMatrix();
  58592. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58593. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58594. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58595. if (this._copy.translateFromPivot) {
  58596. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58597. }
  58598. else {
  58599. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58600. }
  58601. for (i = 0; i < shape.length; i++) {
  58602. this._vertex.x = shape[i].x;
  58603. this._vertex.y = shape[i].y;
  58604. this._vertex.z = shape[i].z;
  58605. if (options && options.vertexFunction) {
  58606. options.vertexFunction(this._copy, this._vertex, i);
  58607. }
  58608. this._vertex.x *= this._copy.scaling.x;
  58609. this._vertex.y *= this._copy.scaling.y;
  58610. this._vertex.z *= this._copy.scaling.z;
  58611. this._vertex.x -= this._scaledPivot.x;
  58612. this._vertex.y -= this._scaledPivot.y;
  58613. this._vertex.z -= this._scaledPivot.z;
  58614. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58615. this._rotated.addInPlace(this._pivotBackTranslation);
  58616. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58617. if (meshUV) {
  58618. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  58619. u += 2;
  58620. }
  58621. if (this._copy.color) {
  58622. this._color = this._copy.color;
  58623. }
  58624. else if (meshCol && meshCol[c] !== undefined) {
  58625. this._color.r = meshCol[c];
  58626. this._color.g = meshCol[c + 1];
  58627. this._color.b = meshCol[c + 2];
  58628. this._color.a = meshCol[c + 3];
  58629. }
  58630. else {
  58631. this._color.r = 1.0;
  58632. this._color.g = 1.0;
  58633. this._color.b = 1.0;
  58634. this._color.a = 1.0;
  58635. }
  58636. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58637. c += 4;
  58638. if (!this.recomputeNormals && meshNor) {
  58639. this._normal.x = meshNor[n];
  58640. this._normal.y = meshNor[n + 1];
  58641. this._normal.z = meshNor[n + 2];
  58642. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58643. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58644. n += 3;
  58645. }
  58646. }
  58647. for (i = 0; i < meshInd.length; i++) {
  58648. var current_ind = p + meshInd[i];
  58649. indices.push(current_ind);
  58650. if (current_ind > 65535) {
  58651. this._needs32Bits = true;
  58652. }
  58653. }
  58654. if (this._pickable) {
  58655. var nbfaces = meshInd.length / 3;
  58656. for (i = 0; i < nbfaces; i++) {
  58657. this.pickedParticles.push({ idx: idx, faceId: i });
  58658. }
  58659. }
  58660. if (this._depthSort) {
  58661. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58662. }
  58663. return this._copy;
  58664. };
  58665. // returns a shape array from positions array
  58666. SolidParticleSystem.prototype._posToShape = function (positions) {
  58667. var shape = [];
  58668. for (var i = 0; i < positions.length; i += 3) {
  58669. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58670. }
  58671. return shape;
  58672. };
  58673. // returns a shapeUV array from a Vector4 uvs
  58674. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58675. var shapeUV = [];
  58676. if (uvs) {
  58677. for (var i = 0; i < uvs.length; i++)
  58678. shapeUV.push(uvs[i]);
  58679. }
  58680. return shapeUV;
  58681. };
  58682. // adds a new particle object in the particles array
  58683. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58684. if (bInfo === void 0) { bInfo = null; }
  58685. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58686. this.particles.push(sp);
  58687. return sp;
  58688. };
  58689. /**
  58690. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58691. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58692. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58693. * @param nb (positive integer) the number of particles to be created from this model
  58694. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58695. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58696. * @returns the number of shapes in the system
  58697. */
  58698. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58699. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58700. var meshInd = mesh.getIndices();
  58701. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58702. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58703. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58704. var bbInfo;
  58705. if (this._particlesIntersect) {
  58706. bbInfo = mesh.getBoundingInfo();
  58707. }
  58708. var shape = this._posToShape(meshPos);
  58709. var shapeUV = this._uvsToShapeUV(meshUV);
  58710. var posfunc = options ? options.positionFunction : null;
  58711. var vtxfunc = options ? options.vertexFunction : null;
  58712. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58713. // particles
  58714. var sp;
  58715. var currentCopy;
  58716. var idx = this.nbParticles;
  58717. for (var i = 0; i < nb; i++) {
  58718. var currentPos = this._positions.length;
  58719. var currentInd = this._indices.length;
  58720. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58721. if (this._updatable) {
  58722. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58723. sp.position.copyFrom(currentCopy.position);
  58724. sp.rotation.copyFrom(currentCopy.rotation);
  58725. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58726. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58727. }
  58728. if (currentCopy.color && sp.color) {
  58729. sp.color.copyFrom(currentCopy.color);
  58730. }
  58731. sp.scaling.copyFrom(currentCopy.scaling);
  58732. sp.uvs.copyFrom(currentCopy.uvs);
  58733. }
  58734. this._index += shape.length;
  58735. idx++;
  58736. }
  58737. this.nbParticles += nb;
  58738. this._shapeCounter++;
  58739. return this._shapeCounter - 1;
  58740. };
  58741. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58742. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58743. this._resetCopy();
  58744. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58745. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58746. }
  58747. if (this._copy.rotationQuaternion) {
  58748. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58749. }
  58750. else {
  58751. this._yaw = this._copy.rotation.y;
  58752. this._pitch = this._copy.rotation.x;
  58753. this._roll = this._copy.rotation.z;
  58754. this._quaternionRotationYPR();
  58755. }
  58756. this._quaternionToRotationMatrix();
  58757. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58758. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58759. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58760. if (this._copy.translateFromPivot) {
  58761. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58762. }
  58763. else {
  58764. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58765. }
  58766. this._shape = particle._model._shape;
  58767. for (var pt = 0; pt < this._shape.length; pt++) {
  58768. this._vertex.x = this._shape[pt].x;
  58769. this._vertex.y = this._shape[pt].y;
  58770. this._vertex.z = this._shape[pt].z;
  58771. if (particle._model._vertexFunction) {
  58772. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58773. }
  58774. this._vertex.x *= this._copy.scaling.x;
  58775. this._vertex.y *= this._copy.scaling.y;
  58776. this._vertex.z *= this._copy.scaling.z;
  58777. this._vertex.x -= this._scaledPivot.x;
  58778. this._vertex.y -= this._scaledPivot.y;
  58779. this._vertex.z -= this._scaledPivot.z;
  58780. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58781. this._rotated.addInPlace(this._pivotBackTranslation);
  58782. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58783. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58784. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58785. }
  58786. particle.position.x = 0.0;
  58787. particle.position.y = 0.0;
  58788. particle.position.z = 0.0;
  58789. particle.rotation.x = 0.0;
  58790. particle.rotation.y = 0.0;
  58791. particle.rotation.z = 0.0;
  58792. particle.rotationQuaternion = null;
  58793. particle.scaling.x = 1.0;
  58794. particle.scaling.y = 1.0;
  58795. particle.scaling.z = 1.0;
  58796. particle.uvs.x = 0.0;
  58797. particle.uvs.y = 0.0;
  58798. particle.uvs.z = 1.0;
  58799. particle.uvs.w = 1.0;
  58800. particle.pivot.x = 0.0;
  58801. particle.pivot.y = 0.0;
  58802. particle.pivot.z = 0.0;
  58803. particle.translateFromPivot = false;
  58804. particle.parentId = null;
  58805. };
  58806. /**
  58807. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58808. * @returns the SPS.
  58809. */
  58810. SolidParticleSystem.prototype.rebuildMesh = function () {
  58811. for (var p = 0; p < this.particles.length; p++) {
  58812. this._rebuildParticle(this.particles[p]);
  58813. }
  58814. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58815. return this;
  58816. };
  58817. /**
  58818. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58819. * This method calls `updateParticle()` for each particle of the SPS.
  58820. * For an animated SPS, it is usually called within the render loop.
  58821. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58822. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58823. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58824. * @returns the SPS.
  58825. */
  58826. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58827. if (start === void 0) { start = 0; }
  58828. if (end === void 0) { end = this.nbParticles - 1; }
  58829. if (update === void 0) { update = true; }
  58830. if (!this._updatable) {
  58831. return this;
  58832. }
  58833. // custom beforeUpdate
  58834. this.beforeUpdateParticles(start, end, update);
  58835. this._cam_axisX.x = 1.0;
  58836. this._cam_axisX.y = 0.0;
  58837. this._cam_axisX.z = 0.0;
  58838. this._cam_axisY.x = 0.0;
  58839. this._cam_axisY.y = 1.0;
  58840. this._cam_axisY.z = 0.0;
  58841. this._cam_axisZ.x = 0.0;
  58842. this._cam_axisZ.y = 0.0;
  58843. this._cam_axisZ.z = 1.0;
  58844. // cases when the World Matrix is to be computed first
  58845. if (this.billboard || this._depthSort) {
  58846. this.mesh.computeWorldMatrix(true);
  58847. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58848. }
  58849. // if the particles will always face the camera
  58850. if (this.billboard) {
  58851. // compute the camera position and un-rotate it by the current mesh rotation
  58852. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58853. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58854. this._cam_axisZ.normalize();
  58855. // same for camera up vector extracted from the cam view matrix
  58856. var view = this._camera.getViewMatrix(true);
  58857. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58858. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58859. this._cam_axisY.normalize();
  58860. this._cam_axisX.normalize();
  58861. }
  58862. // if depthSort, compute the camera global position in the mesh local system
  58863. if (this._depthSort) {
  58864. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58865. }
  58866. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58867. var idx = 0; // current position index in the global array positions32
  58868. var index = 0; // position start index in the global array positions32 of the current particle
  58869. var colidx = 0; // current color index in the global array colors32
  58870. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58871. var uvidx = 0; // current uv index in the global array uvs32
  58872. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58873. var pt = 0; // current index in the particle model shape
  58874. if (this.mesh.isFacetDataEnabled) {
  58875. this._computeBoundingBox = true;
  58876. }
  58877. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58878. if (this._computeBoundingBox) {
  58879. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58880. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58881. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58882. }
  58883. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58884. if (this.mesh._boundingInfo) {
  58885. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58886. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58887. }
  58888. }
  58889. }
  58890. // particle loop
  58891. index = this.particles[start]._pos;
  58892. var vpos = (index / 3) | 0;
  58893. colorIndex = vpos * 4;
  58894. uvIndex = vpos * 2;
  58895. for (var p = start; p <= end; p++) {
  58896. this._particle = this.particles[p];
  58897. this._shape = this._particle._model._shape;
  58898. this._shapeUV = this._particle._model._shapeUV;
  58899. // call to custom user function to update the particle properties
  58900. this.updateParticle(this._particle);
  58901. // camera-particle distance for depth sorting
  58902. if (this._depthSort && this._depthSortParticles) {
  58903. var dsp = this.depthSortedParticles[p];
  58904. dsp.ind = this._particle._ind;
  58905. dsp.indicesLength = this._particle._model._indicesLength;
  58906. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58907. }
  58908. // skip the computations for inactive or already invisible particles
  58909. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58910. // increment indexes for the next particle
  58911. pt = this._shape.length;
  58912. index += pt * 3;
  58913. colorIndex += pt * 4;
  58914. uvIndex += pt * 2;
  58915. continue;
  58916. }
  58917. if (this._particle.isVisible) {
  58918. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58919. this._particleHasParent = (this._particle.parentId !== null);
  58920. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58921. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58922. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58923. // particle rotation matrix
  58924. if (this.billboard) {
  58925. this._particle.rotation.x = 0.0;
  58926. this._particle.rotation.y = 0.0;
  58927. }
  58928. if (this._computeParticleRotation || this.billboard) {
  58929. if (this._particle.rotationQuaternion) {
  58930. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58931. }
  58932. else {
  58933. this._yaw = this._particle.rotation.y;
  58934. this._pitch = this._particle.rotation.x;
  58935. this._roll = this._particle.rotation.z;
  58936. this._quaternionRotationYPR();
  58937. }
  58938. this._quaternionToRotationMatrix();
  58939. }
  58940. if (this._particleHasParent) {
  58941. this._parent = this.particles[this._particle.parentId];
  58942. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  58943. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  58944. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  58945. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58946. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58947. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58948. if (this._computeParticleRotation || this.billboard) {
  58949. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  58950. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  58951. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  58952. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  58953. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  58954. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  58955. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  58956. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  58957. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  58958. }
  58959. }
  58960. else {
  58961. this._particle._globalPosition.x = this._particle.position.x;
  58962. this._particle._globalPosition.y = this._particle.position.y;
  58963. this._particle._globalPosition.z = this._particle.position.z;
  58964. if (this._computeParticleRotation || this.billboard) {
  58965. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58966. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58967. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58968. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58969. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58970. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58971. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58972. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58973. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58974. }
  58975. }
  58976. if (this._particle.translateFromPivot) {
  58977. this._pivotBackTranslation.x = 0.0;
  58978. this._pivotBackTranslation.y = 0.0;
  58979. this._pivotBackTranslation.z = 0.0;
  58980. }
  58981. else {
  58982. this._pivotBackTranslation.x = this._scaledPivot.x;
  58983. this._pivotBackTranslation.y = this._scaledPivot.y;
  58984. this._pivotBackTranslation.z = this._scaledPivot.z;
  58985. }
  58986. // particle vertex loop
  58987. for (pt = 0; pt < this._shape.length; pt++) {
  58988. idx = index + pt * 3;
  58989. colidx = colorIndex + pt * 4;
  58990. uvidx = uvIndex + pt * 2;
  58991. this._vertex.x = this._shape[pt].x;
  58992. this._vertex.y = this._shape[pt].y;
  58993. this._vertex.z = this._shape[pt].z;
  58994. if (this._computeParticleVertex) {
  58995. this.updateParticleVertex(this._particle, this._vertex, pt);
  58996. }
  58997. // positions
  58998. this._vertex.x *= this._particle.scaling.x;
  58999. this._vertex.y *= this._particle.scaling.y;
  59000. this._vertex.z *= this._particle.scaling.z;
  59001. this._vertex.x -= this._scaledPivot.x;
  59002. this._vertex.y -= this._scaledPivot.y;
  59003. this._vertex.z -= this._scaledPivot.z;
  59004. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59005. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59006. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59007. this._rotated.x += this._pivotBackTranslation.x;
  59008. this._rotated.y += this._pivotBackTranslation.y;
  59009. this._rotated.z += this._pivotBackTranslation.z;
  59010. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59011. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  59012. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  59013. if (this._computeBoundingBox) {
  59014. if (this._positions32[idx] < this._minimum.x) {
  59015. this._minimum.x = this._positions32[idx];
  59016. }
  59017. if (this._positions32[idx] > this._maximum.x) {
  59018. this._maximum.x = this._positions32[idx];
  59019. }
  59020. if (this._positions32[idx + 1] < this._minimum.y) {
  59021. this._minimum.y = this._positions32[idx + 1];
  59022. }
  59023. if (this._positions32[idx + 1] > this._maximum.y) {
  59024. this._maximum.y = this._positions32[idx + 1];
  59025. }
  59026. if (this._positions32[idx + 2] < this._minimum.z) {
  59027. this._minimum.z = this._positions32[idx + 2];
  59028. }
  59029. if (this._positions32[idx + 2] > this._maximum.z) {
  59030. this._maximum.z = this._positions32[idx + 2];
  59031. }
  59032. }
  59033. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59034. if (!this._computeParticleVertex) {
  59035. this._normal.x = this._fixedNormal32[idx];
  59036. this._normal.y = this._fixedNormal32[idx + 1];
  59037. this._normal.z = this._fixedNormal32[idx + 2];
  59038. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59039. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59040. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59041. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59042. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  59043. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  59044. }
  59045. if (this._computeParticleColor && this._particle.color) {
  59046. this._colors32[colidx] = this._particle.color.r;
  59047. this._colors32[colidx + 1] = this._particle.color.g;
  59048. this._colors32[colidx + 2] = this._particle.color.b;
  59049. this._colors32[colidx + 3] = this._particle.color.a;
  59050. }
  59051. if (this._computeParticleTexture) {
  59052. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59053. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59054. }
  59055. }
  59056. }
  59057. // particle just set invisible : scaled to zero and positioned at the origin
  59058. else {
  59059. this._particle._stillInvisible = true; // mark the particle as invisible
  59060. for (pt = 0; pt < this._shape.length; pt++) {
  59061. idx = index + pt * 3;
  59062. colidx = colorIndex + pt * 4;
  59063. uvidx = uvIndex + pt * 2;
  59064. this._positions32[idx] = 0.0;
  59065. this._positions32[idx + 1] = 0.0;
  59066. this._positions32[idx + 2] = 0.0;
  59067. this._normals32[idx] = 0.0;
  59068. this._normals32[idx + 1] = 0.0;
  59069. this._normals32[idx + 2] = 0.0;
  59070. if (this._computeParticleColor && this._particle.color) {
  59071. this._colors32[colidx] = this._particle.color.r;
  59072. this._colors32[colidx + 1] = this._particle.color.g;
  59073. this._colors32[colidx + 2] = this._particle.color.b;
  59074. this._colors32[colidx + 3] = this._particle.color.a;
  59075. }
  59076. if (this._computeParticleTexture) {
  59077. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59078. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59079. }
  59080. }
  59081. }
  59082. // if the particle intersections must be computed : update the bbInfo
  59083. if (this._particlesIntersect) {
  59084. var bInfo = this._particle._boundingInfo;
  59085. var bBox = bInfo.boundingBox;
  59086. var bSphere = bInfo.boundingSphere;
  59087. if (!this._bSphereOnly) {
  59088. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59089. for (var b = 0; b < bBox.vectors.length; b++) {
  59090. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59091. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59092. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59093. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59094. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59095. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59096. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59097. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  59098. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  59099. }
  59100. bBox._update(this.mesh._worldMatrix);
  59101. }
  59102. // place and scale the particle bouding sphere in the SPS local system, then update it
  59103. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59104. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59105. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59106. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59107. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59108. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59109. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59110. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59111. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59112. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  59113. bSphere._update(this.mesh._worldMatrix);
  59114. }
  59115. // increment indexes for the next particle
  59116. index = idx + 3;
  59117. colorIndex = colidx + 4;
  59118. uvIndex = uvidx + 2;
  59119. }
  59120. // if the VBO must be updated
  59121. if (update) {
  59122. if (this._computeParticleColor) {
  59123. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59124. }
  59125. if (this._computeParticleTexture) {
  59126. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59127. }
  59128. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59129. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59130. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59131. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59132. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59133. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59134. for (var i = 0; i < this._normals32.length; i++) {
  59135. this._fixedNormal32[i] = this._normals32[i];
  59136. }
  59137. }
  59138. if (!this.mesh.areNormalsFrozen) {
  59139. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59140. }
  59141. }
  59142. if (this._depthSort && this._depthSortParticles) {
  59143. this.depthSortedParticles.sort(this._depthSortFunction);
  59144. var dspl = this.depthSortedParticles.length;
  59145. var sorted = 0;
  59146. var lind = 0;
  59147. var sind = 0;
  59148. var sid = 0;
  59149. for (sorted = 0; sorted < dspl; sorted++) {
  59150. lind = this.depthSortedParticles[sorted].indicesLength;
  59151. sind = this.depthSortedParticles[sorted].ind;
  59152. for (var i = 0; i < lind; i++) {
  59153. this._indices32[sid] = this._indices[sind + i];
  59154. sid++;
  59155. }
  59156. }
  59157. this.mesh.updateIndices(this._indices32);
  59158. }
  59159. }
  59160. if (this._computeBoundingBox) {
  59161. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59162. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59163. }
  59164. this.afterUpdateParticles(start, end, update);
  59165. return this;
  59166. };
  59167. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59168. this._halfroll = this._roll * 0.5;
  59169. this._halfpitch = this._pitch * 0.5;
  59170. this._halfyaw = this._yaw * 0.5;
  59171. this._sinRoll = Math.sin(this._halfroll);
  59172. this._cosRoll = Math.cos(this._halfroll);
  59173. this._sinPitch = Math.sin(this._halfpitch);
  59174. this._cosPitch = Math.cos(this._halfpitch);
  59175. this._sinYaw = Math.sin(this._halfyaw);
  59176. this._cosYaw = Math.cos(this._halfyaw);
  59177. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59178. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59179. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59180. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59181. };
  59182. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59183. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59184. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59185. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59186. this._rotMatrix.m[3] = 0;
  59187. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59188. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59189. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59190. this._rotMatrix.m[7] = 0;
  59191. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59192. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59193. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59194. this._rotMatrix.m[11] = 0;
  59195. this._rotMatrix.m[12] = 0;
  59196. this._rotMatrix.m[13] = 0;
  59197. this._rotMatrix.m[14] = 0;
  59198. this._rotMatrix.m[15] = 1.0;
  59199. };
  59200. /**
  59201. * Disposes the SPS.
  59202. */
  59203. SolidParticleSystem.prototype.dispose = function () {
  59204. this.mesh.dispose();
  59205. this.vars = null;
  59206. // drop references to internal big arrays for the GC
  59207. this._positions = null;
  59208. this._indices = null;
  59209. this._normals = null;
  59210. this._uvs = null;
  59211. this._colors = null;
  59212. this._indices32 = null;
  59213. this._positions32 = null;
  59214. this._normals32 = null;
  59215. this._fixedNormal32 = null;
  59216. this._uvs32 = null;
  59217. this._colors32 = null;
  59218. this.pickedParticles = null;
  59219. };
  59220. /**
  59221. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59222. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59223. * @returns the SPS.
  59224. */
  59225. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59226. if (!this._isVisibilityBoxLocked) {
  59227. this.mesh.refreshBoundingInfo();
  59228. }
  59229. return this;
  59230. };
  59231. /**
  59232. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59233. * @param size the size (float) of the visibility box
  59234. * note : this doesn't lock the SPS mesh bounding box.
  59235. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59236. */
  59237. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59238. var vis = size / 2;
  59239. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59240. };
  59241. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59242. /**
  59243. * Gets whether the SPS as always visible or not
  59244. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59245. */
  59246. get: function () {
  59247. return this._alwaysVisible;
  59248. },
  59249. /**
  59250. * Sets the SPS as always visible or not
  59251. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59252. */
  59253. set: function (val) {
  59254. this._alwaysVisible = val;
  59255. this.mesh.alwaysSelectAsActiveMesh = val;
  59256. },
  59257. enumerable: true,
  59258. configurable: true
  59259. });
  59260. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59261. /**
  59262. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59263. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59264. */
  59265. get: function () {
  59266. return this._isVisibilityBoxLocked;
  59267. },
  59268. /**
  59269. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59270. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59271. */
  59272. set: function (val) {
  59273. this._isVisibilityBoxLocked = val;
  59274. var boundingInfo = this.mesh.getBoundingInfo();
  59275. boundingInfo.isLocked = val;
  59276. },
  59277. enumerable: true,
  59278. configurable: true
  59279. });
  59280. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59281. /**
  59282. * Gets if `setParticles()` computes the particle rotations or not.
  59283. * Default value : true. The SPS is faster when it's set to false.
  59284. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59285. */
  59286. get: function () {
  59287. return this._computeParticleRotation;
  59288. },
  59289. /**
  59290. * Tells to `setParticles()` to compute the particle rotations or not.
  59291. * Default value : true. The SPS is faster when it's set to false.
  59292. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59293. */
  59294. set: function (val) {
  59295. this._computeParticleRotation = val;
  59296. },
  59297. enumerable: true,
  59298. configurable: true
  59299. });
  59300. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59301. /**
  59302. * Gets if `setParticles()` computes the particle colors or not.
  59303. * Default value : true. The SPS is faster when it's set to false.
  59304. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59305. */
  59306. get: function () {
  59307. return this._computeParticleColor;
  59308. },
  59309. /**
  59310. * Tells to `setParticles()` to compute the particle colors or not.
  59311. * Default value : true. The SPS is faster when it's set to false.
  59312. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59313. */
  59314. set: function (val) {
  59315. this._computeParticleColor = val;
  59316. },
  59317. enumerable: true,
  59318. configurable: true
  59319. });
  59320. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59321. /**
  59322. * Gets if `setParticles()` computes the particle textures or not.
  59323. * Default value : true. The SPS is faster when it's set to false.
  59324. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59325. */
  59326. get: function () {
  59327. return this._computeParticleTexture;
  59328. },
  59329. set: function (val) {
  59330. this._computeParticleTexture = val;
  59331. },
  59332. enumerable: true,
  59333. configurable: true
  59334. });
  59335. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59336. /**
  59337. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59338. * Default value : false. The SPS is faster when it's set to false.
  59339. * Note : the particle custom vertex positions aren't stored values.
  59340. */
  59341. get: function () {
  59342. return this._computeParticleVertex;
  59343. },
  59344. /**
  59345. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59346. * Default value : false. The SPS is faster when it's set to false.
  59347. * Note : the particle custom vertex positions aren't stored values.
  59348. */
  59349. set: function (val) {
  59350. this._computeParticleVertex = val;
  59351. },
  59352. enumerable: true,
  59353. configurable: true
  59354. });
  59355. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59356. /**
  59357. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59358. */
  59359. get: function () {
  59360. return this._computeBoundingBox;
  59361. },
  59362. /**
  59363. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59364. */
  59365. set: function (val) {
  59366. this._computeBoundingBox = val;
  59367. },
  59368. enumerable: true,
  59369. configurable: true
  59370. });
  59371. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59372. /**
  59373. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59374. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59375. * Default : `true`
  59376. */
  59377. get: function () {
  59378. return this._depthSortParticles;
  59379. },
  59380. /**
  59381. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59382. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59383. * Default : `true`
  59384. */
  59385. set: function (val) {
  59386. this._depthSortParticles = val;
  59387. },
  59388. enumerable: true,
  59389. configurable: true
  59390. });
  59391. // =======================================================================
  59392. // Particle behavior logic
  59393. // these following methods may be overwritten by the user to fit his needs
  59394. /**
  59395. * This function does nothing. It may be overwritten to set all the particle first values.
  59396. * The SPS doesn't call this function, you may have to call it by your own.
  59397. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59398. */
  59399. SolidParticleSystem.prototype.initParticles = function () {
  59400. };
  59401. /**
  59402. * This function does nothing. It may be overwritten to recycle a particle.
  59403. * The SPS doesn't call this function, you may have to call it by your own.
  59404. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59405. * @param particle The particle to recycle
  59406. * @returns the recycled particle
  59407. */
  59408. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59409. return particle;
  59410. };
  59411. /**
  59412. * Updates a particle : this function should be overwritten by the user.
  59413. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59414. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59415. * @example : just set a particle position or velocity and recycle conditions
  59416. * @param particle The particle to update
  59417. * @returns the updated particle
  59418. */
  59419. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59420. return particle;
  59421. };
  59422. /**
  59423. * Updates a vertex of a particle : it can be overwritten by the user.
  59424. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59425. * @param particle the current particle
  59426. * @param vertex the current index of the current particle
  59427. * @param pt the index of the current vertex in the particle shape
  59428. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59429. * @example : just set a vertex particle position
  59430. * @returns the updated vertex
  59431. */
  59432. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59433. return vertex;
  59434. };
  59435. /**
  59436. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59437. * This does nothing and may be overwritten by the user.
  59438. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59439. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59440. * @param update the boolean update value actually passed to setParticles()
  59441. */
  59442. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59443. };
  59444. /**
  59445. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59446. * This will be passed three parameters.
  59447. * This does nothing and may be overwritten by the user.
  59448. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59449. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59450. * @param update the boolean update value actually passed to setParticles()
  59451. */
  59452. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59453. };
  59454. return SolidParticleSystem;
  59455. }());
  59456. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59457. })(BABYLON || (BABYLON = {}));
  59458. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59459. var BABYLON;
  59460. (function (BABYLON) {
  59461. var ShaderMaterial = /** @class */ (function (_super) {
  59462. __extends(ShaderMaterial, _super);
  59463. function ShaderMaterial(name, scene, shaderPath, options) {
  59464. var _this = _super.call(this, name, scene) || this;
  59465. _this._textures = {};
  59466. _this._textureArrays = {};
  59467. _this._floats = {};
  59468. _this._ints = {};
  59469. _this._floatsArrays = {};
  59470. _this._colors3 = {};
  59471. _this._colors3Arrays = {};
  59472. _this._colors4 = {};
  59473. _this._vectors2 = {};
  59474. _this._vectors3 = {};
  59475. _this._vectors4 = {};
  59476. _this._matrices = {};
  59477. _this._matrices3x3 = {};
  59478. _this._matrices2x2 = {};
  59479. _this._vectors2Arrays = {};
  59480. _this._vectors3Arrays = {};
  59481. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59482. _this._shaderPath = shaderPath;
  59483. options.needAlphaBlending = options.needAlphaBlending || false;
  59484. options.needAlphaTesting = options.needAlphaTesting || false;
  59485. options.attributes = options.attributes || ["position", "normal", "uv"];
  59486. options.uniforms = options.uniforms || ["worldViewProjection"];
  59487. options.uniformBuffers = options.uniformBuffers || [];
  59488. options.samplers = options.samplers || [];
  59489. options.defines = options.defines || [];
  59490. _this._options = options;
  59491. return _this;
  59492. }
  59493. ShaderMaterial.prototype.getClassName = function () {
  59494. return "ShaderMaterial";
  59495. };
  59496. ShaderMaterial.prototype.needAlphaBlending = function () {
  59497. return this._options.needAlphaBlending;
  59498. };
  59499. ShaderMaterial.prototype.needAlphaTesting = function () {
  59500. return this._options.needAlphaTesting;
  59501. };
  59502. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59503. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59504. this._options.uniforms.push(uniformName);
  59505. }
  59506. };
  59507. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59508. if (this._options.samplers.indexOf(name) === -1) {
  59509. this._options.samplers.push(name);
  59510. }
  59511. this._textures[name] = texture;
  59512. return this;
  59513. };
  59514. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59515. if (this._options.samplers.indexOf(name) === -1) {
  59516. this._options.samplers.push(name);
  59517. }
  59518. this._checkUniform(name);
  59519. this._textureArrays[name] = textures;
  59520. return this;
  59521. };
  59522. ShaderMaterial.prototype.setFloat = function (name, value) {
  59523. this._checkUniform(name);
  59524. this._floats[name] = value;
  59525. return this;
  59526. };
  59527. ShaderMaterial.prototype.setInt = function (name, value) {
  59528. this._checkUniform(name);
  59529. this._ints[name] = value;
  59530. return this;
  59531. };
  59532. ShaderMaterial.prototype.setFloats = function (name, value) {
  59533. this._checkUniform(name);
  59534. this._floatsArrays[name] = value;
  59535. return this;
  59536. };
  59537. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59538. this._checkUniform(name);
  59539. this._colors3[name] = value;
  59540. return this;
  59541. };
  59542. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59543. this._checkUniform(name);
  59544. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59545. color.toArray(arr, arr.length);
  59546. return arr;
  59547. }, []);
  59548. return this;
  59549. };
  59550. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59551. this._checkUniform(name);
  59552. this._colors4[name] = value;
  59553. return this;
  59554. };
  59555. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59556. this._checkUniform(name);
  59557. this._vectors2[name] = value;
  59558. return this;
  59559. };
  59560. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59561. this._checkUniform(name);
  59562. this._vectors3[name] = value;
  59563. return this;
  59564. };
  59565. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59566. this._checkUniform(name);
  59567. this._vectors4[name] = value;
  59568. return this;
  59569. };
  59570. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59571. this._checkUniform(name);
  59572. this._matrices[name] = value;
  59573. return this;
  59574. };
  59575. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59576. this._checkUniform(name);
  59577. this._matrices3x3[name] = value;
  59578. return this;
  59579. };
  59580. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59581. this._checkUniform(name);
  59582. this._matrices2x2[name] = value;
  59583. return this;
  59584. };
  59585. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59586. this._checkUniform(name);
  59587. this._vectors2Arrays[name] = value;
  59588. return this;
  59589. };
  59590. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59591. this._checkUniform(name);
  59592. this._vectors3Arrays[name] = value;
  59593. return this;
  59594. };
  59595. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59596. if (!mesh) {
  59597. return true;
  59598. }
  59599. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59600. return false;
  59601. }
  59602. return false;
  59603. };
  59604. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59605. var scene = this.getScene();
  59606. var engine = scene.getEngine();
  59607. if (!this.checkReadyOnEveryCall) {
  59608. if (this._renderId === scene.getRenderId()) {
  59609. if (this._checkCache(scene, mesh, useInstances)) {
  59610. return true;
  59611. }
  59612. }
  59613. }
  59614. // Instances
  59615. var defines = [];
  59616. var attribs = [];
  59617. var fallbacks = new BABYLON.EffectFallbacks();
  59618. if (useInstances) {
  59619. defines.push("#define INSTANCES");
  59620. }
  59621. for (var index = 0; index < this._options.defines.length; index++) {
  59622. defines.push(this._options.defines[index]);
  59623. }
  59624. for (var index = 0; index < this._options.attributes.length; index++) {
  59625. attribs.push(this._options.attributes[index]);
  59626. }
  59627. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59628. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59629. defines.push("#define VERTEXCOLOR");
  59630. }
  59631. // Bones
  59632. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59633. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59634. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59635. if (mesh.numBoneInfluencers > 4) {
  59636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59638. }
  59639. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59640. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59641. fallbacks.addCPUSkinningFallback(0, mesh);
  59642. if (this._options.uniforms.indexOf("mBones") === -1) {
  59643. this._options.uniforms.push("mBones");
  59644. }
  59645. }
  59646. else {
  59647. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59648. }
  59649. // Textures
  59650. for (var name in this._textures) {
  59651. if (!this._textures[name].isReady()) {
  59652. return false;
  59653. }
  59654. }
  59655. // Alpha test
  59656. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59657. defines.push("#define ALPHATEST");
  59658. }
  59659. var previousEffect = this._effect;
  59660. var join = defines.join("\n");
  59661. this._effect = engine.createEffect(this._shaderPath, {
  59662. attributes: attribs,
  59663. uniformsNames: this._options.uniforms,
  59664. uniformBuffersNames: this._options.uniformBuffers,
  59665. samplers: this._options.samplers,
  59666. defines: join,
  59667. fallbacks: fallbacks,
  59668. onCompiled: this.onCompiled,
  59669. onError: this.onError
  59670. }, engine);
  59671. if (!this._effect.isReady()) {
  59672. return false;
  59673. }
  59674. if (previousEffect !== this._effect) {
  59675. scene.resetCachedMaterial();
  59676. }
  59677. this._renderId = scene.getRenderId();
  59678. return true;
  59679. };
  59680. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59681. var scene = this.getScene();
  59682. if (!this._effect) {
  59683. return;
  59684. }
  59685. if (this._options.uniforms.indexOf("world") !== -1) {
  59686. this._effect.setMatrix("world", world);
  59687. }
  59688. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59689. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59690. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59691. }
  59692. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59693. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59694. }
  59695. };
  59696. ShaderMaterial.prototype.bind = function (world, mesh) {
  59697. // Std values
  59698. this.bindOnlyWorldMatrix(world);
  59699. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59700. if (this._options.uniforms.indexOf("view") !== -1) {
  59701. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59702. }
  59703. if (this._options.uniforms.indexOf("projection") !== -1) {
  59704. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59705. }
  59706. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59707. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59708. }
  59709. // Bones
  59710. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59711. var name;
  59712. // Texture
  59713. for (name in this._textures) {
  59714. this._effect.setTexture(name, this._textures[name]);
  59715. }
  59716. // Texture arrays
  59717. for (name in this._textureArrays) {
  59718. this._effect.setTextureArray(name, this._textureArrays[name]);
  59719. }
  59720. // Int
  59721. for (name in this._ints) {
  59722. this._effect.setInt(name, this._ints[name]);
  59723. }
  59724. // Float
  59725. for (name in this._floats) {
  59726. this._effect.setFloat(name, this._floats[name]);
  59727. }
  59728. // Floats
  59729. for (name in this._floatsArrays) {
  59730. this._effect.setArray(name, this._floatsArrays[name]);
  59731. }
  59732. // Color3
  59733. for (name in this._colors3) {
  59734. this._effect.setColor3(name, this._colors3[name]);
  59735. }
  59736. for (name in this._colors3Arrays) {
  59737. this._effect.setArray3(name, this._colors3Arrays[name]);
  59738. }
  59739. // Color4
  59740. for (name in this._colors4) {
  59741. var color = this._colors4[name];
  59742. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59743. }
  59744. // Vector2
  59745. for (name in this._vectors2) {
  59746. this._effect.setVector2(name, this._vectors2[name]);
  59747. }
  59748. // Vector3
  59749. for (name in this._vectors3) {
  59750. this._effect.setVector3(name, this._vectors3[name]);
  59751. }
  59752. // Vector4
  59753. for (name in this._vectors4) {
  59754. this._effect.setVector4(name, this._vectors4[name]);
  59755. }
  59756. // Matrix
  59757. for (name in this._matrices) {
  59758. this._effect.setMatrix(name, this._matrices[name]);
  59759. }
  59760. // Matrix 3x3
  59761. for (name in this._matrices3x3) {
  59762. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59763. }
  59764. // Matrix 2x2
  59765. for (name in this._matrices2x2) {
  59766. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59767. }
  59768. // Vector2Array
  59769. for (name in this._vectors2Arrays) {
  59770. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59771. }
  59772. // Vector3Array
  59773. for (name in this._vectors3Arrays) {
  59774. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59775. }
  59776. }
  59777. this._afterBind(mesh);
  59778. };
  59779. ShaderMaterial.prototype.getActiveTextures = function () {
  59780. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59781. for (var name in this._textures) {
  59782. activeTextures.push(this._textures[name]);
  59783. }
  59784. for (var name in this._textureArrays) {
  59785. var array = this._textureArrays[name];
  59786. for (var index = 0; index < array.length; index++) {
  59787. activeTextures.push(array[index]);
  59788. }
  59789. }
  59790. return activeTextures;
  59791. };
  59792. ShaderMaterial.prototype.hasTexture = function (texture) {
  59793. if (_super.prototype.hasTexture.call(this, texture)) {
  59794. return true;
  59795. }
  59796. for (var name in this._textures) {
  59797. if (this._textures[name] === texture) {
  59798. return true;
  59799. }
  59800. }
  59801. for (var name in this._textureArrays) {
  59802. var array = this._textureArrays[name];
  59803. for (var index = 0; index < array.length; index++) {
  59804. if (array[index] === texture) {
  59805. return true;
  59806. }
  59807. }
  59808. }
  59809. return false;
  59810. };
  59811. ShaderMaterial.prototype.clone = function (name) {
  59812. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59813. return newShaderMaterial;
  59814. };
  59815. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59816. if (forceDisposeTextures) {
  59817. var name;
  59818. for (name in this._textures) {
  59819. this._textures[name].dispose();
  59820. }
  59821. for (name in this._textureArrays) {
  59822. var array = this._textureArrays[name];
  59823. for (var index = 0; index < array.length; index++) {
  59824. array[index].dispose();
  59825. }
  59826. }
  59827. }
  59828. this._textures = {};
  59829. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59830. };
  59831. ShaderMaterial.prototype.serialize = function () {
  59832. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59833. serializationObject.customType = "BABYLON.ShaderMaterial";
  59834. serializationObject.options = this._options;
  59835. serializationObject.shaderPath = this._shaderPath;
  59836. var name;
  59837. // Texture
  59838. serializationObject.textures = {};
  59839. for (name in this._textures) {
  59840. serializationObject.textures[name] = this._textures[name].serialize();
  59841. }
  59842. // Texture arrays
  59843. serializationObject.textureArrays = {};
  59844. for (name in this._textureArrays) {
  59845. serializationObject.textureArrays[name] = [];
  59846. var array = this._textureArrays[name];
  59847. for (var index = 0; index < array.length; index++) {
  59848. serializationObject.textureArrays[name].push(array[index].serialize());
  59849. }
  59850. }
  59851. // Float
  59852. serializationObject.floats = {};
  59853. for (name in this._floats) {
  59854. serializationObject.floats[name] = this._floats[name];
  59855. }
  59856. // Float s
  59857. serializationObject.FloatArrays = {};
  59858. for (name in this._floatsArrays) {
  59859. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59860. }
  59861. // Color3
  59862. serializationObject.colors3 = {};
  59863. for (name in this._colors3) {
  59864. serializationObject.colors3[name] = this._colors3[name].asArray();
  59865. }
  59866. // Color3 array
  59867. serializationObject.colors3Arrays = {};
  59868. for (name in this._colors3Arrays) {
  59869. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59870. }
  59871. // Color4
  59872. serializationObject.colors4 = {};
  59873. for (name in this._colors4) {
  59874. serializationObject.colors4[name] = this._colors4[name].asArray();
  59875. }
  59876. // Vector2
  59877. serializationObject.vectors2 = {};
  59878. for (name in this._vectors2) {
  59879. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59880. }
  59881. // Vector3
  59882. serializationObject.vectors3 = {};
  59883. for (name in this._vectors3) {
  59884. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59885. }
  59886. // Vector4
  59887. serializationObject.vectors4 = {};
  59888. for (name in this._vectors4) {
  59889. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59890. }
  59891. // Matrix
  59892. serializationObject.matrices = {};
  59893. for (name in this._matrices) {
  59894. serializationObject.matrices[name] = this._matrices[name].asArray();
  59895. }
  59896. // Matrix 3x3
  59897. serializationObject.matrices3x3 = {};
  59898. for (name in this._matrices3x3) {
  59899. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59900. }
  59901. // Matrix 2x2
  59902. serializationObject.matrices2x2 = {};
  59903. for (name in this._matrices2x2) {
  59904. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59905. }
  59906. // Vector2Array
  59907. serializationObject.vectors2Arrays = {};
  59908. for (name in this._vectors2Arrays) {
  59909. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59910. }
  59911. // Vector3Array
  59912. serializationObject.vectors3Arrays = {};
  59913. for (name in this._vectors3Arrays) {
  59914. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59915. }
  59916. return serializationObject;
  59917. };
  59918. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59919. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59920. var name;
  59921. // Texture
  59922. for (name in source.textures) {
  59923. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59924. }
  59925. // Texture arrays
  59926. for (name in source.textureArrays) {
  59927. var array = source.textureArrays[name];
  59928. var textureArray = new Array();
  59929. for (var index = 0; index < array.length; index++) {
  59930. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59931. }
  59932. material.setTextureArray(name, textureArray);
  59933. }
  59934. // Float
  59935. for (name in source.floats) {
  59936. material.setFloat(name, source.floats[name]);
  59937. }
  59938. // Float s
  59939. for (name in source.floatsArrays) {
  59940. material.setFloats(name, source.floatsArrays[name]);
  59941. }
  59942. // Color3
  59943. for (name in source.colors3) {
  59944. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59945. }
  59946. // Color3 arrays
  59947. for (name in source.colors3Arrays) {
  59948. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59949. if (i % 3 === 0) {
  59950. arr.push([num]);
  59951. }
  59952. else {
  59953. arr[arr.length - 1].push(num);
  59954. }
  59955. return arr;
  59956. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59957. material.setColor3Array(name, colors);
  59958. }
  59959. // Color4
  59960. for (name in source.colors4) {
  59961. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59962. }
  59963. // Vector2
  59964. for (name in source.vectors2) {
  59965. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59966. }
  59967. // Vector3
  59968. for (name in source.vectors3) {
  59969. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59970. }
  59971. // Vector4
  59972. for (name in source.vectors4) {
  59973. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59974. }
  59975. // Matrix
  59976. for (name in source.matrices) {
  59977. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59978. }
  59979. // Matrix 3x3
  59980. for (name in source.matrices3x3) {
  59981. material.setMatrix3x3(name, source.matrices3x3[name]);
  59982. }
  59983. // Matrix 2x2
  59984. for (name in source.matrices2x2) {
  59985. material.setMatrix2x2(name, source.matrices2x2[name]);
  59986. }
  59987. // Vector2Array
  59988. for (name in source.vectors2Arrays) {
  59989. material.setArray2(name, source.vectors2Arrays[name]);
  59990. }
  59991. // Vector3Array
  59992. for (name in source.vectors3Arrays) {
  59993. material.setArray3(name, source.vectors3Arrays[name]);
  59994. }
  59995. return material;
  59996. };
  59997. return ShaderMaterial;
  59998. }(BABYLON.Material));
  59999. BABYLON.ShaderMaterial = ShaderMaterial;
  60000. })(BABYLON || (BABYLON = {}));
  60001. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60002. var BABYLON;
  60003. (function (BABYLON) {
  60004. var GroundMesh = /** @class */ (function (_super) {
  60005. __extends(GroundMesh, _super);
  60006. function GroundMesh(name, scene) {
  60007. var _this = _super.call(this, name, scene) || this;
  60008. _this.generateOctree = false;
  60009. return _this;
  60010. }
  60011. GroundMesh.prototype.getClassName = function () {
  60012. return "GroundMesh";
  60013. };
  60014. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60015. get: function () {
  60016. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60017. },
  60018. enumerable: true,
  60019. configurable: true
  60020. });
  60021. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60022. get: function () {
  60023. return this._subdivisionsX;
  60024. },
  60025. enumerable: true,
  60026. configurable: true
  60027. });
  60028. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60029. get: function () {
  60030. return this._subdivisionsY;
  60031. },
  60032. enumerable: true,
  60033. configurable: true
  60034. });
  60035. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60036. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60037. this._subdivisionsX = chunksCount;
  60038. this._subdivisionsY = chunksCount;
  60039. this.subdivide(chunksCount);
  60040. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60041. };
  60042. /**
  60043. * Returns a height (y) value in the Worl system :
  60044. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60045. * Returns the ground y position if (x, z) are outside the ground surface.
  60046. */
  60047. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60048. var world = this.getWorldMatrix();
  60049. var invMat = BABYLON.Tmp.Matrix[5];
  60050. world.invertToRef(invMat);
  60051. var tmpVect = BABYLON.Tmp.Vector3[8];
  60052. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60053. x = tmpVect.x;
  60054. z = tmpVect.z;
  60055. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60056. return this.position.y;
  60057. }
  60058. if (!this._heightQuads || this._heightQuads.length == 0) {
  60059. this._initHeightQuads();
  60060. this._computeHeightQuads();
  60061. }
  60062. var facet = this._getFacetAt(x, z);
  60063. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60064. // return y in the World system
  60065. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60066. return tmpVect.y;
  60067. };
  60068. /**
  60069. * Returns a normalized vector (Vector3) orthogonal to the ground
  60070. * at the ground coordinates (x, z) expressed in the World system.
  60071. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60072. */
  60073. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60074. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60075. this.getNormalAtCoordinatesToRef(x, z, normal);
  60076. return normal;
  60077. };
  60078. /**
  60079. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60080. * at the ground coordinates (x, z) expressed in the World system.
  60081. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60082. * Returns the GroundMesh.
  60083. */
  60084. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60085. var world = this.getWorldMatrix();
  60086. var tmpMat = BABYLON.Tmp.Matrix[5];
  60087. world.invertToRef(tmpMat);
  60088. var tmpVect = BABYLON.Tmp.Vector3[8];
  60089. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60090. x = tmpVect.x;
  60091. z = tmpVect.z;
  60092. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60093. return this;
  60094. }
  60095. if (!this._heightQuads || this._heightQuads.length == 0) {
  60096. this._initHeightQuads();
  60097. this._computeHeightQuads();
  60098. }
  60099. var facet = this._getFacetAt(x, z);
  60100. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60101. return this;
  60102. };
  60103. /**
  60104. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60105. * if the ground has been updated.
  60106. * This can be used in the render loop.
  60107. * Returns the GroundMesh.
  60108. */
  60109. GroundMesh.prototype.updateCoordinateHeights = function () {
  60110. if (!this._heightQuads || this._heightQuads.length == 0) {
  60111. this._initHeightQuads();
  60112. }
  60113. this._computeHeightQuads();
  60114. return this;
  60115. };
  60116. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60117. GroundMesh.prototype._getFacetAt = function (x, z) {
  60118. // retrieve col and row from x, z coordinates in the ground local system
  60119. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60120. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60121. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60122. var facet;
  60123. if (z < quad.slope.x * x + quad.slope.y) {
  60124. facet = quad.facet1;
  60125. }
  60126. else {
  60127. facet = quad.facet2;
  60128. }
  60129. return facet;
  60130. };
  60131. // Creates and populates the heightMap array with "facet" elements :
  60132. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60133. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60134. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60135. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60136. // Returns the GroundMesh.
  60137. GroundMesh.prototype._initHeightQuads = function () {
  60138. var subdivisionsX = this._subdivisionsX;
  60139. var subdivisionsY = this._subdivisionsY;
  60140. this._heightQuads = new Array();
  60141. for (var row = 0; row < subdivisionsY; row++) {
  60142. for (var col = 0; col < subdivisionsX; col++) {
  60143. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  60144. this._heightQuads[row * subdivisionsX + col] = quad;
  60145. }
  60146. }
  60147. return this;
  60148. };
  60149. // Compute each quad element values and update the the heightMap array :
  60150. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60151. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60152. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60153. // Returns the GroundMesh.
  60154. GroundMesh.prototype._computeHeightQuads = function () {
  60155. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60156. if (!positions) {
  60157. return this;
  60158. }
  60159. var v1 = BABYLON.Tmp.Vector3[3];
  60160. var v2 = BABYLON.Tmp.Vector3[2];
  60161. var v3 = BABYLON.Tmp.Vector3[1];
  60162. var v4 = BABYLON.Tmp.Vector3[0];
  60163. var v1v2 = BABYLON.Tmp.Vector3[4];
  60164. var v1v3 = BABYLON.Tmp.Vector3[5];
  60165. var v1v4 = BABYLON.Tmp.Vector3[6];
  60166. var norm1 = BABYLON.Tmp.Vector3[7];
  60167. var norm2 = BABYLON.Tmp.Vector3[8];
  60168. var i = 0;
  60169. var j = 0;
  60170. var k = 0;
  60171. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60172. var h = 0;
  60173. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60174. var d2 = 0;
  60175. var subdivisionsX = this._subdivisionsX;
  60176. var subdivisionsY = this._subdivisionsY;
  60177. for (var row = 0; row < subdivisionsY; row++) {
  60178. for (var col = 0; col < subdivisionsX; col++) {
  60179. i = col * 3;
  60180. j = row * (subdivisionsX + 1) * 3;
  60181. k = (row + 1) * (subdivisionsX + 1) * 3;
  60182. v1.x = positions[j + i];
  60183. v1.y = positions[j + i + 1];
  60184. v1.z = positions[j + i + 2];
  60185. v2.x = positions[j + i + 3];
  60186. v2.y = positions[j + i + 4];
  60187. v2.z = positions[j + i + 5];
  60188. v3.x = positions[k + i];
  60189. v3.y = positions[k + i + 1];
  60190. v3.z = positions[k + i + 2];
  60191. v4.x = positions[k + i + 3];
  60192. v4.y = positions[k + i + 4];
  60193. v4.z = positions[k + i + 5];
  60194. // 2D slope V1V4
  60195. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60196. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60197. // facet equations :
  60198. // we compute each facet normal vector
  60199. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60200. // we compute the value d by applying the equation to v1 which belongs to the plane
  60201. // then we store the facet equation in a Vector4
  60202. v2.subtractToRef(v1, v1v2);
  60203. v3.subtractToRef(v1, v1v3);
  60204. v4.subtractToRef(v1, v1v4);
  60205. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60206. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60207. norm1.normalize();
  60208. norm2.normalize();
  60209. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60210. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60211. var quad = this._heightQuads[row * subdivisionsX + col];
  60212. quad.slope.copyFromFloats(cd, h);
  60213. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60214. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60215. }
  60216. }
  60217. return this;
  60218. };
  60219. GroundMesh.prototype.serialize = function (serializationObject) {
  60220. _super.prototype.serialize.call(this, serializationObject);
  60221. serializationObject.subdivisionsX = this._subdivisionsX;
  60222. serializationObject.subdivisionsY = this._subdivisionsY;
  60223. serializationObject.minX = this._minX;
  60224. serializationObject.maxX = this._maxX;
  60225. serializationObject.minZ = this._minZ;
  60226. serializationObject.maxZ = this._maxZ;
  60227. serializationObject.width = this._width;
  60228. serializationObject.height = this._height;
  60229. };
  60230. GroundMesh.Parse = function (parsedMesh, scene) {
  60231. var result = new GroundMesh(parsedMesh.name, scene);
  60232. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60233. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60234. result._minX = parsedMesh.minX;
  60235. result._maxX = parsedMesh.maxX;
  60236. result._minZ = parsedMesh.minZ;
  60237. result._maxZ = parsedMesh.maxZ;
  60238. result._width = parsedMesh.width;
  60239. result._height = parsedMesh.height;
  60240. return result;
  60241. };
  60242. return GroundMesh;
  60243. }(BABYLON.Mesh));
  60244. BABYLON.GroundMesh = GroundMesh;
  60245. })(BABYLON || (BABYLON = {}));
  60246. //# sourceMappingURL=babylon.groundMesh.js.map
  60247. var BABYLON;
  60248. (function (BABYLON) {
  60249. /**
  60250. * Creates an instance based on a source mesh.
  60251. */
  60252. var InstancedMesh = /** @class */ (function (_super) {
  60253. __extends(InstancedMesh, _super);
  60254. function InstancedMesh(name, source) {
  60255. var _this = _super.call(this, name, source.getScene()) || this;
  60256. source.instances.push(_this);
  60257. _this._sourceMesh = source;
  60258. _this.position.copyFrom(source.position);
  60259. _this.rotation.copyFrom(source.rotation);
  60260. _this.scaling.copyFrom(source.scaling);
  60261. if (source.rotationQuaternion) {
  60262. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60263. }
  60264. _this.infiniteDistance = source.infiniteDistance;
  60265. _this.setPivotMatrix(source.getPivotMatrix());
  60266. _this.refreshBoundingInfo();
  60267. _this._syncSubMeshes();
  60268. return _this;
  60269. }
  60270. /**
  60271. * Returns the string "InstancedMesh".
  60272. */
  60273. InstancedMesh.prototype.getClassName = function () {
  60274. return "InstancedMesh";
  60275. };
  60276. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60277. // Methods
  60278. get: function () {
  60279. return this._sourceMesh.receiveShadows;
  60280. },
  60281. enumerable: true,
  60282. configurable: true
  60283. });
  60284. Object.defineProperty(InstancedMesh.prototype, "material", {
  60285. get: function () {
  60286. return this._sourceMesh.material;
  60287. },
  60288. enumerable: true,
  60289. configurable: true
  60290. });
  60291. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60292. get: function () {
  60293. return this._sourceMesh.visibility;
  60294. },
  60295. enumerable: true,
  60296. configurable: true
  60297. });
  60298. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60299. get: function () {
  60300. return this._sourceMesh.skeleton;
  60301. },
  60302. enumerable: true,
  60303. configurable: true
  60304. });
  60305. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60306. get: function () {
  60307. return this._sourceMesh.renderingGroupId;
  60308. },
  60309. set: function (value) {
  60310. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60311. return;
  60312. }
  60313. //no-op with warning
  60314. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60315. },
  60316. enumerable: true,
  60317. configurable: true
  60318. });
  60319. /**
  60320. * Returns the total number of vertices (integer).
  60321. */
  60322. InstancedMesh.prototype.getTotalVertices = function () {
  60323. return this._sourceMesh.getTotalVertices();
  60324. };
  60325. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60326. get: function () {
  60327. return this._sourceMesh;
  60328. },
  60329. enumerable: true,
  60330. configurable: true
  60331. });
  60332. /**
  60333. * Is this node ready to be used/rendered
  60334. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60335. * @return {boolean} is it ready
  60336. */
  60337. InstancedMesh.prototype.isReady = function (completeCheck) {
  60338. if (completeCheck === void 0) { completeCheck = false; }
  60339. return this._sourceMesh.isReady(completeCheck, true);
  60340. };
  60341. /**
  60342. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60343. */
  60344. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60345. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60346. };
  60347. /**
  60348. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60349. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60350. * The `data` are either a numeric array either a Float32Array.
  60351. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60352. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  60353. * Note that a new underlying VertexBuffer object is created each call.
  60354. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60355. *
  60356. * Possible `kind` values :
  60357. * - BABYLON.VertexBuffer.PositionKind
  60358. * - BABYLON.VertexBuffer.UVKind
  60359. * - BABYLON.VertexBuffer.UV2Kind
  60360. * - BABYLON.VertexBuffer.UV3Kind
  60361. * - BABYLON.VertexBuffer.UV4Kind
  60362. * - BABYLON.VertexBuffer.UV5Kind
  60363. * - BABYLON.VertexBuffer.UV6Kind
  60364. * - BABYLON.VertexBuffer.ColorKind
  60365. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60366. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60367. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60368. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60369. *
  60370. * Returns the Mesh.
  60371. */
  60372. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60373. if (this.sourceMesh) {
  60374. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60375. }
  60376. return this.sourceMesh;
  60377. };
  60378. /**
  60379. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60380. * If the mesh has no geometry, it is simply returned as it is.
  60381. * The `data` are either a numeric array either a Float32Array.
  60382. * No new underlying VertexBuffer object is created.
  60383. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60384. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60385. *
  60386. * Possible `kind` values :
  60387. * - BABYLON.VertexBuffer.PositionKind
  60388. * - BABYLON.VertexBuffer.UVKind
  60389. * - BABYLON.VertexBuffer.UV2Kind
  60390. * - BABYLON.VertexBuffer.UV3Kind
  60391. * - BABYLON.VertexBuffer.UV4Kind
  60392. * - BABYLON.VertexBuffer.UV5Kind
  60393. * - BABYLON.VertexBuffer.UV6Kind
  60394. * - BABYLON.VertexBuffer.ColorKind
  60395. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60396. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60397. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60398. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60399. *
  60400. * Returns the Mesh.
  60401. */
  60402. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60403. if (this.sourceMesh) {
  60404. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60405. }
  60406. return this.sourceMesh;
  60407. };
  60408. /**
  60409. * Sets the mesh indices.
  60410. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60411. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60412. * This method creates a new index buffer each call.
  60413. * Returns the Mesh.
  60414. */
  60415. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60416. if (totalVertices === void 0) { totalVertices = null; }
  60417. if (this.sourceMesh) {
  60418. this.sourceMesh.setIndices(indices, totalVertices);
  60419. }
  60420. return this.sourceMesh;
  60421. };
  60422. /**
  60423. * Boolean : True if the mesh owns the requested kind of data.
  60424. */
  60425. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60426. return this._sourceMesh.isVerticesDataPresent(kind);
  60427. };
  60428. /**
  60429. * Returns an array of indices (IndicesArray).
  60430. */
  60431. InstancedMesh.prototype.getIndices = function () {
  60432. return this._sourceMesh.getIndices();
  60433. };
  60434. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60435. get: function () {
  60436. return this._sourceMesh._positions;
  60437. },
  60438. enumerable: true,
  60439. configurable: true
  60440. });
  60441. /**
  60442. * Sets a new updated BoundingInfo to the mesh.
  60443. * Returns the mesh.
  60444. */
  60445. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60446. var meshBB = this._sourceMesh.getBoundingInfo();
  60447. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60448. this._updateBoundingInfo();
  60449. return this;
  60450. };
  60451. InstancedMesh.prototype._preActivate = function () {
  60452. if (this._currentLOD) {
  60453. this._currentLOD._preActivate();
  60454. }
  60455. return this;
  60456. };
  60457. InstancedMesh.prototype._activate = function (renderId) {
  60458. if (this._currentLOD) {
  60459. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60460. }
  60461. return this;
  60462. };
  60463. /**
  60464. * Returns the current associated LOD AbstractMesh.
  60465. */
  60466. InstancedMesh.prototype.getLOD = function (camera) {
  60467. if (!camera) {
  60468. return this;
  60469. }
  60470. var boundingInfo = this.getBoundingInfo();
  60471. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60472. if (this._currentLOD === this.sourceMesh) {
  60473. return this;
  60474. }
  60475. return this._currentLOD;
  60476. };
  60477. InstancedMesh.prototype._syncSubMeshes = function () {
  60478. this.releaseSubMeshes();
  60479. if (this._sourceMesh.subMeshes) {
  60480. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60481. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60482. }
  60483. }
  60484. return this;
  60485. };
  60486. InstancedMesh.prototype._generatePointsArray = function () {
  60487. return this._sourceMesh._generatePointsArray();
  60488. };
  60489. /**
  60490. * Creates a new InstancedMesh from the current mesh.
  60491. * - name (string) : the cloned mesh name
  60492. * - newParent (optional Node) : the optional Node to parent the clone to.
  60493. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60494. *
  60495. * Returns the clone.
  60496. */
  60497. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60498. var result = this._sourceMesh.createInstance(name);
  60499. // Deep copy
  60500. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60501. // Bounding info
  60502. this.refreshBoundingInfo();
  60503. // Parent
  60504. if (newParent) {
  60505. result.parent = newParent;
  60506. }
  60507. if (!doNotCloneChildren) {
  60508. // Children
  60509. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60510. var mesh = this.getScene().meshes[index];
  60511. if (mesh.parent === this) {
  60512. mesh.clone(mesh.name, result);
  60513. }
  60514. }
  60515. }
  60516. result.computeWorldMatrix(true);
  60517. return result;
  60518. };
  60519. /**
  60520. * Disposes the InstancedMesh.
  60521. * Returns nothing.
  60522. */
  60523. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60524. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60525. // Remove from mesh
  60526. var index = this._sourceMesh.instances.indexOf(this);
  60527. this._sourceMesh.instances.splice(index, 1);
  60528. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60529. };
  60530. return InstancedMesh;
  60531. }(BABYLON.AbstractMesh));
  60532. BABYLON.InstancedMesh = InstancedMesh;
  60533. })(BABYLON || (BABYLON = {}));
  60534. //# sourceMappingURL=babylon.instancedMesh.js.map
  60535. var BABYLON;
  60536. (function (BABYLON) {
  60537. var LinesMesh = /** @class */ (function (_super) {
  60538. __extends(LinesMesh, _super);
  60539. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60540. if (scene === void 0) { scene = null; }
  60541. if (parent === void 0) { parent = null; }
  60542. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60543. _this.useVertexColor = useVertexColor;
  60544. _this.useVertexAlpha = useVertexAlpha;
  60545. _this.color = new BABYLON.Color3(1, 1, 1);
  60546. _this.alpha = 1;
  60547. if (source) {
  60548. _this.color = source.color.clone();
  60549. _this.alpha = source.alpha;
  60550. _this.useVertexColor = source.useVertexColor;
  60551. _this.useVertexAlpha = source.useVertexAlpha;
  60552. }
  60553. _this._intersectionThreshold = 0.1;
  60554. var defines = [];
  60555. var options = {
  60556. attributes: [BABYLON.VertexBuffer.PositionKind],
  60557. uniforms: ["world", "viewProjection"],
  60558. needAlphaBlending: true,
  60559. defines: defines
  60560. };
  60561. if (useVertexAlpha === false) {
  60562. options.needAlphaBlending = false;
  60563. }
  60564. if (!useVertexColor) {
  60565. options.uniforms.push("color");
  60566. }
  60567. else {
  60568. options.defines.push("#define VERTEXCOLOR");
  60569. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60570. }
  60571. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60572. return _this;
  60573. }
  60574. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60575. /**
  60576. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60577. * This margin is expressed in world space coordinates, so its value may vary.
  60578. * Default value is 0.1
  60579. * @returns the intersection Threshold value.
  60580. */
  60581. get: function () {
  60582. return this._intersectionThreshold;
  60583. },
  60584. /**
  60585. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60586. * This margin is expressed in world space coordinates, so its value may vary.
  60587. * @param value the new threshold to apply
  60588. */
  60589. set: function (value) {
  60590. if (this._intersectionThreshold === value) {
  60591. return;
  60592. }
  60593. this._intersectionThreshold = value;
  60594. if (this.geometry) {
  60595. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60596. }
  60597. },
  60598. enumerable: true,
  60599. configurable: true
  60600. });
  60601. /**
  60602. * Returns the string "LineMesh"
  60603. */
  60604. LinesMesh.prototype.getClassName = function () {
  60605. return "LinesMesh";
  60606. };
  60607. Object.defineProperty(LinesMesh.prototype, "material", {
  60608. get: function () {
  60609. return this._colorShader;
  60610. },
  60611. set: function (value) {
  60612. // Do nothing
  60613. },
  60614. enumerable: true,
  60615. configurable: true
  60616. });
  60617. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60618. get: function () {
  60619. return false;
  60620. },
  60621. enumerable: true,
  60622. configurable: true
  60623. });
  60624. LinesMesh.prototype.createInstance = function (name) {
  60625. throw new Error("LinesMeshes do not support createInstance.");
  60626. };
  60627. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60628. if (!this._geometry) {
  60629. return this;
  60630. }
  60631. // VBOs
  60632. this._geometry._bind(this._colorShader.getEffect());
  60633. // Color
  60634. if (!this.useVertexColor) {
  60635. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60636. }
  60637. return this;
  60638. };
  60639. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60640. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60641. return this;
  60642. }
  60643. var engine = this.getScene().getEngine();
  60644. // Draw order
  60645. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60646. return this;
  60647. };
  60648. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60649. this._colorShader.dispose();
  60650. _super.prototype.dispose.call(this, doNotRecurse);
  60651. };
  60652. /**
  60653. * Returns a new LineMesh object cloned from the current one.
  60654. */
  60655. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60656. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60657. };
  60658. return LinesMesh;
  60659. }(BABYLON.Mesh));
  60660. BABYLON.LinesMesh = LinesMesh;
  60661. })(BABYLON || (BABYLON = {}));
  60662. //# sourceMappingURL=babylon.linesMesh.js.map
  60663. var BABYLON;
  60664. (function (BABYLON) {
  60665. /**
  60666. * Class containing static functions to help procedurally build meshes
  60667. */
  60668. var MeshBuilder = /** @class */ (function () {
  60669. function MeshBuilder() {
  60670. }
  60671. MeshBuilder.updateSideOrientation = function (orientation) {
  60672. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60673. return BABYLON.Mesh.DOUBLESIDE;
  60674. }
  60675. if (orientation === undefined || orientation === null) {
  60676. return BABYLON.Mesh.FRONTSIDE;
  60677. }
  60678. return orientation;
  60679. };
  60680. /**
  60681. * Creates a box mesh
  60682. * * The parameter `size` sets the size (float) of each box side (default 1)
  60683. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60684. * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements)
  60685. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60686. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60687. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60688. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60689. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60690. * @param name defines the name of the mesh
  60691. * @param options defines the options used to create the mesh
  60692. * @param scene defines the hosting scene
  60693. * @returns the box mesh
  60694. */
  60695. MeshBuilder.CreateBox = function (name, options, scene) {
  60696. if (scene === void 0) { scene = null; }
  60697. var box = new BABYLON.Mesh(name, scene);
  60698. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60699. box._originalBuilderSideOrientation = options.sideOrientation;
  60700. var vertexData = BABYLON.VertexData.CreateBox(options);
  60701. vertexData.applyToMesh(box, options.updatable);
  60702. return box;
  60703. };
  60704. /**
  60705. * Creates a sphere mesh
  60706. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60707. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  60708. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60709. * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  60710. * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude)
  60711. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60712. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60713. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60714. * @param name defines the name of the mesh
  60715. * @param options defines the options used to create the mesh
  60716. * @param scene defines the hosting scene
  60717. * @returns the sphere mesh
  60718. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60719. */
  60720. MeshBuilder.CreateSphere = function (name, options, scene) {
  60721. var sphere = new BABYLON.Mesh(name, scene);
  60722. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60723. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60724. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60725. vertexData.applyToMesh(sphere, options.updatable);
  60726. return sphere;
  60727. };
  60728. /**
  60729. * Creates a plane polygonal mesh. By default, this is a disc
  60730. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60731. * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
  60732. * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  60733. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60734. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60735. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60736. * @param name defines the name of the mesh
  60737. * @param options defines the options used to create the mesh
  60738. * @param scene defines the hosting scene
  60739. * @returns the plane polygonal mesh
  60740. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60741. */
  60742. MeshBuilder.CreateDisc = function (name, options, scene) {
  60743. if (scene === void 0) { scene = null; }
  60744. var disc = new BABYLON.Mesh(name, scene);
  60745. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60746. disc._originalBuilderSideOrientation = options.sideOrientation;
  60747. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60748. vertexData.applyToMesh(disc, options.updatable);
  60749. return disc;
  60750. };
  60751. /**
  60752. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60753. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60754. * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`)
  60755. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60756. * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface
  60757. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60758. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60759. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60760. * @param name defines the name of the mesh
  60761. * @param options defines the options used to create the mesh
  60762. * @param scene defines the hosting scene
  60763. * @returns the icosahedron mesh
  60764. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60765. */
  60766. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60767. var sphere = new BABYLON.Mesh(name, scene);
  60768. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60769. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60770. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60771. vertexData.applyToMesh(sphere, options.updatable);
  60772. return sphere;
  60773. };
  60774. ;
  60775. /**
  60776. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60777. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60778. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60779. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60780. * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path
  60781. * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11
  60782. * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  60783. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60784. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60785. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60786. * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones
  60787. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60788. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60789. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60790. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60791. * @param name defines the name of the mesh
  60792. * @param options defines the options used to create the mesh
  60793. * @param scene defines the hosting scene
  60794. * @returns the ribbon mesh
  60795. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60796. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60797. */
  60798. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60799. if (scene === void 0) { scene = null; }
  60800. var pathArray = options.pathArray;
  60801. var closeArray = options.closeArray;
  60802. var closePath = options.closePath;
  60803. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60804. var instance = options.instance;
  60805. var updatable = options.updatable;
  60806. if (instance) { // existing ribbon instance update
  60807. // positionFunction : ribbon case
  60808. // only pathArray and sideOrientation parameters are taken into account for positions update
  60809. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60810. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60811. var positionFunction = function (positions) {
  60812. var minlg = pathArray[0].length;
  60813. var i = 0;
  60814. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60815. for (var si = 1; si <= ns; si++) {
  60816. for (var p = 0; p < pathArray.length; p++) {
  60817. var path = pathArray[p];
  60818. var l = path.length;
  60819. minlg = (minlg < l) ? minlg : l;
  60820. var j = 0;
  60821. while (j < minlg) {
  60822. positions[i] = path[j].x;
  60823. positions[i + 1] = path[j].y;
  60824. positions[i + 2] = path[j].z;
  60825. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60826. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60827. }
  60828. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60829. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60830. }
  60831. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60832. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60833. }
  60834. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60835. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60836. }
  60837. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60838. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60839. }
  60840. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60841. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60842. }
  60843. j++;
  60844. i += 3;
  60845. }
  60846. if (instance._closePath) {
  60847. positions[i] = path[0].x;
  60848. positions[i + 1] = path[0].y;
  60849. positions[i + 2] = path[0].z;
  60850. i += 3;
  60851. }
  60852. }
  60853. }
  60854. };
  60855. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60856. positionFunction(positions);
  60857. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60858. instance._boundingInfo.update(instance._worldMatrix);
  60859. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60860. if (options.colors) {
  60861. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60862. for (var c = 0; c < options.colors.length; c++) {
  60863. colors[c * 4] = options.colors[c].r;
  60864. colors[c * 4 + 1] = options.colors[c].g;
  60865. colors[c * 4 + 2] = options.colors[c].b;
  60866. colors[c * 4 + 3] = options.colors[c].a;
  60867. }
  60868. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60869. }
  60870. if (options.uvs) {
  60871. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60872. for (var i = 0; i < options.uvs.length; i++) {
  60873. uvs[i * 2] = options.uvs[i].x;
  60874. uvs[i * 2 + 1] = options.uvs[i].y;
  60875. }
  60876. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60877. }
  60878. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60879. var indices = instance.getIndices();
  60880. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60881. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60882. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60883. if (instance._closePath) {
  60884. var indexFirst = 0;
  60885. var indexLast = 0;
  60886. for (var p = 0; p < pathArray.length; p++) {
  60887. indexFirst = instance._idx[p] * 3;
  60888. if (p + 1 < pathArray.length) {
  60889. indexLast = (instance._idx[p + 1] - 1) * 3;
  60890. }
  60891. else {
  60892. indexLast = normals.length - 3;
  60893. }
  60894. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60895. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60896. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60897. normals[indexLast] = normals[indexFirst];
  60898. normals[indexLast + 1] = normals[indexFirst + 1];
  60899. normals[indexLast + 2] = normals[indexFirst + 2];
  60900. }
  60901. }
  60902. if (!(instance.areNormalsFrozen)) {
  60903. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60904. }
  60905. }
  60906. return instance;
  60907. }
  60908. else { // new ribbon creation
  60909. var ribbon = new BABYLON.Mesh(name, scene);
  60910. ribbon._originalBuilderSideOrientation = sideOrientation;
  60911. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60912. if (closePath) {
  60913. ribbon._idx = vertexData._idx;
  60914. }
  60915. ribbon._closePath = closePath;
  60916. ribbon._closeArray = closeArray;
  60917. vertexData.applyToMesh(ribbon, updatable);
  60918. return ribbon;
  60919. }
  60920. };
  60921. /**
  60922. * Creates a cylinder or a cone mesh
  60923. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60924. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60925. * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  60926. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60927. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60928. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60929. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60930. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60931. * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  60932. * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  60933. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60934. * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  60935. * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  60936. * * If `enclose` is false, a ring surface is one element.
  60937. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60938. * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  60939. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60940. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60941. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60942. * @param name defines the name of the mesh
  60943. * @param options defines the options used to create the mesh
  60944. * @param scene defines the hosting scene
  60945. * @returns the cylinder mesh
  60946. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60947. */
  60948. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60949. var cylinder = new BABYLON.Mesh(name, scene);
  60950. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60951. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60952. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60953. vertexData.applyToMesh(cylinder, options.updatable);
  60954. return cylinder;
  60955. };
  60956. /**
  60957. * Creates a torus mesh
  60958. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60959. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60960. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60961. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60962. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60963. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60964. * @param name defines the name of the mesh
  60965. * @param options defines the options used to create the mesh
  60966. * @param scene defines the hosting scene
  60967. * @returns the torus mesh
  60968. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60969. */
  60970. MeshBuilder.CreateTorus = function (name, options, scene) {
  60971. var torus = new BABYLON.Mesh(name, scene);
  60972. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60973. torus._originalBuilderSideOrientation = options.sideOrientation;
  60974. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60975. vertexData.applyToMesh(torus, options.updatable);
  60976. return torus;
  60977. };
  60978. /**
  60979. * Creates a torus knot mesh
  60980. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60981. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60982. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60983. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60984. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60985. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60986. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60987. * @param name defines the name of the mesh
  60988. * @param options defines the options used to create the mesh
  60989. * @param scene defines the hosting scene
  60990. * @returns the torus knot mesh
  60991. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60992. */
  60993. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60994. var torusKnot = new BABYLON.Mesh(name, scene);
  60995. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60996. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60997. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60998. vertexData.applyToMesh(torusKnot, options.updatable);
  60999. return torusKnot;
  61000. };
  61001. /**
  61002. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61003. * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter
  61004. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61005. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61006. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61007. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61008. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61009. * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  61010. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61011. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61012. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61013. * @param name defines the name of the new line system
  61014. * @param options defines the options used to create the line system
  61015. * @param scene defines the hosting scene
  61016. * @returns a new line system mesh
  61017. */
  61018. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61019. var instance = options.instance;
  61020. var lines = options.lines;
  61021. var colors = options.colors;
  61022. if (instance) { // lines update
  61023. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61024. var vertexColor;
  61025. var lineColors;
  61026. if (colors) {
  61027. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61028. }
  61029. var i = 0;
  61030. var c = 0;
  61031. for (var l = 0; l < lines.length; l++) {
  61032. var points = lines[l];
  61033. for (var p = 0; p < points.length; p++) {
  61034. positions[i] = points[p].x;
  61035. positions[i + 1] = points[p].y;
  61036. positions[i + 2] = points[p].z;
  61037. if (colors && vertexColor) {
  61038. lineColors = colors[l];
  61039. vertexColor[c] = lineColors[p].r;
  61040. vertexColor[c + 1] = lineColors[p].g;
  61041. vertexColor[c + 2] = lineColors[p].b;
  61042. vertexColor[c + 3] = lineColors[p].a;
  61043. c += 4;
  61044. }
  61045. i += 3;
  61046. }
  61047. }
  61048. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61049. if (colors && vertexColor) {
  61050. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61051. }
  61052. return instance;
  61053. }
  61054. // line system creation
  61055. var useVertexColor = (colors) ? true : false;
  61056. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61057. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61058. vertexData.applyToMesh(lineSystem, options.updatable);
  61059. return lineSystem;
  61060. };
  61061. /**
  61062. * Creates a line mesh
  61063. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter
  61064. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61065. * * The parameter `points` is an array successive Vector3
  61066. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  61067. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61068. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61069. * * When updating an instance, remember that only point positions can change, not the number of points
  61070. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61071. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61072. * @param name defines the name of the new line system
  61073. * @param options defines the options used to create the line system
  61074. * @param scene defines the hosting scene
  61075. * @returns a new line mesh
  61076. */
  61077. MeshBuilder.CreateLines = function (name, options, scene) {
  61078. if (scene === void 0) { scene = null; }
  61079. var colors = (options.colors) ? [options.colors] : null;
  61080. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61081. return lines;
  61082. };
  61083. /**
  61084. * Creates a dashed line mesh
  61085. * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter
  61086. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61087. * * The parameter `points` is an array successive Vector3
  61088. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61089. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61090. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61091. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  61092. * * When updating an instance, remember that only point positions can change, not the number of points
  61093. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61094. * @param name defines the name of the mesh
  61095. * @param options defines the options used to create the mesh
  61096. * @param scene defines the hosting scene
  61097. * @returns the dashed line mesh
  61098. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61099. */
  61100. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61101. if (scene === void 0) { scene = null; }
  61102. var points = options.points;
  61103. var instance = options.instance;
  61104. var gapSize = options.gapSize || 1;
  61105. var dashSize = options.dashSize || 3;
  61106. if (instance) { // dashed lines update
  61107. var positionFunction = function (positions) {
  61108. var curvect = BABYLON.Vector3.Zero();
  61109. var nbSeg = positions.length / 6;
  61110. var lg = 0;
  61111. var nb = 0;
  61112. var shft = 0;
  61113. var dashshft = 0;
  61114. var curshft = 0;
  61115. var p = 0;
  61116. var i = 0;
  61117. var j = 0;
  61118. for (i = 0; i < points.length - 1; i++) {
  61119. points[i + 1].subtractToRef(points[i], curvect);
  61120. lg += curvect.length();
  61121. }
  61122. shft = lg / nbSeg;
  61123. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61124. for (i = 0; i < points.length - 1; i++) {
  61125. points[i + 1].subtractToRef(points[i], curvect);
  61126. nb = Math.floor(curvect.length() / shft);
  61127. curvect.normalize();
  61128. j = 0;
  61129. while (j < nb && p < positions.length) {
  61130. curshft = shft * j;
  61131. positions[p] = points[i].x + curshft * curvect.x;
  61132. positions[p + 1] = points[i].y + curshft * curvect.y;
  61133. positions[p + 2] = points[i].z + curshft * curvect.z;
  61134. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61135. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61136. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61137. p += 6;
  61138. j++;
  61139. }
  61140. }
  61141. while (p < positions.length) {
  61142. positions[p] = points[i].x;
  61143. positions[p + 1] = points[i].y;
  61144. positions[p + 2] = points[i].z;
  61145. p += 3;
  61146. }
  61147. };
  61148. instance.updateMeshPositions(positionFunction, false);
  61149. return instance;
  61150. }
  61151. // dashed lines creation
  61152. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61153. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61154. vertexData.applyToMesh(dashedLines, options.updatable);
  61155. dashedLines.dashSize = dashSize;
  61156. dashedLines.gapSize = gapSize;
  61157. return dashedLines;
  61158. };
  61159. /**
  61160. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61161. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61162. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61163. * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  61164. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61165. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  61166. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  61167. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61168. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61169. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61170. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61171. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61172. * @param name defines the name of the mesh
  61173. * @param options defines the options used to create the mesh
  61174. * @param scene defines the hosting scene
  61175. * @returns the extruded shape mesh
  61176. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61177. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61178. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61179. */
  61180. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61181. if (scene === void 0) { scene = null; }
  61182. var path = options.path;
  61183. var shape = options.shape;
  61184. var scale = options.scale || 1;
  61185. var rotation = options.rotation || 0;
  61186. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61187. var updatable = options.updatable;
  61188. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61189. var instance = options.instance || null;
  61190. var invertUV = options.invertUV || false;
  61191. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);
  61192. };
  61193. /**
  61194. * Creates an custom extruded shape mesh.
  61195. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61196. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61197. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61198. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61199. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61200. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61201. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61202. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61203. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61204. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  61205. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  61206. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61207. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61208. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61209. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61210. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61211. * @param name defines the name of the mesh
  61212. * @param options defines the options used to create the mesh
  61213. * @param scene defines the hosting scene
  61214. * @returns the custom extruded shape mesh
  61215. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61216. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61217. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61218. */
  61219. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61220. var path = options.path;
  61221. var shape = options.shape;
  61222. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61223. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61224. var ribbonCloseArray = options.ribbonCloseArray || false;
  61225. var ribbonClosePath = options.ribbonClosePath || false;
  61226. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61227. var updatable = options.updatable;
  61228. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61229. var instance = options.instance;
  61230. var invertUV = options.invertUV || false;
  61231. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);
  61232. };
  61233. /**
  61234. * Creates lathe mesh.
  61235. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61236. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  61237. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61238. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61239. * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape
  61240. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61241. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  61242. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61243. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61244. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61245. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61246. * @param name defines the name of the mesh
  61247. * @param options defines the options used to create the mesh
  61248. * @param scene defines the hosting scene
  61249. * @returns the lathe mesh
  61250. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61251. */
  61252. MeshBuilder.CreateLathe = function (name, options, scene) {
  61253. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61254. var closed = (options.closed === undefined) ? true : options.closed;
  61255. var shape = options.shape;
  61256. var radius = options.radius || 1;
  61257. var tessellation = options.tessellation || 64;
  61258. var updatable = options.updatable;
  61259. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61260. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61261. var pi2 = Math.PI * 2;
  61262. var paths = new Array();
  61263. var invertUV = options.invertUV || false;
  61264. var i = 0;
  61265. var p = 0;
  61266. var step = pi2 / tessellation * arc;
  61267. var rotated;
  61268. var path = new Array();
  61269. for (i = 0; i <= tessellation; i++) {
  61270. var path = [];
  61271. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61272. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61273. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61274. }
  61275. for (p = 0; p < shape.length; p++) {
  61276. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61277. path.push(rotated);
  61278. }
  61279. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61280. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  61281. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61282. }
  61283. paths.push(path);
  61284. }
  61285. // lathe ribbon
  61286. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61287. return lathe;
  61288. };
  61289. /**
  61290. * Creates a plane mesh
  61291. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61292. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61293. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61294. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61295. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61296. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61297. * @param name defines the name of the mesh
  61298. * @param options defines the options used to create the mesh
  61299. * @param scene defines the hosting scene
  61300. * @returns the plane mesh
  61301. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61302. */
  61303. MeshBuilder.CreatePlane = function (name, options, scene) {
  61304. var plane = new BABYLON.Mesh(name, scene);
  61305. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61306. plane._originalBuilderSideOrientation = options.sideOrientation;
  61307. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61308. vertexData.applyToMesh(plane, options.updatable);
  61309. if (options.sourcePlane) {
  61310. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61311. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61312. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61313. plane.rotate(vectorProduct, product);
  61314. }
  61315. return plane;
  61316. };
  61317. /**
  61318. * Creates a ground mesh
  61319. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61320. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61321. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61322. * @param name defines the name of the mesh
  61323. * @param options defines the options used to create the mesh
  61324. * @param scene defines the hosting scene
  61325. * @returns the ground mesh
  61326. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61327. */
  61328. MeshBuilder.CreateGround = function (name, options, scene) {
  61329. var ground = new BABYLON.GroundMesh(name, scene);
  61330. ground._setReady(false);
  61331. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61332. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61333. ground._width = options.width || 1;
  61334. ground._height = options.height || 1;
  61335. ground._maxX = ground._width / 2;
  61336. ground._maxZ = ground._height / 2;
  61337. ground._minX = -ground._maxX;
  61338. ground._minZ = -ground._maxZ;
  61339. var vertexData = BABYLON.VertexData.CreateGround(options);
  61340. vertexData.applyToMesh(ground, options.updatable);
  61341. ground._setReady(true);
  61342. return ground;
  61343. };
  61344. /**
  61345. * Creates a tiled ground mesh
  61346. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61347. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61348. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61349. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61350. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61351. * @param name defines the name of the mesh
  61352. * @param options defines the options used to create the mesh
  61353. * @param scene defines the hosting scene
  61354. * @returns the tiled ground mesh
  61355. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61356. */
  61357. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61358. var tiledGround = new BABYLON.Mesh(name, scene);
  61359. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61360. vertexData.applyToMesh(tiledGround, options.updatable);
  61361. return tiledGround;
  61362. };
  61363. /**
  61364. * Creates a ground mesh from a height map
  61365. * * The parameter `url` sets the URL of the height map image resource.
  61366. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61367. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61368. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61369. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61370. * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  61371. * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  61372. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61373. * @param name defines the name of the mesh
  61374. * @param url defines the url to the height map
  61375. * @param options defines the options used to create the mesh
  61376. * @param scene defines the hosting scene
  61377. * @returns the ground mesh
  61378. * @see http://doc.babylonjs.com/babylon101/height_map
  61379. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61380. */
  61381. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61382. var width = options.width || 10.0;
  61383. var height = options.height || 10.0;
  61384. var subdivisions = options.subdivisions || 1 | 0;
  61385. var minHeight = options.minHeight || 0.0;
  61386. var maxHeight = options.maxHeight || 1.0;
  61387. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61388. var updatable = options.updatable;
  61389. var onReady = options.onReady;
  61390. var ground = new BABYLON.GroundMesh(name, scene);
  61391. ground._subdivisionsX = subdivisions;
  61392. ground._subdivisionsY = subdivisions;
  61393. ground._width = width;
  61394. ground._height = height;
  61395. ground._maxX = ground._width / 2.0;
  61396. ground._maxZ = ground._height / 2.0;
  61397. ground._minX = -ground._maxX;
  61398. ground._minZ = -ground._maxZ;
  61399. ground._setReady(false);
  61400. var onload = function (img) {
  61401. // Getting height map data
  61402. var canvas = document.createElement("canvas");
  61403. var context = canvas.getContext("2d");
  61404. if (!context) {
  61405. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61406. }
  61407. if (scene.isDisposed) {
  61408. return;
  61409. }
  61410. var bufferWidth = img.width;
  61411. var bufferHeight = img.height;
  61412. canvas.width = bufferWidth;
  61413. canvas.height = bufferHeight;
  61414. context.drawImage(img, 0, 0);
  61415. // Create VertexData from map data
  61416. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61417. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61418. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61419. width: width, height: height,
  61420. subdivisions: subdivisions,
  61421. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61422. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61423. });
  61424. vertexData.applyToMesh(ground, updatable);
  61425. //execute ready callback, if set
  61426. if (onReady) {
  61427. onReady(ground);
  61428. }
  61429. ground._setReady(true);
  61430. };
  61431. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61432. return ground;
  61433. };
  61434. /**
  61435. * Creates a polygon mesh
  61436. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61437. * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  61438. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61439. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61440. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4)
  61441. * * Remember you can only change the shape positions, not their number when updating a polygon
  61442. * @param name defines the name of the mesh
  61443. * @param options defines the options used to create the mesh
  61444. * @param scene defines the hosting scene
  61445. * @returns the polygon mesh
  61446. */
  61447. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61448. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61449. var shape = options.shape;
  61450. var holes = options.holes || [];
  61451. var depth = options.depth || 0;
  61452. var contours = [];
  61453. var hole = [];
  61454. for (var i = 0; i < shape.length; i++) {
  61455. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61456. }
  61457. var epsilon = 0.00000001;
  61458. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61459. contours.pop();
  61460. }
  61461. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61462. for (var hNb = 0; hNb < holes.length; hNb++) {
  61463. hole = [];
  61464. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61465. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61466. }
  61467. polygonTriangulation.addHole(hole);
  61468. }
  61469. var polygon = polygonTriangulation.build(options.updatable, depth);
  61470. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61471. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61472. vertexData.applyToMesh(polygon, options.updatable);
  61473. return polygon;
  61474. };
  61475. ;
  61476. /**
  61477. * Creates an extruded polygon mesh, with depth in the Y direction.
  61478. * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)
  61479. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61480. * @param name defines the name of the mesh
  61481. * @param options defines the options used to create the mesh
  61482. * @param scene defines the hosting scene
  61483. * @returns the polygon mesh
  61484. */
  61485. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61486. return MeshBuilder.CreatePolygon(name, options, scene);
  61487. };
  61488. ;
  61489. /**
  61490. * Creates a tube mesh.
  61491. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61492. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61493. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61494. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61495. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61496. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  61497. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61498. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  61499. * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  61500. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61501. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61502. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61503. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61504. * @param name defines the name of the mesh
  61505. * @param options defines the options used to create the mesh
  61506. * @param scene defines the hosting scene
  61507. * @returns the tube mesh
  61508. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61509. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61510. */
  61511. MeshBuilder.CreateTube = function (name, options, scene) {
  61512. var path = options.path;
  61513. var instance = options.instance;
  61514. var radius = 1.0;
  61515. if (instance) {
  61516. radius = instance.radius;
  61517. }
  61518. if (options.radius !== undefined) {
  61519. radius = options.radius;
  61520. }
  61521. ;
  61522. var tessellation = options.tessellation || 64 | 0;
  61523. var radiusFunction = options.radiusFunction || null;
  61524. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61525. var invertUV = options.invertUV || false;
  61526. var updatable = options.updatable;
  61527. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61528. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61529. // tube geometry
  61530. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61531. var tangents = path3D.getTangents();
  61532. var normals = path3D.getNormals();
  61533. var distances = path3D.getDistances();
  61534. var pi2 = Math.PI * 2;
  61535. var step = pi2 / tessellation * arc;
  61536. var returnRadius = function () { return radius; };
  61537. var radiusFunctionFinal = radiusFunction || returnRadius;
  61538. var circlePath;
  61539. var rad;
  61540. var normal;
  61541. var rotated;
  61542. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61543. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61544. for (var i = 0; i < path.length; i++) {
  61545. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61546. circlePath = Array(); // current circle array
  61547. normal = normals[i]; // current normal
  61548. for (var t = 0; t < tessellation; t++) {
  61549. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61550. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61551. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61552. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61553. circlePath[t] = rotated;
  61554. }
  61555. circlePaths[index] = circlePath;
  61556. index++;
  61557. }
  61558. // cap
  61559. var capPath = function (nbPoints, pathIndex) {
  61560. var pointCap = Array();
  61561. for (var i = 0; i < nbPoints; i++) {
  61562. pointCap.push(path[pathIndex]);
  61563. }
  61564. return pointCap;
  61565. };
  61566. switch (cap) {
  61567. case BABYLON.Mesh.NO_CAP:
  61568. break;
  61569. case BABYLON.Mesh.CAP_START:
  61570. circlePaths[0] = capPath(tessellation, 0);
  61571. circlePaths[1] = circlePaths[2].slice(0);
  61572. break;
  61573. case BABYLON.Mesh.CAP_END:
  61574. circlePaths[index] = circlePaths[index - 1].slice(0);
  61575. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61576. break;
  61577. case BABYLON.Mesh.CAP_ALL:
  61578. circlePaths[0] = capPath(tessellation, 0);
  61579. circlePaths[1] = circlePaths[2].slice(0);
  61580. circlePaths[index] = circlePaths[index - 1].slice(0);
  61581. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61582. break;
  61583. default:
  61584. break;
  61585. }
  61586. return circlePaths;
  61587. };
  61588. var path3D;
  61589. var pathArray;
  61590. if (instance) { // tube update
  61591. var arc = options.arc || instance.arc;
  61592. path3D = (instance.path3D).update(path);
  61593. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61594. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61595. instance.path3D = path3D;
  61596. instance.pathArray = pathArray;
  61597. instance.arc = arc;
  61598. instance.radius = radius;
  61599. return instance;
  61600. }
  61601. // tube creation
  61602. path3D = new BABYLON.Path3D(path);
  61603. var newPathArray = new Array();
  61604. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61605. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61606. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61607. tube.pathArray = pathArray;
  61608. tube.path3D = path3D;
  61609. tube.tessellation = tessellation;
  61610. tube.cap = cap;
  61611. tube.arc = options.arc;
  61612. tube.radius = radius;
  61613. return tube;
  61614. };
  61615. /**
  61616. * Creates a polyhedron mesh
  61617. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  61618. * * The parameter `size` (positive float, default 1) sets the polygon size
  61619. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61620. * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`
  61621. * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  61622. * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)
  61623. * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61624. * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored
  61625. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61626. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61627. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61628. * @param name defines the name of the mesh
  61629. * @param options defines the options used to create the mesh
  61630. * @param scene defines the hosting scene
  61631. * @returns the polyhedron mesh
  61632. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61633. */
  61634. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61635. var polyhedron = new BABYLON.Mesh(name, scene);
  61636. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61637. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61638. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61639. vertexData.applyToMesh(polyhedron, options.updatable);
  61640. return polyhedron;
  61641. };
  61642. /**
  61643. * Creates a decal mesh.
  61644. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal
  61645. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61646. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61647. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61648. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61649. * @param name defines the name of the mesh
  61650. * @param sourceMesh defines the mesh where the decal must be applied
  61651. * @param options defines the options used to create the mesh
  61652. * @param scene defines the hosting scene
  61653. * @returns the decal mesh
  61654. * @see http://doc.babylonjs.com/how_to/decals
  61655. */
  61656. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61657. var indices = sourceMesh.getIndices();
  61658. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61659. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61660. var position = options.position || BABYLON.Vector3.Zero();
  61661. var normal = options.normal || BABYLON.Vector3.Up();
  61662. var size = options.size || BABYLON.Vector3.One();
  61663. var angle = options.angle || 0;
  61664. // Getting correct rotation
  61665. if (!normal) {
  61666. var target = new BABYLON.Vector3(0, 0, 1);
  61667. var camera = sourceMesh.getScene().activeCamera;
  61668. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61669. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61670. }
  61671. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61672. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61673. var pitch = Math.atan2(normal.y, len);
  61674. // Matrix
  61675. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61676. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61677. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61678. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61679. var vertexData = new BABYLON.VertexData();
  61680. vertexData.indices = [];
  61681. vertexData.positions = [];
  61682. vertexData.normals = [];
  61683. vertexData.uvs = [];
  61684. var currentVertexDataIndex = 0;
  61685. var extractDecalVector3 = function (indexId) {
  61686. var result = new BABYLON.PositionNormalVertex();
  61687. if (!indices || !positions || !normals) {
  61688. return result;
  61689. }
  61690. var vertexId = indices[indexId];
  61691. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61692. // Send vector to decal local world
  61693. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61694. // Get normal
  61695. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61696. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61697. return result;
  61698. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61699. var clip = function (vertices, axis) {
  61700. if (vertices.length === 0) {
  61701. return vertices;
  61702. }
  61703. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61704. var clipVertices = function (v0, v1) {
  61705. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61706. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61707. };
  61708. var result = new Array();
  61709. for (var index = 0; index < vertices.length; index += 3) {
  61710. var v1Out;
  61711. var v2Out;
  61712. var v3Out;
  61713. var total = 0;
  61714. var nV1 = null;
  61715. var nV2 = null;
  61716. var nV3 = null;
  61717. var nV4 = null;
  61718. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61719. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61720. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61721. v1Out = d1 > 0;
  61722. v2Out = d2 > 0;
  61723. v3Out = d3 > 0;
  61724. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61725. switch (total) {
  61726. case 0:
  61727. result.push(vertices[index]);
  61728. result.push(vertices[index + 1]);
  61729. result.push(vertices[index + 2]);
  61730. break;
  61731. case 1:
  61732. if (v1Out) {
  61733. nV1 = vertices[index + 1];
  61734. nV2 = vertices[index + 2];
  61735. nV3 = clipVertices(vertices[index], nV1);
  61736. nV4 = clipVertices(vertices[index], nV2);
  61737. }
  61738. if (v2Out) {
  61739. nV1 = vertices[index];
  61740. nV2 = vertices[index + 2];
  61741. nV3 = clipVertices(vertices[index + 1], nV1);
  61742. nV4 = clipVertices(vertices[index + 1], nV2);
  61743. result.push(nV3);
  61744. result.push(nV2.clone());
  61745. result.push(nV1.clone());
  61746. result.push(nV2.clone());
  61747. result.push(nV3.clone());
  61748. result.push(nV4);
  61749. break;
  61750. }
  61751. if (v3Out) {
  61752. nV1 = vertices[index];
  61753. nV2 = vertices[index + 1];
  61754. nV3 = clipVertices(vertices[index + 2], nV1);
  61755. nV4 = clipVertices(vertices[index + 2], nV2);
  61756. }
  61757. if (nV1 && nV2 && nV3 && nV4) {
  61758. result.push(nV1.clone());
  61759. result.push(nV2.clone());
  61760. result.push(nV3);
  61761. result.push(nV4);
  61762. result.push(nV3.clone());
  61763. result.push(nV2.clone());
  61764. }
  61765. break;
  61766. case 2:
  61767. if (!v1Out) {
  61768. nV1 = vertices[index].clone();
  61769. nV2 = clipVertices(nV1, vertices[index + 1]);
  61770. nV3 = clipVertices(nV1, vertices[index + 2]);
  61771. result.push(nV1);
  61772. result.push(nV2);
  61773. result.push(nV3);
  61774. }
  61775. if (!v2Out) {
  61776. nV1 = vertices[index + 1].clone();
  61777. nV2 = clipVertices(nV1, vertices[index + 2]);
  61778. nV3 = clipVertices(nV1, vertices[index]);
  61779. result.push(nV1);
  61780. result.push(nV2);
  61781. result.push(nV3);
  61782. }
  61783. if (!v3Out) {
  61784. nV1 = vertices[index + 2].clone();
  61785. nV2 = clipVertices(nV1, vertices[index]);
  61786. nV3 = clipVertices(nV1, vertices[index + 1]);
  61787. result.push(nV1);
  61788. result.push(nV2);
  61789. result.push(nV3);
  61790. }
  61791. break;
  61792. case 3:
  61793. break;
  61794. }
  61795. }
  61796. return result;
  61797. };
  61798. for (var index = 0; index < indices.length; index += 3) {
  61799. var faceVertices = new Array();
  61800. faceVertices.push(extractDecalVector3(index));
  61801. faceVertices.push(extractDecalVector3(index + 1));
  61802. faceVertices.push(extractDecalVector3(index + 2));
  61803. // Clip
  61804. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61805. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61806. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61807. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61808. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61809. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61810. if (faceVertices.length === 0) {
  61811. continue;
  61812. }
  61813. // Add UVs and get back to world
  61814. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61815. var vertex = faceVertices[vIndex];
  61816. //TODO check for Int32Array | Uint32Array | Uint16Array
  61817. vertexData.indices.push(currentVertexDataIndex);
  61818. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61819. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61820. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61821. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61822. currentVertexDataIndex++;
  61823. }
  61824. }
  61825. // Return mesh
  61826. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61827. vertexData.applyToMesh(decal);
  61828. decal.position = position.clone();
  61829. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61830. return decal;
  61831. };
  61832. // Privates
  61833. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61834. // extrusion geometry
  61835. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61836. var tangents = path3D.getTangents();
  61837. var normals = path3D.getNormals();
  61838. var binormals = path3D.getBinormals();
  61839. var distances = path3D.getDistances();
  61840. var angle = 0;
  61841. var returnScale = function () { return scale !== null ? scale : 1; };
  61842. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61843. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61844. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61845. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61846. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61847. for (var i = 0; i < curve.length; i++) {
  61848. var shapePath = new Array();
  61849. var angleStep = rotate(i, distances[i]);
  61850. var scaleRatio = scl(i, distances[i]);
  61851. for (var p = 0; p < shape.length; p++) {
  61852. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61853. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61854. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61855. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61856. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61857. shapePath[p] = rotated;
  61858. }
  61859. shapePaths[index] = shapePath;
  61860. angle += angleStep;
  61861. index++;
  61862. }
  61863. // cap
  61864. var capPath = function (shapePath) {
  61865. var pointCap = Array();
  61866. var barycenter = BABYLON.Vector3.Zero();
  61867. var i;
  61868. for (i = 0; i < shapePath.length; i++) {
  61869. barycenter.addInPlace(shapePath[i]);
  61870. }
  61871. barycenter.scaleInPlace(1.0 / shapePath.length);
  61872. for (i = 0; i < shapePath.length; i++) {
  61873. pointCap.push(barycenter);
  61874. }
  61875. return pointCap;
  61876. };
  61877. switch (cap) {
  61878. case BABYLON.Mesh.NO_CAP:
  61879. break;
  61880. case BABYLON.Mesh.CAP_START:
  61881. shapePaths[0] = capPath(shapePaths[2]);
  61882. shapePaths[1] = shapePaths[2];
  61883. break;
  61884. case BABYLON.Mesh.CAP_END:
  61885. shapePaths[index] = shapePaths[index - 1];
  61886. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61887. break;
  61888. case BABYLON.Mesh.CAP_ALL:
  61889. shapePaths[0] = capPath(shapePaths[2]);
  61890. shapePaths[1] = shapePaths[2];
  61891. shapePaths[index] = shapePaths[index - 1];
  61892. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61893. break;
  61894. default:
  61895. break;
  61896. }
  61897. return shapePaths;
  61898. };
  61899. var path3D;
  61900. var pathArray;
  61901. if (instance) { // instance update
  61902. path3D = (instance.path3D).update(curve);
  61903. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61904. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61905. return instance;
  61906. }
  61907. // extruded shape creation
  61908. path3D = new BABYLON.Path3D(curve);
  61909. var newShapePaths = new Array();
  61910. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61911. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61912. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61913. extrudedGeneric.pathArray = pathArray;
  61914. extrudedGeneric.path3D = path3D;
  61915. extrudedGeneric.cap = cap;
  61916. return extrudedGeneric;
  61917. };
  61918. return MeshBuilder;
  61919. }());
  61920. BABYLON.MeshBuilder = MeshBuilder;
  61921. })(BABYLON || (BABYLON = {}));
  61922. //# sourceMappingURL=babylon.meshBuilder.js.map
  61923. var BABYLON;
  61924. (function (BABYLON) {
  61925. /**
  61926. * Draco compression (https://google.github.io/draco/)
  61927. */
  61928. var DracoCompression = /** @class */ (function () {
  61929. /**
  61930. * Constructor
  61931. */
  61932. function DracoCompression() {
  61933. }
  61934. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61935. /**
  61936. * Returns true if the decoder is available.
  61937. */
  61938. get: function () {
  61939. if (typeof DracoDecoderModule !== "undefined") {
  61940. return true;
  61941. }
  61942. var decoder = DracoCompression.Configuration.decoder;
  61943. if (decoder) {
  61944. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61945. return true;
  61946. }
  61947. if (decoder.fallbackUrl) {
  61948. return true;
  61949. }
  61950. }
  61951. return false;
  61952. },
  61953. enumerable: true,
  61954. configurable: true
  61955. });
  61956. /**
  61957. * Stop all async operations and release resources.
  61958. */
  61959. DracoCompression.prototype.dispose = function () {
  61960. };
  61961. /**
  61962. * Decode Draco compressed mesh data to vertex data.
  61963. * @param data The array buffer view for the Draco compression data
  61964. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61965. * @returns A promise that resolves with the decoded vertex data
  61966. */
  61967. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61968. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61969. var module = wrappedModule.module;
  61970. var vertexData = new BABYLON.VertexData();
  61971. var buffer = new module.DecoderBuffer();
  61972. buffer.Init(data, data.byteLength);
  61973. var decoder = new module.Decoder();
  61974. var geometry;
  61975. var status;
  61976. try {
  61977. var type = decoder.GetEncodedGeometryType(buffer);
  61978. switch (type) {
  61979. case module.TRIANGULAR_MESH:
  61980. geometry = new module.Mesh();
  61981. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61982. break;
  61983. case module.POINT_CLOUD:
  61984. geometry = new module.PointCloud();
  61985. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61986. break;
  61987. default:
  61988. throw new Error("Invalid geometry type " + type);
  61989. }
  61990. if (!status.ok() || !geometry.ptr) {
  61991. throw new Error(status.error_msg());
  61992. }
  61993. var numPoints = geometry.num_points();
  61994. if (type === module.TRIANGULAR_MESH) {
  61995. var numFaces = geometry.num_faces();
  61996. var faceIndices = new module.DracoInt32Array();
  61997. try {
  61998. var indices = new Uint32Array(numFaces * 3);
  61999. for (var i = 0; i < numFaces; i++) {
  62000. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62001. var offset = i * 3;
  62002. indices[offset + 0] = faceIndices.GetValue(0);
  62003. indices[offset + 1] = faceIndices.GetValue(1);
  62004. indices[offset + 2] = faceIndices.GetValue(2);
  62005. }
  62006. vertexData.indices = indices;
  62007. }
  62008. finally {
  62009. module.destroy(faceIndices);
  62010. }
  62011. }
  62012. for (var kind in attributes) {
  62013. var uniqueId = attributes[kind];
  62014. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62015. var dracoData = new module.DracoFloat32Array();
  62016. try {
  62017. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62018. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62019. for (var i = 0; i < babylonData.length; i++) {
  62020. babylonData[i] = dracoData.GetValue(i);
  62021. }
  62022. vertexData.set(babylonData, kind);
  62023. }
  62024. finally {
  62025. module.destroy(dracoData);
  62026. }
  62027. }
  62028. }
  62029. finally {
  62030. if (geometry) {
  62031. module.destroy(geometry);
  62032. }
  62033. module.destroy(decoder);
  62034. module.destroy(buffer);
  62035. }
  62036. return vertexData;
  62037. });
  62038. };
  62039. DracoCompression._GetDecoderModule = function () {
  62040. if (!DracoCompression._DecoderModulePromise) {
  62041. var promise = null;
  62042. var config_1 = {};
  62043. if (typeof DracoDecoderModule !== "undefined") {
  62044. promise = Promise.resolve();
  62045. }
  62046. else {
  62047. var decoder = DracoCompression.Configuration.decoder;
  62048. if (decoder) {
  62049. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62050. promise = Promise.all([
  62051. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62052. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62053. config_1.wasmBinary = data;
  62054. })
  62055. ]);
  62056. }
  62057. else if (decoder.fallbackUrl) {
  62058. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62059. }
  62060. }
  62061. }
  62062. if (!promise) {
  62063. throw new Error("Draco decoder module is not available");
  62064. }
  62065. DracoCompression._DecoderModulePromise = promise.then(function () {
  62066. return new Promise(function (resolve) {
  62067. config_1.onModuleLoaded = function (decoderModule) {
  62068. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62069. resolve({ module: decoderModule });
  62070. };
  62071. DracoDecoderModule(config_1);
  62072. });
  62073. });
  62074. }
  62075. return DracoCompression._DecoderModulePromise;
  62076. };
  62077. DracoCompression._LoadScriptAsync = function (url) {
  62078. return new Promise(function (resolve, reject) {
  62079. BABYLON.Tools.LoadScript(url, function () {
  62080. resolve();
  62081. }, function (message) {
  62082. reject(new Error(message));
  62083. });
  62084. });
  62085. };
  62086. DracoCompression._LoadFileAsync = function (url) {
  62087. return new Promise(function (resolve, reject) {
  62088. BABYLON.Tools.LoadFile(url, function (data) {
  62089. resolve(data);
  62090. }, undefined, undefined, true, function (request, exception) {
  62091. reject(exception);
  62092. });
  62093. });
  62094. };
  62095. /**
  62096. * The configuration.
  62097. */
  62098. DracoCompression.Configuration = {
  62099. decoder: {
  62100. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62101. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62102. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62103. }
  62104. };
  62105. return DracoCompression;
  62106. }());
  62107. BABYLON.DracoCompression = DracoCompression;
  62108. })(BABYLON || (BABYLON = {}));
  62109. //# sourceMappingURL=babylon.dracoCompression.js.map
  62110. var BABYLON;
  62111. (function (BABYLON) {
  62112. var AudioEngine = /** @class */ (function () {
  62113. function AudioEngine() {
  62114. this._audioContext = null;
  62115. this._audioContextInitialized = false;
  62116. this.canUseWebAudio = false;
  62117. this.WarnedWebAudioUnsupported = false;
  62118. this.unlocked = false;
  62119. this.isMP3supported = false;
  62120. this.isOGGsupported = false;
  62121. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62122. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62123. this.canUseWebAudio = true;
  62124. }
  62125. var audioElem = document.createElement('audio');
  62126. try {
  62127. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62128. this.isMP3supported = true;
  62129. }
  62130. }
  62131. catch (e) {
  62132. // protect error during capability check.
  62133. }
  62134. try {
  62135. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62136. this.isOGGsupported = true;
  62137. }
  62138. }
  62139. catch (e) {
  62140. // protect error during capability check.
  62141. }
  62142. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62143. this._unlockiOSaudio();
  62144. }
  62145. else {
  62146. this.unlocked = true;
  62147. }
  62148. }
  62149. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62150. get: function () {
  62151. if (!this._audioContextInitialized) {
  62152. this._initializeAudioContext();
  62153. }
  62154. return this._audioContext;
  62155. },
  62156. enumerable: true,
  62157. configurable: true
  62158. });
  62159. AudioEngine.prototype._unlockiOSaudio = function () {
  62160. var _this = this;
  62161. var unlockaudio = function () {
  62162. if (!_this.audioContext) {
  62163. return;
  62164. }
  62165. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62166. var source = _this.audioContext.createBufferSource();
  62167. source.buffer = buffer;
  62168. source.connect(_this.audioContext.destination);
  62169. source.start(0);
  62170. setTimeout(function () {
  62171. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62172. _this.unlocked = true;
  62173. window.removeEventListener('touchend', unlockaudio, false);
  62174. if (_this.onAudioUnlocked) {
  62175. _this.onAudioUnlocked();
  62176. }
  62177. }
  62178. }, 0);
  62179. };
  62180. window.addEventListener('touchend', unlockaudio, false);
  62181. };
  62182. AudioEngine.prototype._initializeAudioContext = function () {
  62183. try {
  62184. if (this.canUseWebAudio) {
  62185. this._audioContext = new AudioContext();
  62186. // create a global volume gain node
  62187. this.masterGain = this._audioContext.createGain();
  62188. this.masterGain.gain.value = 1;
  62189. this.masterGain.connect(this._audioContext.destination);
  62190. this._audioContextInitialized = true;
  62191. }
  62192. }
  62193. catch (e) {
  62194. this.canUseWebAudio = false;
  62195. BABYLON.Tools.Error("Web Audio: " + e.message);
  62196. }
  62197. };
  62198. AudioEngine.prototype.dispose = function () {
  62199. if (this.canUseWebAudio && this._audioContextInitialized) {
  62200. if (this._connectedAnalyser && this._audioContext) {
  62201. this._connectedAnalyser.stopDebugCanvas();
  62202. this._connectedAnalyser.dispose();
  62203. this.masterGain.disconnect();
  62204. this.masterGain.connect(this._audioContext.destination);
  62205. this._connectedAnalyser = null;
  62206. }
  62207. this.masterGain.gain.value = 1;
  62208. }
  62209. this.WarnedWebAudioUnsupported = false;
  62210. };
  62211. AudioEngine.prototype.getGlobalVolume = function () {
  62212. if (this.canUseWebAudio && this._audioContextInitialized) {
  62213. return this.masterGain.gain.value;
  62214. }
  62215. else {
  62216. return -1;
  62217. }
  62218. };
  62219. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62220. if (this.canUseWebAudio && this._audioContextInitialized) {
  62221. this.masterGain.gain.value = newVolume;
  62222. }
  62223. };
  62224. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62225. if (this._connectedAnalyser) {
  62226. this._connectedAnalyser.stopDebugCanvas();
  62227. }
  62228. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62229. this._connectedAnalyser = analyser;
  62230. this.masterGain.disconnect();
  62231. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62232. }
  62233. };
  62234. return AudioEngine;
  62235. }());
  62236. BABYLON.AudioEngine = AudioEngine;
  62237. })(BABYLON || (BABYLON = {}));
  62238. //# sourceMappingURL=babylon.audioEngine.js.map
  62239. var BABYLON;
  62240. (function (BABYLON) {
  62241. var Sound = /** @class */ (function () {
  62242. /**
  62243. * Create a sound and attach it to a scene
  62244. * @param name Name of your sound
  62245. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62246. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62247. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62248. */
  62249. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62250. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62251. var _this = this;
  62252. this.autoplay = false;
  62253. this.loop = false;
  62254. this.useCustomAttenuation = false;
  62255. this.spatialSound = false;
  62256. this.refDistance = 1;
  62257. this.rolloffFactor = 1;
  62258. this.maxDistance = 100;
  62259. this.distanceModel = "linear";
  62260. this._panningModel = "equalpower";
  62261. this._playbackRate = 1;
  62262. this._streaming = false;
  62263. this._startTime = 0;
  62264. this._startOffset = 0;
  62265. this._position = BABYLON.Vector3.Zero();
  62266. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62267. this._volume = 1;
  62268. this._isReadyToPlay = false;
  62269. this.isPlaying = false;
  62270. this.isPaused = false;
  62271. this._isDirectional = false;
  62272. // Used if you'd like to create a directional sound.
  62273. // If not set, the sound will be omnidirectional
  62274. this._coneInnerAngle = 360;
  62275. this._coneOuterAngle = 360;
  62276. this._coneOuterGain = 0;
  62277. this._isOutputConnected = false;
  62278. this._urlType = "Unknown";
  62279. this.name = name;
  62280. this._scene = scene;
  62281. this._readyToPlayCallback = readyToPlayCallback;
  62282. // Default custom attenuation function is a linear attenuation
  62283. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62284. if (currentDistance < maxDistance) {
  62285. return currentVolume * (1 - currentDistance / maxDistance);
  62286. }
  62287. else {
  62288. return 0;
  62289. }
  62290. };
  62291. if (options) {
  62292. this.autoplay = options.autoplay || false;
  62293. this.loop = options.loop || false;
  62294. // if volume === 0, we need another way to check this option
  62295. if (options.volume !== undefined) {
  62296. this._volume = options.volume;
  62297. }
  62298. this.spatialSound = options.spatialSound || false;
  62299. this.maxDistance = options.maxDistance || 100;
  62300. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62301. this.rolloffFactor = options.rolloffFactor || 1;
  62302. this.refDistance = options.refDistance || 1;
  62303. this.distanceModel = options.distanceModel || "linear";
  62304. this._playbackRate = options.playbackRate || 1;
  62305. this._streaming = options.streaming || false;
  62306. }
  62307. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62308. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62309. this._soundGain.gain.value = this._volume;
  62310. this._inputAudioNode = this._soundGain;
  62311. this._ouputAudioNode = this._soundGain;
  62312. if (this.spatialSound) {
  62313. this._createSpatialParameters();
  62314. }
  62315. this._scene.mainSoundTrack.AddSound(this);
  62316. var validParameter = true;
  62317. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62318. if (urlOrArrayBuffer) {
  62319. try {
  62320. if (typeof (urlOrArrayBuffer) === "string")
  62321. this._urlType = "String";
  62322. if (Array.isArray(urlOrArrayBuffer))
  62323. this._urlType = "Array";
  62324. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62325. this._urlType = "ArrayBuffer";
  62326. var urls = [];
  62327. var codecSupportedFound = false;
  62328. switch (this._urlType) {
  62329. case "ArrayBuffer":
  62330. if (urlOrArrayBuffer.byteLength > 0) {
  62331. codecSupportedFound = true;
  62332. this._soundLoaded(urlOrArrayBuffer);
  62333. }
  62334. break;
  62335. case "String":
  62336. urls.push(urlOrArrayBuffer);
  62337. case "Array":
  62338. if (urls.length === 0)
  62339. urls = urlOrArrayBuffer;
  62340. // If we found a supported format, we load it immediately and stop the loop
  62341. for (var i = 0; i < urls.length; i++) {
  62342. var url = urls[i];
  62343. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62344. codecSupportedFound = true;
  62345. }
  62346. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62347. codecSupportedFound = true;
  62348. }
  62349. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62350. codecSupportedFound = true;
  62351. }
  62352. if (url.indexOf("blob:") !== -1) {
  62353. codecSupportedFound = true;
  62354. }
  62355. if (codecSupportedFound) {
  62356. // Loading sound using XHR2
  62357. if (!this._streaming) {
  62358. this._scene._loadFile(url, function (data) {
  62359. _this._soundLoaded(data);
  62360. }, undefined, true, true, function (exception) {
  62361. if (exception) {
  62362. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62363. }
  62364. BABYLON.Tools.Error("Sound creation aborted.");
  62365. _this._scene.mainSoundTrack.RemoveSound(_this);
  62366. });
  62367. }
  62368. // Streaming sound using HTML5 Audio tag
  62369. else {
  62370. this._htmlAudioElement = new Audio(url);
  62371. this._htmlAudioElement.controls = false;
  62372. this._htmlAudioElement.loop = this.loop;
  62373. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62374. this._htmlAudioElement.preload = "auto";
  62375. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62376. _this._isReadyToPlay = true;
  62377. if (_this.autoplay) {
  62378. _this.play();
  62379. }
  62380. if (_this._readyToPlayCallback) {
  62381. _this._readyToPlayCallback();
  62382. }
  62383. });
  62384. document.body.appendChild(this._htmlAudioElement);
  62385. }
  62386. break;
  62387. }
  62388. }
  62389. break;
  62390. default:
  62391. validParameter = false;
  62392. break;
  62393. }
  62394. if (!validParameter) {
  62395. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62396. }
  62397. else {
  62398. if (!codecSupportedFound) {
  62399. this._isReadyToPlay = true;
  62400. // Simulating a ready to play event to avoid breaking code path
  62401. if (this._readyToPlayCallback) {
  62402. window.setTimeout(function () {
  62403. if (_this._readyToPlayCallback) {
  62404. _this._readyToPlayCallback();
  62405. }
  62406. }, 1000);
  62407. }
  62408. }
  62409. }
  62410. }
  62411. catch (ex) {
  62412. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62413. this._scene.mainSoundTrack.RemoveSound(this);
  62414. }
  62415. }
  62416. }
  62417. else {
  62418. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62419. this._scene.mainSoundTrack.AddSound(this);
  62420. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62421. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62422. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62423. }
  62424. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62425. if (this._readyToPlayCallback) {
  62426. window.setTimeout(function () {
  62427. if (_this._readyToPlayCallback) {
  62428. _this._readyToPlayCallback();
  62429. }
  62430. }, 1000);
  62431. }
  62432. }
  62433. }
  62434. Sound.prototype.dispose = function () {
  62435. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62436. if (this.isPlaying) {
  62437. this.stop();
  62438. }
  62439. this._isReadyToPlay = false;
  62440. if (this.soundTrackId === -1) {
  62441. this._scene.mainSoundTrack.RemoveSound(this);
  62442. }
  62443. else {
  62444. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62445. }
  62446. if (this._soundGain) {
  62447. this._soundGain.disconnect();
  62448. this._soundGain = null;
  62449. }
  62450. if (this._soundPanner) {
  62451. this._soundPanner.disconnect();
  62452. this._soundPanner = null;
  62453. }
  62454. if (this._soundSource) {
  62455. this._soundSource.disconnect();
  62456. this._soundSource = null;
  62457. }
  62458. this._audioBuffer = null;
  62459. if (this._htmlAudioElement) {
  62460. this._htmlAudioElement.pause();
  62461. this._htmlAudioElement.src = "";
  62462. document.body.removeChild(this._htmlAudioElement);
  62463. }
  62464. if (this._connectedMesh && this._registerFunc) {
  62465. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62466. this._connectedMesh = null;
  62467. }
  62468. }
  62469. };
  62470. Sound.prototype.isReady = function () {
  62471. return this._isReadyToPlay;
  62472. };
  62473. Sound.prototype._soundLoaded = function (audioData) {
  62474. var _this = this;
  62475. if (!BABYLON.Engine.audioEngine.audioContext) {
  62476. return;
  62477. }
  62478. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62479. _this._audioBuffer = buffer;
  62480. _this._isReadyToPlay = true;
  62481. if (_this.autoplay) {
  62482. _this.play();
  62483. }
  62484. if (_this._readyToPlayCallback) {
  62485. _this._readyToPlayCallback();
  62486. }
  62487. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62488. };
  62489. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62490. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62491. this._audioBuffer = audioBuffer;
  62492. this._isReadyToPlay = true;
  62493. }
  62494. };
  62495. Sound.prototype.updateOptions = function (options) {
  62496. if (options) {
  62497. this.loop = options.loop || this.loop;
  62498. this.maxDistance = options.maxDistance || this.maxDistance;
  62499. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62500. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62501. this.refDistance = options.refDistance || this.refDistance;
  62502. this.distanceModel = options.distanceModel || this.distanceModel;
  62503. this._playbackRate = options.playbackRate || this._playbackRate;
  62504. this._updateSpatialParameters();
  62505. if (this.isPlaying) {
  62506. if (this._streaming) {
  62507. this._htmlAudioElement.playbackRate = this._playbackRate;
  62508. }
  62509. else {
  62510. if (this._soundSource) {
  62511. this._soundSource.playbackRate.value = this._playbackRate;
  62512. }
  62513. }
  62514. }
  62515. }
  62516. };
  62517. Sound.prototype._createSpatialParameters = function () {
  62518. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62519. if (this._scene.headphone) {
  62520. this._panningModel = "HRTF";
  62521. }
  62522. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62523. this._updateSpatialParameters();
  62524. this._soundPanner.connect(this._ouputAudioNode);
  62525. this._inputAudioNode = this._soundPanner;
  62526. }
  62527. };
  62528. Sound.prototype._updateSpatialParameters = function () {
  62529. if (this.spatialSound && this._soundPanner) {
  62530. if (this.useCustomAttenuation) {
  62531. // Tricks to disable in a way embedded Web Audio attenuation
  62532. this._soundPanner.distanceModel = "linear";
  62533. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62534. this._soundPanner.refDistance = 1;
  62535. this._soundPanner.rolloffFactor = 1;
  62536. this._soundPanner.panningModel = this._panningModel;
  62537. }
  62538. else {
  62539. this._soundPanner.distanceModel = this.distanceModel;
  62540. this._soundPanner.maxDistance = this.maxDistance;
  62541. this._soundPanner.refDistance = this.refDistance;
  62542. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62543. this._soundPanner.panningModel = this._panningModel;
  62544. }
  62545. }
  62546. };
  62547. Sound.prototype.switchPanningModelToHRTF = function () {
  62548. this._panningModel = "HRTF";
  62549. this._switchPanningModel();
  62550. };
  62551. Sound.prototype.switchPanningModelToEqualPower = function () {
  62552. this._panningModel = "equalpower";
  62553. this._switchPanningModel();
  62554. };
  62555. Sound.prototype._switchPanningModel = function () {
  62556. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62557. this._soundPanner.panningModel = this._panningModel;
  62558. }
  62559. };
  62560. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62561. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62562. if (this._isOutputConnected) {
  62563. this._ouputAudioNode.disconnect();
  62564. }
  62565. this._ouputAudioNode.connect(soundTrackAudioNode);
  62566. this._isOutputConnected = true;
  62567. }
  62568. };
  62569. /**
  62570. * Transform this sound into a directional source
  62571. * @param coneInnerAngle Size of the inner cone in degree
  62572. * @param coneOuterAngle Size of the outer cone in degree
  62573. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62574. */
  62575. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62576. if (coneOuterAngle < coneInnerAngle) {
  62577. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62578. return;
  62579. }
  62580. this._coneInnerAngle = coneInnerAngle;
  62581. this._coneOuterAngle = coneOuterAngle;
  62582. this._coneOuterGain = coneOuterGain;
  62583. this._isDirectional = true;
  62584. if (this.isPlaying && this.loop) {
  62585. this.stop();
  62586. this.play();
  62587. }
  62588. };
  62589. Sound.prototype.setPosition = function (newPosition) {
  62590. this._position = newPosition;
  62591. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62592. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62593. }
  62594. };
  62595. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62596. this._localDirection = newLocalDirection;
  62597. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62598. this._updateDirection();
  62599. }
  62600. };
  62601. Sound.prototype._updateDirection = function () {
  62602. if (!this._connectedMesh || !this._soundPanner) {
  62603. return;
  62604. }
  62605. var mat = this._connectedMesh.getWorldMatrix();
  62606. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62607. direction.normalize();
  62608. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62609. };
  62610. Sound.prototype.updateDistanceFromListener = function () {
  62611. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62612. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62613. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62614. }
  62615. };
  62616. Sound.prototype.setAttenuationFunction = function (callback) {
  62617. this._customAttenuationFunction = callback;
  62618. };
  62619. /**
  62620. * Play the sound
  62621. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62622. * @param offset (optional) Start the sound setting it at a specific time
  62623. */
  62624. Sound.prototype.play = function (time, offset) {
  62625. var _this = this;
  62626. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62627. try {
  62628. if (this._startOffset < 0) {
  62629. time = -this._startOffset;
  62630. this._startOffset = 0;
  62631. }
  62632. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62633. if (!this._soundSource || !this._streamingSource) {
  62634. if (this.spatialSound && this._soundPanner) {
  62635. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62636. if (this._isDirectional) {
  62637. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62638. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62639. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62640. if (this._connectedMesh) {
  62641. this._updateDirection();
  62642. }
  62643. else {
  62644. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62645. }
  62646. }
  62647. }
  62648. }
  62649. if (this._streaming) {
  62650. if (!this._streamingSource) {
  62651. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62652. this._htmlAudioElement.onended = function () { _this._onended(); };
  62653. this._htmlAudioElement.playbackRate = this._playbackRate;
  62654. }
  62655. this._streamingSource.disconnect();
  62656. this._streamingSource.connect(this._inputAudioNode);
  62657. this._htmlAudioElement.play();
  62658. }
  62659. else {
  62660. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62661. this._soundSource.buffer = this._audioBuffer;
  62662. this._soundSource.connect(this._inputAudioNode);
  62663. this._soundSource.loop = this.loop;
  62664. this._soundSource.playbackRate.value = this._playbackRate;
  62665. this._soundSource.onended = function () { _this._onended(); };
  62666. if (this._soundSource.buffer) {
  62667. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62668. }
  62669. }
  62670. this._startTime = startTime;
  62671. this.isPlaying = true;
  62672. this.isPaused = false;
  62673. }
  62674. catch (ex) {
  62675. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62676. }
  62677. }
  62678. };
  62679. Sound.prototype._onended = function () {
  62680. this.isPlaying = false;
  62681. if (this.onended) {
  62682. this.onended();
  62683. }
  62684. };
  62685. /**
  62686. * Stop the sound
  62687. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62688. */
  62689. Sound.prototype.stop = function (time) {
  62690. if (this.isPlaying) {
  62691. if (this._streaming) {
  62692. this._htmlAudioElement.pause();
  62693. // Test needed for Firefox or it will generate an Invalid State Error
  62694. if (this._htmlAudioElement.currentTime > 0) {
  62695. this._htmlAudioElement.currentTime = 0;
  62696. }
  62697. }
  62698. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62699. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62700. this._soundSource.stop(stopTime);
  62701. this._soundSource.onended = function () { };
  62702. if (!this.isPaused) {
  62703. this._startOffset = 0;
  62704. }
  62705. }
  62706. this.isPlaying = false;
  62707. }
  62708. };
  62709. Sound.prototype.pause = function () {
  62710. if (this.isPlaying) {
  62711. this.isPaused = true;
  62712. if (this._streaming) {
  62713. this._htmlAudioElement.pause();
  62714. }
  62715. else if (BABYLON.Engine.audioEngine.audioContext) {
  62716. this.stop(0);
  62717. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62718. }
  62719. }
  62720. };
  62721. Sound.prototype.setVolume = function (newVolume, time) {
  62722. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62723. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62724. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62725. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62726. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62727. }
  62728. else {
  62729. this._soundGain.gain.value = newVolume;
  62730. }
  62731. }
  62732. this._volume = newVolume;
  62733. };
  62734. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62735. this._playbackRate = newPlaybackRate;
  62736. if (this.isPlaying) {
  62737. if (this._streaming) {
  62738. this._htmlAudioElement.playbackRate = this._playbackRate;
  62739. }
  62740. else if (this._soundSource) {
  62741. this._soundSource.playbackRate.value = this._playbackRate;
  62742. }
  62743. }
  62744. };
  62745. Sound.prototype.getVolume = function () {
  62746. return this._volume;
  62747. };
  62748. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62749. var _this = this;
  62750. if (this._connectedMesh && this._registerFunc) {
  62751. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62752. this._registerFunc = null;
  62753. }
  62754. this._connectedMesh = meshToConnectTo;
  62755. if (!this.spatialSound) {
  62756. this.spatialSound = true;
  62757. this._createSpatialParameters();
  62758. if (this.isPlaying && this.loop) {
  62759. this.stop();
  62760. this.play();
  62761. }
  62762. }
  62763. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62764. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62765. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62766. };
  62767. Sound.prototype.detachFromMesh = function () {
  62768. if (this._connectedMesh && this._registerFunc) {
  62769. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62770. this._registerFunc = null;
  62771. this._connectedMesh = null;
  62772. }
  62773. };
  62774. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62775. if (!node.getBoundingInfo) {
  62776. return;
  62777. }
  62778. var mesh = node;
  62779. var boundingInfo = mesh.getBoundingInfo();
  62780. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62781. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62782. this._updateDirection();
  62783. }
  62784. };
  62785. Sound.prototype.clone = function () {
  62786. var _this = this;
  62787. if (!this._streaming) {
  62788. var setBufferAndRun = function () {
  62789. if (_this._isReadyToPlay) {
  62790. clonedSound._audioBuffer = _this.getAudioBuffer();
  62791. clonedSound._isReadyToPlay = true;
  62792. if (clonedSound.autoplay) {
  62793. clonedSound.play();
  62794. }
  62795. }
  62796. else {
  62797. window.setTimeout(setBufferAndRun, 300);
  62798. }
  62799. };
  62800. var currentOptions = {
  62801. autoplay: this.autoplay, loop: this.loop,
  62802. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62803. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62804. refDistance: this.refDistance, distanceModel: this.distanceModel
  62805. };
  62806. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62807. if (this.useCustomAttenuation) {
  62808. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62809. }
  62810. clonedSound.setPosition(this._position);
  62811. clonedSound.setPlaybackRate(this._playbackRate);
  62812. setBufferAndRun();
  62813. return clonedSound;
  62814. }
  62815. // Can't clone a streaming sound
  62816. else {
  62817. return null;
  62818. }
  62819. };
  62820. Sound.prototype.getAudioBuffer = function () {
  62821. return this._audioBuffer;
  62822. };
  62823. Sound.prototype.serialize = function () {
  62824. var serializationObject = {
  62825. name: this.name,
  62826. url: this.name,
  62827. autoplay: this.autoplay,
  62828. loop: this.loop,
  62829. volume: this._volume,
  62830. spatialSound: this.spatialSound,
  62831. maxDistance: this.maxDistance,
  62832. rolloffFactor: this.rolloffFactor,
  62833. refDistance: this.refDistance,
  62834. distanceModel: this.distanceModel,
  62835. playbackRate: this._playbackRate,
  62836. panningModel: this._panningModel,
  62837. soundTrackId: this.soundTrackId
  62838. };
  62839. if (this.spatialSound) {
  62840. if (this._connectedMesh)
  62841. serializationObject.connectedMeshId = this._connectedMesh.id;
  62842. serializationObject.position = this._position.asArray();
  62843. serializationObject.refDistance = this.refDistance;
  62844. serializationObject.distanceModel = this.distanceModel;
  62845. serializationObject.isDirectional = this._isDirectional;
  62846. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62847. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62848. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62849. serializationObject.coneOuterGain = this._coneOuterGain;
  62850. }
  62851. return serializationObject;
  62852. };
  62853. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62854. var soundName = parsedSound.name;
  62855. var soundUrl;
  62856. if (parsedSound.url) {
  62857. soundUrl = rootUrl + parsedSound.url;
  62858. }
  62859. else {
  62860. soundUrl = rootUrl + soundName;
  62861. }
  62862. var options = {
  62863. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62864. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62865. rolloffFactor: parsedSound.rolloffFactor,
  62866. refDistance: parsedSound.refDistance,
  62867. distanceModel: parsedSound.distanceModel,
  62868. playbackRate: parsedSound.playbackRate
  62869. };
  62870. var newSound;
  62871. if (!sourceSound) {
  62872. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62873. scene._addPendingData(newSound);
  62874. }
  62875. else {
  62876. var setBufferAndRun = function () {
  62877. if (sourceSound._isReadyToPlay) {
  62878. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62879. newSound._isReadyToPlay = true;
  62880. if (newSound.autoplay) {
  62881. newSound.play();
  62882. }
  62883. }
  62884. else {
  62885. window.setTimeout(setBufferAndRun, 300);
  62886. }
  62887. };
  62888. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62889. setBufferAndRun();
  62890. }
  62891. if (parsedSound.position) {
  62892. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62893. newSound.setPosition(soundPosition);
  62894. }
  62895. if (parsedSound.isDirectional) {
  62896. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62897. if (parsedSound.localDirectionToMesh) {
  62898. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62899. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62900. }
  62901. }
  62902. if (parsedSound.connectedMeshId) {
  62903. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62904. if (connectedMesh) {
  62905. newSound.attachToMesh(connectedMesh);
  62906. }
  62907. }
  62908. return newSound;
  62909. };
  62910. return Sound;
  62911. }());
  62912. BABYLON.Sound = Sound;
  62913. })(BABYLON || (BABYLON = {}));
  62914. //# sourceMappingURL=babylon.sound.js.map
  62915. var BABYLON;
  62916. (function (BABYLON) {
  62917. var SoundTrack = /** @class */ (function () {
  62918. function SoundTrack(scene, options) {
  62919. this.id = -1;
  62920. this._isMainTrack = false;
  62921. this._isInitialized = false;
  62922. this._scene = scene;
  62923. this.soundCollection = new Array();
  62924. this._options = options;
  62925. if (!this._isMainTrack) {
  62926. this._scene.soundTracks.push(this);
  62927. this.id = this._scene.soundTracks.length - 1;
  62928. }
  62929. }
  62930. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62931. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62932. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62933. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62934. if (this._options) {
  62935. if (this._options.volume) {
  62936. this._outputAudioNode.gain.value = this._options.volume;
  62937. }
  62938. if (this._options.mainTrack) {
  62939. this._isMainTrack = this._options.mainTrack;
  62940. }
  62941. }
  62942. this._isInitialized = true;
  62943. }
  62944. };
  62945. SoundTrack.prototype.dispose = function () {
  62946. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62947. if (this._connectedAnalyser) {
  62948. this._connectedAnalyser.stopDebugCanvas();
  62949. }
  62950. while (this.soundCollection.length) {
  62951. this.soundCollection[0].dispose();
  62952. }
  62953. if (this._outputAudioNode) {
  62954. this._outputAudioNode.disconnect();
  62955. }
  62956. this._outputAudioNode = null;
  62957. }
  62958. };
  62959. SoundTrack.prototype.AddSound = function (sound) {
  62960. if (!this._isInitialized) {
  62961. this._initializeSoundTrackAudioGraph();
  62962. }
  62963. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62964. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62965. }
  62966. if (sound.soundTrackId) {
  62967. if (sound.soundTrackId === -1) {
  62968. this._scene.mainSoundTrack.RemoveSound(sound);
  62969. }
  62970. else {
  62971. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62972. }
  62973. }
  62974. this.soundCollection.push(sound);
  62975. sound.soundTrackId = this.id;
  62976. };
  62977. SoundTrack.prototype.RemoveSound = function (sound) {
  62978. var index = this.soundCollection.indexOf(sound);
  62979. if (index !== -1) {
  62980. this.soundCollection.splice(index, 1);
  62981. }
  62982. };
  62983. SoundTrack.prototype.setVolume = function (newVolume) {
  62984. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62985. this._outputAudioNode.gain.value = newVolume;
  62986. }
  62987. };
  62988. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62989. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62990. for (var i = 0; i < this.soundCollection.length; i++) {
  62991. this.soundCollection[i].switchPanningModelToHRTF();
  62992. }
  62993. }
  62994. };
  62995. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62996. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62997. for (var i = 0; i < this.soundCollection.length; i++) {
  62998. this.soundCollection[i].switchPanningModelToEqualPower();
  62999. }
  63000. }
  63001. };
  63002. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63003. if (this._connectedAnalyser) {
  63004. this._connectedAnalyser.stopDebugCanvas();
  63005. }
  63006. this._connectedAnalyser = analyser;
  63007. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63008. this._outputAudioNode.disconnect();
  63009. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63010. }
  63011. };
  63012. return SoundTrack;
  63013. }());
  63014. BABYLON.SoundTrack = SoundTrack;
  63015. })(BABYLON || (BABYLON = {}));
  63016. //# sourceMappingURL=babylon.soundtrack.js.map
  63017. var BABYLON;
  63018. (function (BABYLON) {
  63019. /**
  63020. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63021. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63022. */
  63023. var Analyser = /** @class */ (function () {
  63024. /**
  63025. * Creates a new analyser
  63026. * @param scene defines hosting scene
  63027. */
  63028. function Analyser(scene) {
  63029. /**
  63030. * Gets or sets the smoothing
  63031. * @ignorenaming
  63032. */
  63033. this.SMOOTHING = 0.75;
  63034. /**
  63035. * Gets or sets the FFT table size
  63036. * @ignorenaming
  63037. */
  63038. this.FFT_SIZE = 512;
  63039. /**
  63040. * Gets or sets the bar graph amplitude
  63041. * @ignorenaming
  63042. */
  63043. this.BARGRAPHAMPLITUDE = 256;
  63044. /**
  63045. * Gets or sets the position of the debug canvas
  63046. * @ignorenaming
  63047. */
  63048. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63049. /**
  63050. * Gets or sets the debug canvas size
  63051. * @ignorenaming
  63052. */
  63053. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63054. this._scene = scene;
  63055. this._audioEngine = BABYLON.Engine.audioEngine;
  63056. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63057. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63058. this._webAudioAnalyser.minDecibels = -140;
  63059. this._webAudioAnalyser.maxDecibels = 0;
  63060. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63061. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63062. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63063. }
  63064. }
  63065. /**
  63066. * Get the number of data values you will have to play with for the visualization
  63067. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63068. * @returns a number
  63069. */
  63070. Analyser.prototype.getFrequencyBinCount = function () {
  63071. if (this._audioEngine.canUseWebAudio) {
  63072. return this._webAudioAnalyser.frequencyBinCount;
  63073. }
  63074. else {
  63075. return 0;
  63076. }
  63077. };
  63078. /**
  63079. * Gets the current frequency data as a byte array
  63080. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63081. * @returns a Uint8Array
  63082. */
  63083. Analyser.prototype.getByteFrequencyData = function () {
  63084. if (this._audioEngine.canUseWebAudio) {
  63085. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63086. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63087. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63088. }
  63089. return this._byteFreqs;
  63090. };
  63091. /**
  63092. * Gets the current waveform as a byte array
  63093. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63094. * @returns a Uint8Array
  63095. */
  63096. Analyser.prototype.getByteTimeDomainData = function () {
  63097. if (this._audioEngine.canUseWebAudio) {
  63098. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63099. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63100. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63101. }
  63102. return this._byteTime;
  63103. };
  63104. /**
  63105. * Gets the current frequency data as a float array
  63106. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63107. * @returns a Float32Array
  63108. */
  63109. Analyser.prototype.getFloatFrequencyData = function () {
  63110. if (this._audioEngine.canUseWebAudio) {
  63111. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63112. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63113. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63114. }
  63115. return this._floatFreqs;
  63116. };
  63117. /**
  63118. * Renders the debug canvas
  63119. */
  63120. Analyser.prototype.drawDebugCanvas = function () {
  63121. var _this = this;
  63122. if (this._audioEngine.canUseWebAudio) {
  63123. if (!this._debugCanvas) {
  63124. this._debugCanvas = document.createElement("canvas");
  63125. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63126. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63127. this._debugCanvas.style.position = "absolute";
  63128. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63129. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63130. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63131. document.body.appendChild(this._debugCanvas);
  63132. this._registerFunc = function () {
  63133. _this.drawDebugCanvas();
  63134. };
  63135. this._scene.registerBeforeRender(this._registerFunc);
  63136. }
  63137. if (this._registerFunc && this._debugCanvasContext) {
  63138. var workingArray = this.getByteFrequencyData();
  63139. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63140. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63141. // Draw the frequency domain chart.
  63142. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63143. var value = workingArray[i];
  63144. var percent = value / this.BARGRAPHAMPLITUDE;
  63145. var height = this.DEBUGCANVASSIZE.height * percent;
  63146. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63147. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63148. var hue = i / this.getFrequencyBinCount() * 360;
  63149. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63150. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63151. }
  63152. }
  63153. }
  63154. };
  63155. /**
  63156. * Stops rendering the debug canvas and removes it
  63157. */
  63158. Analyser.prototype.stopDebugCanvas = function () {
  63159. if (this._debugCanvas) {
  63160. if (this._registerFunc) {
  63161. this._scene.unregisterBeforeRender(this._registerFunc);
  63162. this._registerFunc = null;
  63163. }
  63164. document.body.removeChild(this._debugCanvas);
  63165. this._debugCanvas = null;
  63166. this._debugCanvasContext = null;
  63167. }
  63168. };
  63169. /**
  63170. * Connects two audio nodes
  63171. * @param inputAudioNode defines first node to connect
  63172. * @param outputAudioNode defines second node to connect
  63173. */
  63174. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63175. if (this._audioEngine.canUseWebAudio) {
  63176. inputAudioNode.connect(this._webAudioAnalyser);
  63177. this._webAudioAnalyser.connect(outputAudioNode);
  63178. }
  63179. };
  63180. /**
  63181. * Releases all associated resources
  63182. */
  63183. Analyser.prototype.dispose = function () {
  63184. if (this._audioEngine.canUseWebAudio) {
  63185. this._webAudioAnalyser.disconnect();
  63186. }
  63187. };
  63188. return Analyser;
  63189. }());
  63190. BABYLON.Analyser = Analyser;
  63191. })(BABYLON || (BABYLON = {}));
  63192. //# sourceMappingURL=babylon.analyser.js.map
  63193. var BABYLON;
  63194. (function (BABYLON) {
  63195. var CubeTexture = /** @class */ (function (_super) {
  63196. __extends(CubeTexture, _super);
  63197. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  63198. if (extensions === void 0) { extensions = null; }
  63199. if (noMipmap === void 0) { noMipmap = false; }
  63200. if (files === void 0) { files = null; }
  63201. if (onLoad === void 0) { onLoad = null; }
  63202. if (onError === void 0) { onError = null; }
  63203. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63204. if (prefiltered === void 0) { prefiltered = false; }
  63205. if (forcedExtension === void 0) { forcedExtension = null; }
  63206. var _this = _super.call(this, scene) || this;
  63207. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63208. /**
  63209. * Gets or sets the center of the bounding box associated with the cube texture
  63210. * It must define where the camera used to render the texture was set
  63211. */
  63212. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63213. _this._rotationY = 0;
  63214. _this.name = rootUrl;
  63215. _this.url = rootUrl;
  63216. _this._noMipmap = noMipmap;
  63217. _this.hasAlpha = false;
  63218. _this._format = format;
  63219. _this._prefiltered = prefiltered;
  63220. _this.isCube = true;
  63221. _this._textureMatrix = BABYLON.Matrix.Identity();
  63222. if (prefiltered) {
  63223. _this.gammaSpace = false;
  63224. }
  63225. if (!rootUrl && !files) {
  63226. return _this;
  63227. }
  63228. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63229. var lastDot = rootUrl.lastIndexOf(".");
  63230. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63231. var isDDS = (extension === ".dds");
  63232. if (!files) {
  63233. if (!isDDS && !extensions) {
  63234. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63235. }
  63236. files = [];
  63237. if (extensions) {
  63238. for (var index = 0; index < extensions.length; index++) {
  63239. files.push(rootUrl + extensions[index]);
  63240. }
  63241. }
  63242. }
  63243. _this._files = files;
  63244. if (!_this._texture) {
  63245. if (!scene.useDelayedTextureLoading) {
  63246. if (prefiltered) {
  63247. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63248. }
  63249. else {
  63250. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63251. }
  63252. }
  63253. else {
  63254. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63255. }
  63256. }
  63257. else if (onLoad) {
  63258. if (_this._texture.isReady) {
  63259. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63260. }
  63261. else {
  63262. _this._texture.onLoadedObservable.add(onLoad);
  63263. }
  63264. }
  63265. return _this;
  63266. }
  63267. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63268. get: function () {
  63269. return this._boundingBoxSize;
  63270. },
  63271. /**
  63272. * Gets or sets the size of the bounding box associated with the cube texture
  63273. * When defined, the cubemap will switch to local mode
  63274. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63275. * @example https://www.babylonjs-playground.com/#RNASML
  63276. */
  63277. set: function (value) {
  63278. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63279. return;
  63280. }
  63281. this._boundingBoxSize = value;
  63282. var scene = this.getScene();
  63283. if (scene) {
  63284. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63285. }
  63286. },
  63287. enumerable: true,
  63288. configurable: true
  63289. });
  63290. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63291. /**
  63292. * Gets texture matrix rotation angle around Y axis radians.
  63293. */
  63294. get: function () {
  63295. return this._rotationY;
  63296. },
  63297. /**
  63298. * Sets texture matrix rotation angle around Y axis in radians.
  63299. */
  63300. set: function (value) {
  63301. this._rotationY = value;
  63302. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63303. },
  63304. enumerable: true,
  63305. configurable: true
  63306. });
  63307. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63308. var rootUrlKey = "";
  63309. files.forEach(function (url) { return rootUrlKey += url; });
  63310. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63311. };
  63312. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63313. if (forcedExtension === void 0) { forcedExtension = null; }
  63314. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63315. };
  63316. // Methods
  63317. CubeTexture.prototype.delayLoad = function () {
  63318. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63319. return;
  63320. }
  63321. var scene = this.getScene();
  63322. if (!scene) {
  63323. return;
  63324. }
  63325. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63326. this._texture = this._getFromCache(this.url, this._noMipmap);
  63327. if (!this._texture) {
  63328. if (this._prefiltered) {
  63329. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63330. }
  63331. else {
  63332. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63333. }
  63334. }
  63335. };
  63336. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63337. return this._textureMatrix;
  63338. };
  63339. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63340. this._textureMatrix = value;
  63341. };
  63342. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63343. var texture = BABYLON.SerializationHelper.Parse(function () {
  63344. var prefiltered = false;
  63345. if (parsedTexture.prefiltered) {
  63346. prefiltered = parsedTexture.prefiltered;
  63347. }
  63348. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63349. }, parsedTexture, scene);
  63350. // Local Cubemaps
  63351. if (parsedTexture.boundingBoxPosition) {
  63352. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63353. }
  63354. if (parsedTexture.boundingBoxSize) {
  63355. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63356. }
  63357. // Animations
  63358. if (parsedTexture.animations) {
  63359. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63360. var parsedAnimation = parsedTexture.animations[animationIndex];
  63361. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63362. }
  63363. }
  63364. return texture;
  63365. };
  63366. CubeTexture.prototype.clone = function () {
  63367. var _this = this;
  63368. return BABYLON.SerializationHelper.Clone(function () {
  63369. var scene = _this.getScene();
  63370. if (!scene) {
  63371. return _this;
  63372. }
  63373. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63374. }, this);
  63375. };
  63376. __decorate([
  63377. BABYLON.serialize("rotationY")
  63378. ], CubeTexture.prototype, "_rotationY", void 0);
  63379. return CubeTexture;
  63380. }(BABYLON.BaseTexture));
  63381. BABYLON.CubeTexture = CubeTexture;
  63382. })(BABYLON || (BABYLON = {}));
  63383. //# sourceMappingURL=babylon.cubeTexture.js.map
  63384. var BABYLON;
  63385. (function (BABYLON) {
  63386. var RenderTargetTexture = /** @class */ (function (_super) {
  63387. __extends(RenderTargetTexture, _super);
  63388. /**
  63389. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63390. * or used a shadow, depth texture...
  63391. * @param name The friendly name of the texture
  63392. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  63393. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63394. * @param generateMipMaps True if mip maps need to be generated after render.
  63395. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63396. * @param type The type of the buffer in the RTT (int, half float, float...)
  63397. * @param isCube True if a cube texture needs to be created
  63398. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63399. * @param generateDepthBuffer True to generate a depth buffer
  63400. * @param generateStencilBuffer True to generate a stencil buffer
  63401. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63402. */
  63403. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63404. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63405. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63406. if (isCube === void 0) { isCube = false; }
  63407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63408. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63409. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63410. if (isMulti === void 0) { isMulti = false; }
  63411. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63412. _this.isCube = isCube;
  63413. /**
  63414. * Use this list to define the list of mesh you want to render.
  63415. */
  63416. _this.renderList = new Array();
  63417. _this.renderParticles = true;
  63418. _this.renderSprites = false;
  63419. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63420. _this.ignoreCameraViewport = false;
  63421. // Events
  63422. /**
  63423. * An event triggered when the texture is unbind.
  63424. */
  63425. _this.onBeforeBindObservable = new BABYLON.Observable();
  63426. /**
  63427. * An event triggered when the texture is unbind.
  63428. */
  63429. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63430. /**
  63431. * An event triggered before rendering the texture
  63432. */
  63433. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63434. /**
  63435. * An event triggered after rendering the texture
  63436. */
  63437. _this.onAfterRenderObservable = new BABYLON.Observable();
  63438. /**
  63439. * An event triggered after the texture clear
  63440. */
  63441. _this.onClearObservable = new BABYLON.Observable();
  63442. _this._currentRefreshId = -1;
  63443. _this._refreshRate = 1;
  63444. _this._samples = 1;
  63445. /**
  63446. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63447. * It must define where the camera used to render the texture is set
  63448. */
  63449. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63450. scene = _this.getScene();
  63451. if (!scene) {
  63452. return _this;
  63453. }
  63454. _this._engine = scene.getEngine();
  63455. _this.name = name;
  63456. _this.isRenderTarget = true;
  63457. _this._initialSizeParameter = size;
  63458. _this._processSizeParameter(size);
  63459. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63460. });
  63461. _this._generateMipMaps = generateMipMaps ? true : false;
  63462. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63463. // Rendering groups
  63464. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63465. if (isMulti) {
  63466. return _this;
  63467. }
  63468. _this._renderTargetOptions = {
  63469. generateMipMaps: generateMipMaps,
  63470. type: type,
  63471. samplingMode: samplingMode,
  63472. generateDepthBuffer: generateDepthBuffer,
  63473. generateStencilBuffer: generateStencilBuffer
  63474. };
  63475. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63476. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63477. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63478. }
  63479. if (isCube) {
  63480. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63481. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63482. _this._textureMatrix = BABYLON.Matrix.Identity();
  63483. }
  63484. else {
  63485. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63486. }
  63487. return _this;
  63488. }
  63489. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63490. get: function () {
  63491. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63492. },
  63493. enumerable: true,
  63494. configurable: true
  63495. });
  63496. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63497. get: function () {
  63498. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63499. },
  63500. enumerable: true,
  63501. configurable: true
  63502. });
  63503. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63504. get: function () {
  63505. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63506. },
  63507. enumerable: true,
  63508. configurable: true
  63509. });
  63510. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63511. set: function (callback) {
  63512. if (this._onAfterUnbindObserver) {
  63513. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63514. }
  63515. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63516. },
  63517. enumerable: true,
  63518. configurable: true
  63519. });
  63520. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63521. set: function (callback) {
  63522. if (this._onBeforeRenderObserver) {
  63523. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63524. }
  63525. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63526. },
  63527. enumerable: true,
  63528. configurable: true
  63529. });
  63530. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63531. set: function (callback) {
  63532. if (this._onAfterRenderObserver) {
  63533. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63534. }
  63535. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63536. },
  63537. enumerable: true,
  63538. configurable: true
  63539. });
  63540. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63541. set: function (callback) {
  63542. if (this._onClearObserver) {
  63543. this.onClearObservable.remove(this._onClearObserver);
  63544. }
  63545. this._onClearObserver = this.onClearObservable.add(callback);
  63546. },
  63547. enumerable: true,
  63548. configurable: true
  63549. });
  63550. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63551. get: function () {
  63552. return this._renderTargetOptions;
  63553. },
  63554. enumerable: true,
  63555. configurable: true
  63556. });
  63557. RenderTargetTexture.prototype._onRatioRescale = function () {
  63558. if (this._sizeRatio) {
  63559. this.resize(this._initialSizeParameter);
  63560. }
  63561. };
  63562. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63563. get: function () {
  63564. return this._boundingBoxSize;
  63565. },
  63566. /**
  63567. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63568. * When defined, the cubemap will switch to local mode
  63569. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63570. * @example https://www.babylonjs-playground.com/#RNASML
  63571. */
  63572. set: function (value) {
  63573. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63574. return;
  63575. }
  63576. this._boundingBoxSize = value;
  63577. var scene = this.getScene();
  63578. if (scene) {
  63579. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63580. }
  63581. },
  63582. enumerable: true,
  63583. configurable: true
  63584. });
  63585. /**
  63586. * Creates a depth stencil texture.
  63587. * This is only available in WebGL 2 or with the depth texture extension available.
  63588. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63589. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63590. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63591. */
  63592. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63593. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63594. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63595. if (generateStencil === void 0) { generateStencil = false; }
  63596. if (!this.getScene()) {
  63597. return;
  63598. }
  63599. var engine = this.getScene().getEngine();
  63600. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63601. bilinearFiltering: bilinearFiltering,
  63602. comparisonFunction: comparisonFunction,
  63603. generateStencil: generateStencil,
  63604. isCube: this.isCube
  63605. });
  63606. engine.setFrameBufferDepthStencilTexture(this);
  63607. };
  63608. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63609. if (size.ratio) {
  63610. this._sizeRatio = size.ratio;
  63611. this._size = {
  63612. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63613. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63614. };
  63615. }
  63616. else {
  63617. this._size = size;
  63618. }
  63619. };
  63620. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63621. get: function () {
  63622. return this._samples;
  63623. },
  63624. set: function (value) {
  63625. if (this._samples === value) {
  63626. return;
  63627. }
  63628. var scene = this.getScene();
  63629. if (!scene) {
  63630. return;
  63631. }
  63632. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63633. },
  63634. enumerable: true,
  63635. configurable: true
  63636. });
  63637. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63638. this._currentRefreshId = -1;
  63639. };
  63640. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63641. get: function () {
  63642. return this._refreshRate;
  63643. },
  63644. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63645. set: function (value) {
  63646. this._refreshRate = value;
  63647. this.resetRefreshCounter();
  63648. },
  63649. enumerable: true,
  63650. configurable: true
  63651. });
  63652. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63653. if (!this._postProcessManager) {
  63654. var scene = this.getScene();
  63655. if (!scene) {
  63656. return;
  63657. }
  63658. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63659. this._postProcesses = new Array();
  63660. }
  63661. this._postProcesses.push(postProcess);
  63662. this._postProcesses[0].autoClear = false;
  63663. };
  63664. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63665. if (!this._postProcesses) {
  63666. return;
  63667. }
  63668. if (dispose) {
  63669. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63670. var postProcess = _a[_i];
  63671. postProcess.dispose();
  63672. }
  63673. }
  63674. this._postProcesses = [];
  63675. };
  63676. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63677. if (!this._postProcesses) {
  63678. return;
  63679. }
  63680. var index = this._postProcesses.indexOf(postProcess);
  63681. if (index === -1) {
  63682. return;
  63683. }
  63684. this._postProcesses.splice(index, 1);
  63685. if (this._postProcesses.length > 0) {
  63686. this._postProcesses[0].autoClear = false;
  63687. }
  63688. };
  63689. RenderTargetTexture.prototype._shouldRender = function () {
  63690. if (this._currentRefreshId === -1) { // At least render once
  63691. this._currentRefreshId = 1;
  63692. return true;
  63693. }
  63694. if (this.refreshRate === this._currentRefreshId) {
  63695. this._currentRefreshId = 1;
  63696. return true;
  63697. }
  63698. this._currentRefreshId++;
  63699. return false;
  63700. };
  63701. RenderTargetTexture.prototype.getRenderSize = function () {
  63702. if (this._size.width) {
  63703. return this._size.width;
  63704. }
  63705. return this._size;
  63706. };
  63707. RenderTargetTexture.prototype.getRenderWidth = function () {
  63708. if (this._size.width) {
  63709. return this._size.width;
  63710. }
  63711. return this._size;
  63712. };
  63713. RenderTargetTexture.prototype.getRenderHeight = function () {
  63714. if (this._size.width) {
  63715. return this._size.height;
  63716. }
  63717. return this._size;
  63718. };
  63719. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63720. get: function () {
  63721. return true;
  63722. },
  63723. enumerable: true,
  63724. configurable: true
  63725. });
  63726. RenderTargetTexture.prototype.scale = function (ratio) {
  63727. var newSize = this.getRenderSize() * ratio;
  63728. this.resize(newSize);
  63729. };
  63730. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63731. if (this.isCube) {
  63732. return this._textureMatrix;
  63733. }
  63734. return _super.prototype.getReflectionTextureMatrix.call(this);
  63735. };
  63736. RenderTargetTexture.prototype.resize = function (size) {
  63737. this.releaseInternalTexture();
  63738. var scene = this.getScene();
  63739. if (!scene) {
  63740. return;
  63741. }
  63742. this._processSizeParameter(size);
  63743. if (this.isCube) {
  63744. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63745. }
  63746. else {
  63747. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63748. }
  63749. };
  63750. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63751. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63752. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63753. var scene = this.getScene();
  63754. if (!scene) {
  63755. return;
  63756. }
  63757. var engine = scene.getEngine();
  63758. if (this.useCameraPostProcesses !== undefined) {
  63759. useCameraPostProcess = this.useCameraPostProcesses;
  63760. }
  63761. if (this._waitingRenderList) {
  63762. this.renderList = [];
  63763. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63764. var id = this._waitingRenderList[index];
  63765. var mesh_1 = scene.getMeshByID(id);
  63766. if (mesh_1) {
  63767. this.renderList.push(mesh_1);
  63768. }
  63769. }
  63770. delete this._waitingRenderList;
  63771. }
  63772. // Is predicate defined?
  63773. if (this.renderListPredicate) {
  63774. if (this.renderList) {
  63775. this.renderList.splice(0); // Clear previous renderList
  63776. }
  63777. else {
  63778. this.renderList = [];
  63779. }
  63780. var scene = this.getScene();
  63781. if (!scene) {
  63782. return;
  63783. }
  63784. var sceneMeshes = scene.meshes;
  63785. for (var index = 0; index < sceneMeshes.length; index++) {
  63786. var mesh = sceneMeshes[index];
  63787. if (this.renderListPredicate(mesh)) {
  63788. this.renderList.push(mesh);
  63789. }
  63790. }
  63791. }
  63792. this.onBeforeBindObservable.notifyObservers(this);
  63793. // Set custom projection.
  63794. // Needs to be before binding to prevent changing the aspect ratio.
  63795. var camera;
  63796. if (this.activeCamera) {
  63797. camera = this.activeCamera;
  63798. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63799. if (this.activeCamera !== scene.activeCamera) {
  63800. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63801. }
  63802. }
  63803. else {
  63804. camera = scene.activeCamera;
  63805. if (camera) {
  63806. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63807. }
  63808. }
  63809. // Prepare renderingManager
  63810. this._renderingManager.reset();
  63811. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63812. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63813. var sceneRenderId = scene.getRenderId();
  63814. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63815. var mesh = currentRenderList[meshIndex];
  63816. if (mesh) {
  63817. if (!mesh.isReady(this.refreshRate === 0)) {
  63818. this.resetRefreshCounter();
  63819. continue;
  63820. }
  63821. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63822. var isMasked = void 0;
  63823. if (!this.renderList && camera) {
  63824. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63825. }
  63826. else {
  63827. isMasked = false;
  63828. }
  63829. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63830. mesh._activate(sceneRenderId);
  63831. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63832. var subMesh = mesh.subMeshes[subIndex];
  63833. scene._activeIndices.addCount(subMesh.indexCount, false);
  63834. this._renderingManager.dispatch(subMesh, mesh);
  63835. }
  63836. }
  63837. }
  63838. }
  63839. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63840. var particleSystem = scene.particleSystems[particleIndex];
  63841. var emitter = particleSystem.emitter;
  63842. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63843. continue;
  63844. }
  63845. if (currentRenderList.indexOf(emitter) >= 0) {
  63846. this._renderingManager.dispatchParticles(particleSystem);
  63847. }
  63848. }
  63849. if (this.isCube) {
  63850. for (var face = 0; face < 6; face++) {
  63851. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63852. scene.incrementRenderId();
  63853. scene.resetCachedMaterial();
  63854. }
  63855. }
  63856. else {
  63857. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63858. }
  63859. this.onAfterUnbindObservable.notifyObservers(this);
  63860. if (scene.activeCamera) {
  63861. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63862. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63863. }
  63864. engine.setViewport(scene.activeCamera.viewport);
  63865. }
  63866. scene.resetCachedMaterial();
  63867. };
  63868. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63869. var minimum = 128;
  63870. var x = renderDimension * scale;
  63871. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63872. // Ensure we don't exceed the render dimension (while staying POT)
  63873. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63874. };
  63875. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63876. var _this = this;
  63877. if (!this._texture) {
  63878. return;
  63879. }
  63880. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63881. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63882. });
  63883. };
  63884. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63885. var scene = this.getScene();
  63886. if (!scene) {
  63887. return;
  63888. }
  63889. var engine = scene.getEngine();
  63890. if (!this._texture) {
  63891. return;
  63892. }
  63893. // Bind
  63894. if (this._postProcessManager) {
  63895. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63896. }
  63897. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63898. if (this._texture) {
  63899. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63900. }
  63901. }
  63902. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63903. // Clear
  63904. if (this.onClearObservable.hasObservers()) {
  63905. this.onClearObservable.notifyObservers(engine);
  63906. }
  63907. else {
  63908. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63909. }
  63910. if (!this._doNotChangeAspectRatio) {
  63911. scene.updateTransformMatrix(true);
  63912. }
  63913. // Render
  63914. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63915. if (this._postProcessManager) {
  63916. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63917. }
  63918. else if (useCameraPostProcess) {
  63919. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63920. }
  63921. if (!this._doNotChangeAspectRatio) {
  63922. scene.updateTransformMatrix(true);
  63923. }
  63924. // Dump ?
  63925. if (dumpForDebug) {
  63926. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63927. }
  63928. // Unbind
  63929. if (!this.isCube || faceIndex === 5) {
  63930. if (this.isCube) {
  63931. if (faceIndex === 5) {
  63932. engine.generateMipMapsForCubemap(this._texture);
  63933. }
  63934. }
  63935. this.unbindFrameBuffer(engine, faceIndex);
  63936. }
  63937. else {
  63938. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63939. }
  63940. };
  63941. /**
  63942. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63943. * This allowed control for front to back rendering or reversly depending of the special needs.
  63944. *
  63945. * @param renderingGroupId The rendering group id corresponding to its index
  63946. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63947. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63948. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63949. */
  63950. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63951. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63952. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63953. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63954. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63955. };
  63956. /**
  63957. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63958. *
  63959. * @param renderingGroupId The rendering group id corresponding to its index
  63960. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63961. */
  63962. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63963. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63964. };
  63965. RenderTargetTexture.prototype.clone = function () {
  63966. var textureSize = this.getSize();
  63967. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63968. // Base texture
  63969. newTexture.hasAlpha = this.hasAlpha;
  63970. newTexture.level = this.level;
  63971. // RenderTarget Texture
  63972. newTexture.coordinatesMode = this.coordinatesMode;
  63973. if (this.renderList) {
  63974. newTexture.renderList = this.renderList.slice(0);
  63975. }
  63976. return newTexture;
  63977. };
  63978. RenderTargetTexture.prototype.serialize = function () {
  63979. if (!this.name) {
  63980. return null;
  63981. }
  63982. var serializationObject = _super.prototype.serialize.call(this);
  63983. serializationObject.renderTargetSize = this.getRenderSize();
  63984. serializationObject.renderList = [];
  63985. if (this.renderList) {
  63986. for (var index = 0; index < this.renderList.length; index++) {
  63987. serializationObject.renderList.push(this.renderList[index].id);
  63988. }
  63989. }
  63990. return serializationObject;
  63991. };
  63992. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63993. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63994. var objBuffer = this.getInternalTexture();
  63995. var scene = this.getScene();
  63996. if (objBuffer && scene) {
  63997. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63998. }
  63999. };
  64000. RenderTargetTexture.prototype.dispose = function () {
  64001. if (this._postProcessManager) {
  64002. this._postProcessManager.dispose();
  64003. this._postProcessManager = null;
  64004. }
  64005. this.clearPostProcesses(true);
  64006. if (this._resizeObserver) {
  64007. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64008. this._resizeObserver = null;
  64009. }
  64010. this.renderList = null;
  64011. // Remove from custom render targets
  64012. var scene = this.getScene();
  64013. if (!scene) {
  64014. return;
  64015. }
  64016. var index = scene.customRenderTargets.indexOf(this);
  64017. if (index >= 0) {
  64018. scene.customRenderTargets.splice(index, 1);
  64019. }
  64020. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64021. var camera = _a[_i];
  64022. index = camera.customRenderTargets.indexOf(this);
  64023. if (index >= 0) {
  64024. camera.customRenderTargets.splice(index, 1);
  64025. }
  64026. }
  64027. _super.prototype.dispose.call(this);
  64028. };
  64029. RenderTargetTexture.prototype._rebuild = function () {
  64030. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64031. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64032. }
  64033. if (this._postProcessManager) {
  64034. this._postProcessManager._rebuild();
  64035. }
  64036. };
  64037. /**
  64038. * Clear the info related to rendering groups preventing retention point in material dispose.
  64039. */
  64040. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64041. if (this._renderingManager) {
  64042. this._renderingManager.freeRenderingGroups();
  64043. }
  64044. };
  64045. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64046. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64047. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64048. return RenderTargetTexture;
  64049. }(BABYLON.Texture));
  64050. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64051. })(BABYLON || (BABYLON = {}));
  64052. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64053. var BABYLON;
  64054. (function (BABYLON) {
  64055. ;
  64056. var MultiRenderTarget = /** @class */ (function (_super) {
  64057. __extends(MultiRenderTarget, _super);
  64058. function MultiRenderTarget(name, size, count, scene, options) {
  64059. var _this = this;
  64060. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64061. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64062. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64063. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64064. _this._engine = scene.getEngine();
  64065. if (!_this.isSupported) {
  64066. _this.dispose();
  64067. return;
  64068. }
  64069. var types = [];
  64070. var samplingModes = [];
  64071. for (var i = 0; i < count; i++) {
  64072. if (options && options.types && options.types[i] !== undefined) {
  64073. types.push(options.types[i]);
  64074. }
  64075. else {
  64076. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64077. }
  64078. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64079. samplingModes.push(options.samplingModes[i]);
  64080. }
  64081. else {
  64082. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64083. }
  64084. }
  64085. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64086. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64087. _this._size = size;
  64088. _this._multiRenderTargetOptions = {
  64089. samplingModes: samplingModes,
  64090. generateMipMaps: generateMipMaps,
  64091. generateDepthBuffer: generateDepthBuffer,
  64092. generateStencilBuffer: generateStencilBuffer,
  64093. generateDepthTexture: generateDepthTexture,
  64094. types: types,
  64095. textureCount: count
  64096. };
  64097. _this._createInternalTextures();
  64098. _this._createTextures();
  64099. return _this;
  64100. }
  64101. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64102. get: function () {
  64103. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64104. },
  64105. enumerable: true,
  64106. configurable: true
  64107. });
  64108. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64109. get: function () {
  64110. return this._textures;
  64111. },
  64112. enumerable: true,
  64113. configurable: true
  64114. });
  64115. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64116. get: function () {
  64117. return this._textures[this._textures.length - 1];
  64118. },
  64119. enumerable: true,
  64120. configurable: true
  64121. });
  64122. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64123. set: function (wrap) {
  64124. if (this._textures) {
  64125. for (var i = 0; i < this._textures.length; i++) {
  64126. this._textures[i].wrapU = wrap;
  64127. }
  64128. }
  64129. },
  64130. enumerable: true,
  64131. configurable: true
  64132. });
  64133. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64134. set: function (wrap) {
  64135. if (this._textures) {
  64136. for (var i = 0; i < this._textures.length; i++) {
  64137. this._textures[i].wrapV = wrap;
  64138. }
  64139. }
  64140. },
  64141. enumerable: true,
  64142. configurable: true
  64143. });
  64144. MultiRenderTarget.prototype._rebuild = function () {
  64145. this.releaseInternalTextures();
  64146. this._createInternalTextures();
  64147. for (var i = 0; i < this._internalTextures.length; i++) {
  64148. var texture = this._textures[i];
  64149. texture._texture = this._internalTextures[i];
  64150. }
  64151. // Keeps references to frame buffer and stencil/depth buffer
  64152. this._texture = this._internalTextures[0];
  64153. };
  64154. MultiRenderTarget.prototype._createInternalTextures = function () {
  64155. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64156. };
  64157. MultiRenderTarget.prototype._createTextures = function () {
  64158. this._textures = [];
  64159. for (var i = 0; i < this._internalTextures.length; i++) {
  64160. var texture = new BABYLON.Texture(null, this.getScene());
  64161. texture._texture = this._internalTextures[i];
  64162. this._textures.push(texture);
  64163. }
  64164. // Keeps references to frame buffer and stencil/depth buffer
  64165. this._texture = this._internalTextures[0];
  64166. };
  64167. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64168. get: function () {
  64169. return this._samples;
  64170. },
  64171. set: function (value) {
  64172. if (this._samples === value) {
  64173. return;
  64174. }
  64175. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64176. },
  64177. enumerable: true,
  64178. configurable: true
  64179. });
  64180. MultiRenderTarget.prototype.resize = function (size) {
  64181. this.releaseInternalTextures();
  64182. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64183. this._createInternalTextures();
  64184. };
  64185. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64186. var _this = this;
  64187. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64188. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64189. });
  64190. };
  64191. MultiRenderTarget.prototype.dispose = function () {
  64192. this.releaseInternalTextures();
  64193. _super.prototype.dispose.call(this);
  64194. };
  64195. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64196. if (!this._internalTextures) {
  64197. return;
  64198. }
  64199. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64200. if (this._internalTextures[i] !== undefined) {
  64201. this._internalTextures[i].dispose();
  64202. this._internalTextures.splice(i, 1);
  64203. }
  64204. }
  64205. };
  64206. return MultiRenderTarget;
  64207. }(BABYLON.RenderTargetTexture));
  64208. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64209. })(BABYLON || (BABYLON = {}));
  64210. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64211. var BABYLON;
  64212. (function (BABYLON) {
  64213. var MirrorTexture = /** @class */ (function (_super) {
  64214. __extends(MirrorTexture, _super);
  64215. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64216. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64217. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64218. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64219. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64220. _this.scene = scene;
  64221. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64222. _this._transformMatrix = BABYLON.Matrix.Zero();
  64223. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64224. _this._adaptiveBlurKernel = 0;
  64225. _this._blurKernelX = 0;
  64226. _this._blurKernelY = 0;
  64227. _this._blurRatio = 1.0;
  64228. _this.ignoreCameraViewport = true;
  64229. _this._updateGammaSpace();
  64230. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64231. _this._updateGammaSpace;
  64232. });
  64233. _this.onBeforeRenderObservable.add(function () {
  64234. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64235. _this._savedViewMatrix = scene.getViewMatrix();
  64236. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64237. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64238. scene.clipPlane = _this.mirrorPlane;
  64239. scene.getEngine().cullBackFaces = false;
  64240. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64241. });
  64242. _this.onAfterRenderObservable.add(function () {
  64243. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64244. scene.getEngine().cullBackFaces = true;
  64245. scene._mirroredCameraPosition = null;
  64246. delete scene.clipPlane;
  64247. });
  64248. return _this;
  64249. }
  64250. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64251. get: function () {
  64252. return this._blurRatio;
  64253. },
  64254. set: function (value) {
  64255. if (this._blurRatio === value) {
  64256. return;
  64257. }
  64258. this._blurRatio = value;
  64259. this._preparePostProcesses();
  64260. },
  64261. enumerable: true,
  64262. configurable: true
  64263. });
  64264. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64265. set: function (value) {
  64266. this._adaptiveBlurKernel = value;
  64267. this._autoComputeBlurKernel();
  64268. },
  64269. enumerable: true,
  64270. configurable: true
  64271. });
  64272. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64273. set: function (value) {
  64274. this.blurKernelX = value;
  64275. this.blurKernelY = value;
  64276. },
  64277. enumerable: true,
  64278. configurable: true
  64279. });
  64280. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64281. get: function () {
  64282. return this._blurKernelX;
  64283. },
  64284. set: function (value) {
  64285. if (this._blurKernelX === value) {
  64286. return;
  64287. }
  64288. this._blurKernelX = value;
  64289. this._preparePostProcesses();
  64290. },
  64291. enumerable: true,
  64292. configurable: true
  64293. });
  64294. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64295. get: function () {
  64296. return this._blurKernelY;
  64297. },
  64298. set: function (value) {
  64299. if (this._blurKernelY === value) {
  64300. return;
  64301. }
  64302. this._blurKernelY = value;
  64303. this._preparePostProcesses();
  64304. },
  64305. enumerable: true,
  64306. configurable: true
  64307. });
  64308. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64309. var engine = this.getScene().getEngine();
  64310. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64311. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64312. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64313. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64314. };
  64315. MirrorTexture.prototype._onRatioRescale = function () {
  64316. if (this._sizeRatio) {
  64317. this.resize(this._initialSizeParameter);
  64318. if (!this._adaptiveBlurKernel) {
  64319. this._preparePostProcesses();
  64320. }
  64321. }
  64322. if (this._adaptiveBlurKernel) {
  64323. this._autoComputeBlurKernel();
  64324. }
  64325. };
  64326. MirrorTexture.prototype._updateGammaSpace = function () {
  64327. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64328. };
  64329. MirrorTexture.prototype._preparePostProcesses = function () {
  64330. this.clearPostProcesses(true);
  64331. if (this._blurKernelX && this._blurKernelY) {
  64332. var engine = this.getScene().getEngine();
  64333. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64334. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  64335. this._blurX.autoClear = false;
  64336. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64337. this._blurX.inputTexture = this._texture;
  64338. }
  64339. else {
  64340. this._blurX.alwaysForcePOT = true;
  64341. }
  64342. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  64343. this._blurY.autoClear = false;
  64344. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64345. this.addPostProcess(this._blurX);
  64346. this.addPostProcess(this._blurY);
  64347. }
  64348. else {
  64349. if (this._blurY) {
  64350. this.removePostProcess(this._blurY);
  64351. this._blurY.dispose();
  64352. this._blurY = null;
  64353. }
  64354. if (this._blurX) {
  64355. this.removePostProcess(this._blurX);
  64356. this._blurX.dispose();
  64357. this._blurX = null;
  64358. }
  64359. }
  64360. };
  64361. MirrorTexture.prototype.clone = function () {
  64362. var scene = this.getScene();
  64363. if (!scene) {
  64364. return this;
  64365. }
  64366. var textureSize = this.getSize();
  64367. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64368. // Base texture
  64369. newTexture.hasAlpha = this.hasAlpha;
  64370. newTexture.level = this.level;
  64371. // Mirror Texture
  64372. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64373. if (this.renderList) {
  64374. newTexture.renderList = this.renderList.slice(0);
  64375. }
  64376. return newTexture;
  64377. };
  64378. MirrorTexture.prototype.serialize = function () {
  64379. if (!this.name) {
  64380. return null;
  64381. }
  64382. var serializationObject = _super.prototype.serialize.call(this);
  64383. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64384. return serializationObject;
  64385. };
  64386. MirrorTexture.prototype.dispose = function () {
  64387. _super.prototype.dispose.call(this);
  64388. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64389. };
  64390. return MirrorTexture;
  64391. }(BABYLON.RenderTargetTexture));
  64392. BABYLON.MirrorTexture = MirrorTexture;
  64393. })(BABYLON || (BABYLON = {}));
  64394. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64395. var BABYLON;
  64396. (function (BABYLON) {
  64397. /**
  64398. * Creates a refraction texture used by refraction channel of the standard material.
  64399. * @param name the texture name
  64400. * @param size size of the underlying texture
  64401. * @param scene root scene
  64402. */
  64403. var RefractionTexture = /** @class */ (function (_super) {
  64404. __extends(RefractionTexture, _super);
  64405. function RefractionTexture(name, size, scene, generateMipMaps) {
  64406. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64407. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64408. _this.depth = 2.0;
  64409. _this.onBeforeRenderObservable.add(function () {
  64410. scene.clipPlane = _this.refractionPlane;
  64411. });
  64412. _this.onAfterRenderObservable.add(function () {
  64413. delete scene.clipPlane;
  64414. });
  64415. return _this;
  64416. }
  64417. RefractionTexture.prototype.clone = function () {
  64418. var scene = this.getScene();
  64419. if (!scene) {
  64420. return this;
  64421. }
  64422. var textureSize = this.getSize();
  64423. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64424. // Base texture
  64425. newTexture.hasAlpha = this.hasAlpha;
  64426. newTexture.level = this.level;
  64427. // Refraction Texture
  64428. newTexture.refractionPlane = this.refractionPlane.clone();
  64429. if (this.renderList) {
  64430. newTexture.renderList = this.renderList.slice(0);
  64431. }
  64432. newTexture.depth = this.depth;
  64433. return newTexture;
  64434. };
  64435. RefractionTexture.prototype.serialize = function () {
  64436. if (!this.name) {
  64437. return null;
  64438. }
  64439. var serializationObject = _super.prototype.serialize.call(this);
  64440. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64441. serializationObject.depth = this.depth;
  64442. return serializationObject;
  64443. };
  64444. return RefractionTexture;
  64445. }(BABYLON.RenderTargetTexture));
  64446. BABYLON.RefractionTexture = RefractionTexture;
  64447. })(BABYLON || (BABYLON = {}));
  64448. //# sourceMappingURL=babylon.refractionTexture.js.map
  64449. var BABYLON;
  64450. (function (BABYLON) {
  64451. /**
  64452. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64453. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64454. */
  64455. var DynamicTexture = /** @class */ (function (_super) {
  64456. __extends(DynamicTexture, _super);
  64457. /**
  64458. * Creates a {BABYLON.DynamicTexture}
  64459. * @param name defines the name of the texture
  64460. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  64461. * @param scene defines the scene where you want the texture
  64462. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64463. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64464. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64465. */
  64466. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64467. if (scene === void 0) { scene = null; }
  64468. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64469. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64470. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64471. _this.name = name;
  64472. _this._engine = _this.getScene().getEngine();
  64473. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64474. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64475. _this._generateMipMaps = generateMipMaps;
  64476. if (options.getContext) {
  64477. _this._canvas = options;
  64478. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64479. }
  64480. else {
  64481. _this._canvas = document.createElement("canvas");
  64482. if (options.width || options.width === 0) {
  64483. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64484. }
  64485. else {
  64486. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64487. }
  64488. }
  64489. var textureSize = _this.getSize();
  64490. _this._canvas.width = textureSize.width;
  64491. _this._canvas.height = textureSize.height;
  64492. _this._context = _this._canvas.getContext("2d");
  64493. return _this;
  64494. }
  64495. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64496. /**
  64497. * Gets the current state of canRescale
  64498. */
  64499. get: function () {
  64500. return true;
  64501. },
  64502. enumerable: true,
  64503. configurable: true
  64504. });
  64505. DynamicTexture.prototype._recreate = function (textureSize) {
  64506. this._canvas.width = textureSize.width;
  64507. this._canvas.height = textureSize.height;
  64508. this.releaseInternalTexture();
  64509. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64510. };
  64511. /**
  64512. * Scales the texture
  64513. * @param ratio the scale factor to apply to both width and height
  64514. */
  64515. DynamicTexture.prototype.scale = function (ratio) {
  64516. var textureSize = this.getSize();
  64517. textureSize.width *= ratio;
  64518. textureSize.height *= ratio;
  64519. this._recreate(textureSize);
  64520. };
  64521. /**
  64522. * Resizes the texture
  64523. * @param width the new width
  64524. * @param height the new height
  64525. */
  64526. DynamicTexture.prototype.scaleTo = function (width, height) {
  64527. var textureSize = this.getSize();
  64528. textureSize.width = width;
  64529. textureSize.height = height;
  64530. this._recreate(textureSize);
  64531. };
  64532. /**
  64533. * Gets the context of the canvas used by the texture
  64534. * @returns the canvas context of the dynamic texture
  64535. */
  64536. DynamicTexture.prototype.getContext = function () {
  64537. return this._context;
  64538. };
  64539. /**
  64540. * Clears the texture
  64541. */
  64542. DynamicTexture.prototype.clear = function () {
  64543. var size = this.getSize();
  64544. this._context.fillRect(0, 0, size.width, size.height);
  64545. };
  64546. /**
  64547. * Updates the texture
  64548. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64549. */
  64550. DynamicTexture.prototype.update = function (invertY) {
  64551. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64552. };
  64553. /**
  64554. * Draws text onto the texture
  64555. * @param text defines the text to be drawn
  64556. * @param x defines the placement of the text from the left
  64557. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64558. * @param font defines the font to be used with font-style, font-size, font-name
  64559. * @param color defines the color used for the text
  64560. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64561. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64562. * @param update defines whether texture is immediately update (default is true)
  64563. */
  64564. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64565. if (update === void 0) { update = true; }
  64566. var size = this.getSize();
  64567. if (clearColor) {
  64568. this._context.fillStyle = clearColor;
  64569. this._context.fillRect(0, 0, size.width, size.height);
  64570. }
  64571. this._context.font = font;
  64572. if (x === null || x === undefined) {
  64573. var textSize = this._context.measureText(text);
  64574. x = (size.width - textSize.width) / 2;
  64575. }
  64576. if (y === null || y === undefined) {
  64577. var fontSize = parseInt((font.replace(/\D/g, '')));
  64578. y = (size.height / 2) + (fontSize / 3.65);
  64579. }
  64580. this._context.fillStyle = color;
  64581. this._context.fillText(text, x, y);
  64582. if (update) {
  64583. this.update(invertY);
  64584. }
  64585. };
  64586. /**
  64587. * Clones the texture
  64588. * @returns the clone of the texture.
  64589. */
  64590. DynamicTexture.prototype.clone = function () {
  64591. var scene = this.getScene();
  64592. if (!scene) {
  64593. return this;
  64594. }
  64595. var textureSize = this.getSize();
  64596. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64597. // Base texture
  64598. newTexture.hasAlpha = this.hasAlpha;
  64599. newTexture.level = this.level;
  64600. // Dynamic Texture
  64601. newTexture.wrapU = this.wrapU;
  64602. newTexture.wrapV = this.wrapV;
  64603. return newTexture;
  64604. };
  64605. /** @hidden */
  64606. DynamicTexture.prototype._rebuild = function () {
  64607. this.update();
  64608. };
  64609. return DynamicTexture;
  64610. }(BABYLON.Texture));
  64611. BABYLON.DynamicTexture = DynamicTexture;
  64612. })(BABYLON || (BABYLON = {}));
  64613. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64614. var BABYLON;
  64615. (function (BABYLON) {
  64616. var VideoTexture = /** @class */ (function (_super) {
  64617. __extends(VideoTexture, _super);
  64618. /**
  64619. * Creates a video texture.
  64620. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64621. * @param {string | null} name optional name, will detect from video source, if not defined
  64622. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64623. * @param {BABYLON.Scene} scene is obviously the current scene.
  64624. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64625. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64626. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64627. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64628. */
  64629. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64630. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64631. if (invertY === void 0) { invertY = false; }
  64632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64633. if (settings === void 0) { settings = {
  64634. autoPlay: true,
  64635. loop: true,
  64636. autoUpdateTexture: true,
  64637. }; }
  64638. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64639. _this._stillImageCaptured = false;
  64640. _this._createInternalTexture = function () {
  64641. if (_this._texture != null) {
  64642. return;
  64643. }
  64644. if (!_this._engine.needPOTTextures ||
  64645. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64646. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64647. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64648. }
  64649. else {
  64650. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64651. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64652. _this._generateMipMaps = false;
  64653. }
  64654. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64655. if (!_this.video.autoplay) {
  64656. var oldHandler_1 = _this.video.onplaying;
  64657. _this.video.onplaying = function () {
  64658. _this.video.onplaying = oldHandler_1;
  64659. _this._texture.isReady = true;
  64660. _this._updateInternalTexture();
  64661. _this.video.pause();
  64662. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64663. _this.onLoadObservable.notifyObservers(_this);
  64664. }
  64665. };
  64666. _this.video.play();
  64667. }
  64668. else {
  64669. _this._texture.isReady = true;
  64670. _this._updateInternalTexture();
  64671. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64672. _this.onLoadObservable.notifyObservers(_this);
  64673. }
  64674. }
  64675. };
  64676. _this.reset = function () {
  64677. if (_this._texture == null) {
  64678. return;
  64679. }
  64680. _this._texture.dispose();
  64681. _this._texture = null;
  64682. };
  64683. _this._updateInternalTexture = function (e) {
  64684. if (_this._texture == null || !_this._texture.isReady) {
  64685. return;
  64686. }
  64687. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64688. return;
  64689. }
  64690. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64691. };
  64692. _this._engine = _this.getScene().getEngine();
  64693. _this._generateMipMaps = generateMipMaps;
  64694. _this._samplingMode = samplingMode;
  64695. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64696. _this.name = name || _this._getName(src);
  64697. _this.video = _this._getVideo(src);
  64698. if (settings.autoPlay !== undefined) {
  64699. _this.video.autoplay = settings.autoPlay;
  64700. }
  64701. if (settings.loop !== undefined) {
  64702. _this.video.loop = settings.loop;
  64703. }
  64704. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64705. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64706. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64707. _this.video.addEventListener("emptied", _this.reset);
  64708. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64709. _this._createInternalTexture();
  64710. }
  64711. return _this;
  64712. }
  64713. VideoTexture.prototype._getName = function (src) {
  64714. if (src instanceof HTMLVideoElement) {
  64715. return src.currentSrc;
  64716. }
  64717. if (typeof src === "object") {
  64718. return src.toString();
  64719. }
  64720. return src;
  64721. };
  64722. ;
  64723. VideoTexture.prototype._getVideo = function (src) {
  64724. if (src instanceof HTMLVideoElement) {
  64725. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64726. return src;
  64727. }
  64728. var video = document.createElement("video");
  64729. if (typeof src === "string") {
  64730. BABYLON.Tools.SetCorsBehavior(src, video);
  64731. video.src = src;
  64732. }
  64733. else {
  64734. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64735. src.forEach(function (url) {
  64736. var source = document.createElement("source");
  64737. source.src = url;
  64738. video.appendChild(source);
  64739. });
  64740. }
  64741. return video;
  64742. };
  64743. ;
  64744. /**
  64745. * Internal method to initiate `update`.
  64746. */
  64747. VideoTexture.prototype._rebuild = function () {
  64748. this.update();
  64749. };
  64750. /**
  64751. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64752. */
  64753. VideoTexture.prototype.update = function () {
  64754. if (!this.autoUpdateTexture) {
  64755. // Expecting user to call `updateTexture` manually
  64756. return;
  64757. }
  64758. this.updateTexture(true);
  64759. };
  64760. /**
  64761. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64762. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64763. */
  64764. VideoTexture.prototype.updateTexture = function (isVisible) {
  64765. if (!isVisible) {
  64766. return;
  64767. }
  64768. if (this.video.paused && this._stillImageCaptured) {
  64769. return;
  64770. }
  64771. this._stillImageCaptured = true;
  64772. this._updateInternalTexture();
  64773. };
  64774. /**
  64775. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64776. * @param url New url.
  64777. */
  64778. VideoTexture.prototype.updateURL = function (url) {
  64779. this.video.src = url;
  64780. };
  64781. VideoTexture.prototype.dispose = function () {
  64782. _super.prototype.dispose.call(this);
  64783. this.video.removeEventListener("canplay", this._createInternalTexture);
  64784. this.video.removeEventListener("paused", this._updateInternalTexture);
  64785. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64786. this.video.removeEventListener("emptied", this.reset);
  64787. this.video.pause();
  64788. };
  64789. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64790. var video = document.createElement("video");
  64791. var constraintsDeviceId;
  64792. if (constraints && constraints.deviceId) {
  64793. constraintsDeviceId = {
  64794. exact: constraints.deviceId,
  64795. };
  64796. }
  64797. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64798. if (navigator.mediaDevices) {
  64799. navigator.mediaDevices.getUserMedia({ video: constraints })
  64800. .then(function (stream) {
  64801. if (video.mozSrcObject !== undefined) {
  64802. // hack for Firefox < 19
  64803. video.mozSrcObject = stream;
  64804. }
  64805. else {
  64806. video.srcObject = stream;
  64807. }
  64808. var onPlaying = function () {
  64809. if (onReady) {
  64810. onReady(new VideoTexture("video", video, scene, true, true));
  64811. }
  64812. video.removeEventListener("playing", onPlaying);
  64813. };
  64814. video.addEventListener("playing", onPlaying);
  64815. video.play();
  64816. })
  64817. .catch(function (err) {
  64818. BABYLON.Tools.Error(err.name);
  64819. });
  64820. }
  64821. else {
  64822. navigator.getUserMedia =
  64823. navigator.getUserMedia ||
  64824. navigator.webkitGetUserMedia ||
  64825. navigator.mozGetUserMedia ||
  64826. navigator.msGetUserMedia;
  64827. if (navigator.getUserMedia) {
  64828. navigator.getUserMedia({
  64829. video: {
  64830. deviceId: constraintsDeviceId,
  64831. width: {
  64832. min: (constraints && constraints.minWidth) || 256,
  64833. max: (constraints && constraints.maxWidth) || 640,
  64834. },
  64835. height: {
  64836. min: (constraints && constraints.minHeight) || 256,
  64837. max: (constraints && constraints.maxHeight) || 480,
  64838. },
  64839. },
  64840. }, function (stream) {
  64841. if (video.mozSrcObject !== undefined) {
  64842. // hack for Firefox < 19
  64843. video.mozSrcObject = stream;
  64844. }
  64845. else {
  64846. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64847. }
  64848. video.play();
  64849. if (onReady) {
  64850. onReady(new VideoTexture("video", video, scene, true, true));
  64851. }
  64852. }, function (e) {
  64853. BABYLON.Tools.Error(e.name);
  64854. });
  64855. }
  64856. }
  64857. };
  64858. return VideoTexture;
  64859. }(BABYLON.Texture));
  64860. BABYLON.VideoTexture = VideoTexture;
  64861. })(BABYLON || (BABYLON = {}));
  64862. //# sourceMappingURL=babylon.videoTexture.js.map
  64863. var BABYLON;
  64864. (function (BABYLON) {
  64865. var RawTexture = /** @class */ (function (_super) {
  64866. __extends(RawTexture, _super);
  64867. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64868. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64869. if (invertY === void 0) { invertY = false; }
  64870. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64871. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64872. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64873. _this.format = format;
  64874. _this._engine = scene.getEngine();
  64875. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64876. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64877. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64878. return _this;
  64879. }
  64880. RawTexture.prototype.update = function (data) {
  64881. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64882. };
  64883. // Statics
  64884. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64885. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64886. if (invertY === void 0) { invertY = false; }
  64887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64888. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64889. };
  64890. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64891. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64892. if (invertY === void 0) { invertY = false; }
  64893. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64894. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64895. };
  64896. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64897. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64898. if (invertY === void 0) { invertY = false; }
  64899. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64900. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64901. };
  64902. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64903. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64904. if (invertY === void 0) { invertY = false; }
  64905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64906. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64907. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64908. };
  64909. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64910. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64911. if (invertY === void 0) { invertY = false; }
  64912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64913. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64914. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64915. };
  64916. return RawTexture;
  64917. }(BABYLON.Texture));
  64918. BABYLON.RawTexture = RawTexture;
  64919. })(BABYLON || (BABYLON = {}));
  64920. //# sourceMappingURL=babylon.rawTexture.js.map
  64921. var BABYLON;
  64922. (function (BABYLON) {
  64923. /**
  64924. * Class used to store 3D textures containing user data
  64925. */
  64926. var RawTexture3D = /** @class */ (function (_super) {
  64927. __extends(RawTexture3D, _super);
  64928. /**
  64929. * Create a new RawTexture3D
  64930. * @param data defines the data of the texture
  64931. * @param width defines the width of the texture
  64932. * @param height defines the height of the texture
  64933. * @param depth defines the depth of the texture
  64934. * @param format defines the texture format to use
  64935. * @param scene defines the hosting scene
  64936. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64937. * @param invertY defines if texture must be stored with Y axis inverted
  64938. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64939. */
  64940. function RawTexture3D(data, width, height, depth,
  64941. /** Gets or sets the texture format to use*/
  64942. format, scene, generateMipMaps, invertY, samplingMode) {
  64943. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64944. if (invertY === void 0) { invertY = false; }
  64945. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64946. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64947. _this.format = format;
  64948. _this._engine = scene.getEngine();
  64949. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64950. _this.is3D = true;
  64951. return _this;
  64952. }
  64953. /**
  64954. * Update the texture with new data
  64955. * @param data defines the data to store in the texture
  64956. */
  64957. RawTexture3D.prototype.update = function (data) {
  64958. if (!this._texture) {
  64959. return;
  64960. }
  64961. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64962. };
  64963. return RawTexture3D;
  64964. }(BABYLON.Texture));
  64965. BABYLON.RawTexture3D = RawTexture3D;
  64966. })(BABYLON || (BABYLON = {}));
  64967. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64968. var BABYLON;
  64969. (function (BABYLON) {
  64970. /**
  64971. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64972. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64973. */
  64974. var PostProcess = /** @class */ (function () {
  64975. /**
  64976. * Creates a new instance PostProcess
  64977. * @param name The name of the PostProcess.
  64978. * @param fragmentUrl The url of the fragment shader to be used.
  64979. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64980. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64981. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64982. * @param camera The camera to apply the render pass to.
  64983. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64984. * @param engine The engine which the post process will be applied. (default: current engine)
  64985. * @param reusable If the post process can be reused on the same frame. (default: false)
  64986. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64987. * @param textureType Type of textures used when performing the post process. (default: 0)
  64988. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64989. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  64990. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64991. */
  64992. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64994. if (defines === void 0) { defines = null; }
  64995. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64996. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64997. if (blockCompilation === void 0) { blockCompilation = false; }
  64998. this.name = name;
  64999. /**
  65000. * Width of the texture to apply the post process on
  65001. */
  65002. this.width = -1;
  65003. /**
  65004. * Height of the texture to apply the post process on
  65005. */
  65006. this.height = -1;
  65007. /**
  65008. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65009. */
  65010. this._outputTexture = null;
  65011. /**
  65012. * If the buffer needs to be cleared before applying the post process. (default: true)
  65013. * Should be set to false if shader will overwrite all previous pixels.
  65014. */
  65015. this.autoClear = true;
  65016. /**
  65017. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65018. */
  65019. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65020. /**
  65021. * Animations to be used for the post processing
  65022. */
  65023. this.animations = new Array();
  65024. /**
  65025. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65026. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65027. */
  65028. this.enablePixelPerfectMode = false;
  65029. /**
  65030. * Force the postprocess to be applied without taking in account viewport
  65031. */
  65032. this.forceFullscreenViewport = true;
  65033. /**
  65034. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65035. */
  65036. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65037. /**
  65038. * Force textures to be a power of two (default: false)
  65039. */
  65040. this.alwaysForcePOT = false;
  65041. /**
  65042. * Number of sample textures (default: 1)
  65043. */
  65044. this.samples = 1;
  65045. /**
  65046. * Modify the scale of the post process to be the same as the viewport (default: false)
  65047. */
  65048. this.adaptScaleToCurrentViewport = false;
  65049. this._reusable = false;
  65050. /**
  65051. * Smart array of input and output textures for the post process.
  65052. */
  65053. this._textures = new BABYLON.SmartArray(2);
  65054. /**
  65055. * The index in _textures that corresponds to the output texture.
  65056. */
  65057. this._currentRenderTextureInd = 0;
  65058. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65059. this._texelSize = BABYLON.Vector2.Zero();
  65060. // Events
  65061. /**
  65062. * An event triggered when the postprocess is activated.
  65063. */
  65064. this.onActivateObservable = new BABYLON.Observable();
  65065. /**
  65066. * An event triggered when the postprocess changes its size.
  65067. */
  65068. this.onSizeChangedObservable = new BABYLON.Observable();
  65069. /**
  65070. * An event triggered when the postprocess applies its effect.
  65071. */
  65072. this.onApplyObservable = new BABYLON.Observable();
  65073. /**
  65074. * An event triggered before rendering the postprocess
  65075. */
  65076. this.onBeforeRenderObservable = new BABYLON.Observable();
  65077. /**
  65078. * An event triggered after rendering the postprocess
  65079. */
  65080. this.onAfterRenderObservable = new BABYLON.Observable();
  65081. if (camera != null) {
  65082. this._camera = camera;
  65083. this._scene = camera.getScene();
  65084. camera.attachPostProcess(this);
  65085. this._engine = this._scene.getEngine();
  65086. this._scene.postProcesses.push(this);
  65087. }
  65088. else if (engine) {
  65089. this._engine = engine;
  65090. this._engine.postProcesses.push(this);
  65091. }
  65092. this._options = options;
  65093. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65094. this._reusable = reusable || false;
  65095. this._textureType = textureType;
  65096. this._samplers = samplers || [];
  65097. this._samplers.push("textureSampler");
  65098. this._fragmentUrl = fragmentUrl;
  65099. this._vertexUrl = vertexUrl;
  65100. this._parameters = parameters || [];
  65101. this._parameters.push("scale");
  65102. this._indexParameters = indexParameters;
  65103. if (!blockCompilation) {
  65104. this.updateEffect(defines);
  65105. }
  65106. }
  65107. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65108. /**
  65109. * A function that is added to the onActivateObservable
  65110. */
  65111. set: function (callback) {
  65112. if (this._onActivateObserver) {
  65113. this.onActivateObservable.remove(this._onActivateObserver);
  65114. }
  65115. if (callback) {
  65116. this._onActivateObserver = this.onActivateObservable.add(callback);
  65117. }
  65118. },
  65119. enumerable: true,
  65120. configurable: true
  65121. });
  65122. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65123. /**
  65124. * A function that is added to the onSizeChangedObservable
  65125. */
  65126. set: function (callback) {
  65127. if (this._onSizeChangedObserver) {
  65128. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65129. }
  65130. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65131. },
  65132. enumerable: true,
  65133. configurable: true
  65134. });
  65135. Object.defineProperty(PostProcess.prototype, "onApply", {
  65136. /**
  65137. * A function that is added to the onApplyObservable
  65138. */
  65139. set: function (callback) {
  65140. if (this._onApplyObserver) {
  65141. this.onApplyObservable.remove(this._onApplyObserver);
  65142. }
  65143. this._onApplyObserver = this.onApplyObservable.add(callback);
  65144. },
  65145. enumerable: true,
  65146. configurable: true
  65147. });
  65148. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65149. /**
  65150. * A function that is added to the onBeforeRenderObservable
  65151. */
  65152. set: function (callback) {
  65153. if (this._onBeforeRenderObserver) {
  65154. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65155. }
  65156. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65157. },
  65158. enumerable: true,
  65159. configurable: true
  65160. });
  65161. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65162. /**
  65163. * A function that is added to the onAfterRenderObservable
  65164. */
  65165. set: function (callback) {
  65166. if (this._onAfterRenderObserver) {
  65167. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65168. }
  65169. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65170. },
  65171. enumerable: true,
  65172. configurable: true
  65173. });
  65174. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65175. /**
  65176. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  65177. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65178. */
  65179. get: function () {
  65180. return this._textures.data[this._currentRenderTextureInd];
  65181. },
  65182. set: function (value) {
  65183. this._forcedOutputTexture = value;
  65184. },
  65185. enumerable: true,
  65186. configurable: true
  65187. });
  65188. /**
  65189. * Gets the camera which post process is applied to.
  65190. * @returns The camera the post process is applied to.
  65191. */
  65192. PostProcess.prototype.getCamera = function () {
  65193. return this._camera;
  65194. };
  65195. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65196. /**
  65197. * Gets the texel size of the postprocess.
  65198. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65199. */
  65200. get: function () {
  65201. if (this._shareOutputWithPostProcess) {
  65202. return this._shareOutputWithPostProcess.texelSize;
  65203. }
  65204. if (this._forcedOutputTexture) {
  65205. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65206. }
  65207. return this._texelSize;
  65208. },
  65209. enumerable: true,
  65210. configurable: true
  65211. });
  65212. /**
  65213. * Gets the engine which this post process belongs to.
  65214. * @returns The engine the post process was enabled with.
  65215. */
  65216. PostProcess.prototype.getEngine = function () {
  65217. return this._engine;
  65218. };
  65219. /**
  65220. * The effect that is created when initializing the post process.
  65221. * @returns The created effect corrisponding the the postprocess.
  65222. */
  65223. PostProcess.prototype.getEffect = function () {
  65224. return this._effect;
  65225. };
  65226. /**
  65227. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65228. * @param postProcess The post process to share the output with.
  65229. * @returns This post process.
  65230. */
  65231. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65232. this._disposeTextures();
  65233. this._shareOutputWithPostProcess = postProcess;
  65234. return this;
  65235. };
  65236. /**
  65237. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65238. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65239. */
  65240. PostProcess.prototype.useOwnOutput = function () {
  65241. if (this._textures.length == 0) {
  65242. this._textures = new BABYLON.SmartArray(2);
  65243. }
  65244. this._shareOutputWithPostProcess = null;
  65245. };
  65246. /**
  65247. * Updates the effect with the current post process compile time values and recompiles the shader.
  65248. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65249. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65250. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65251. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  65252. * @param onCompiled Called when the shader has been compiled.
  65253. * @param onError Called if there is an error when compiling a shader.
  65254. */
  65255. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65256. if (defines === void 0) { defines = null; }
  65257. if (uniforms === void 0) { uniforms = null; }
  65258. if (samplers === void 0) { samplers = null; }
  65259. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : "", undefined, onCompiled, onError, indexParameters || this._indexParameters);
  65260. };
  65261. /**
  65262. * The post process is reusable if it can be used multiple times within one frame.
  65263. * @returns If the post process is reusable
  65264. */
  65265. PostProcess.prototype.isReusable = function () {
  65266. return this._reusable;
  65267. };
  65268. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65269. PostProcess.prototype.markTextureDirty = function () {
  65270. this.width = -1;
  65271. };
  65272. /**
  65273. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65274. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  65275. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65276. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65277. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65278. * @returns The target texture that was bound to be written to.
  65279. */
  65280. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65281. var _this = this;
  65282. if (sourceTexture === void 0) { sourceTexture = null; }
  65283. camera = camera || this._camera;
  65284. var scene = camera.getScene();
  65285. var engine = scene.getEngine();
  65286. var maxSize = engine.getCaps().maxTextureSize;
  65287. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65288. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65289. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  65290. var webVRCamera = camera.parent;
  65291. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65292. requiredWidth /= 2;
  65293. }
  65294. var desiredWidth = (this._options.width || requiredWidth);
  65295. var desiredHeight = this._options.height || requiredHeight;
  65296. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65297. if (this.adaptScaleToCurrentViewport) {
  65298. var currentViewport = engine.currentViewport;
  65299. if (currentViewport) {
  65300. desiredWidth *= currentViewport.width;
  65301. desiredHeight *= currentViewport.height;
  65302. }
  65303. }
  65304. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65305. if (!this._options.width) {
  65306. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65307. }
  65308. if (!this._options.height) {
  65309. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65310. }
  65311. }
  65312. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65313. if (this._textures.length > 0) {
  65314. for (var i = 0; i < this._textures.length; i++) {
  65315. this._engine._releaseTexture(this._textures.data[i]);
  65316. }
  65317. this._textures.reset();
  65318. }
  65319. this.width = desiredWidth;
  65320. this.height = desiredHeight;
  65321. var textureSize = { width: this.width, height: this.height };
  65322. var textureOptions = {
  65323. generateMipMaps: false,
  65324. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65325. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65326. samplingMode: this.renderTargetSamplingMode,
  65327. type: this._textureType
  65328. };
  65329. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65330. if (this._reusable) {
  65331. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65332. }
  65333. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65334. this.onSizeChangedObservable.notifyObservers(this);
  65335. }
  65336. this._textures.forEach(function (texture) {
  65337. if (texture.samples !== _this.samples) {
  65338. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65339. }
  65340. });
  65341. }
  65342. var target;
  65343. if (this._shareOutputWithPostProcess) {
  65344. target = this._shareOutputWithPostProcess.inputTexture;
  65345. }
  65346. else if (this._forcedOutputTexture) {
  65347. target = this._forcedOutputTexture;
  65348. this.width = this._forcedOutputTexture.width;
  65349. this.height = this._forcedOutputTexture.height;
  65350. }
  65351. else {
  65352. target = this.inputTexture;
  65353. }
  65354. // Bind the input of this post process to be used as the output of the previous post process.
  65355. if (this.enablePixelPerfectMode) {
  65356. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65357. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65358. }
  65359. else {
  65360. this._scaleRatio.copyFromFloats(1, 1);
  65361. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65362. }
  65363. this.onActivateObservable.notifyObservers(camera);
  65364. // Clear
  65365. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65366. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65367. }
  65368. if (this._reusable) {
  65369. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65370. }
  65371. return target;
  65372. };
  65373. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65374. /**
  65375. * If the post process is supported.
  65376. */
  65377. get: function () {
  65378. return this._effect.isSupported;
  65379. },
  65380. enumerable: true,
  65381. configurable: true
  65382. });
  65383. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65384. /**
  65385. * The aspect ratio of the output texture.
  65386. */
  65387. get: function () {
  65388. if (this._shareOutputWithPostProcess) {
  65389. return this._shareOutputWithPostProcess.aspectRatio;
  65390. }
  65391. if (this._forcedOutputTexture) {
  65392. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65393. }
  65394. return this.width / this.height;
  65395. },
  65396. enumerable: true,
  65397. configurable: true
  65398. });
  65399. /**
  65400. * Get a value indicating if the post-process is ready to be used
  65401. * @returns true if the post-process is ready (shader is compiled)
  65402. */
  65403. PostProcess.prototype.isReady = function () {
  65404. return this._effect && this._effect.isReady();
  65405. };
  65406. /**
  65407. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65408. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65409. */
  65410. PostProcess.prototype.apply = function () {
  65411. // Check
  65412. if (!this._effect || !this._effect.isReady())
  65413. return null;
  65414. // States
  65415. this._engine.enableEffect(this._effect);
  65416. this._engine.setState(false);
  65417. this._engine.setDepthBuffer(false);
  65418. this._engine.setDepthWrite(false);
  65419. // Alpha
  65420. this._engine.setAlphaMode(this.alphaMode);
  65421. if (this.alphaConstants) {
  65422. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65423. }
  65424. // Bind the output texture of the preivous post process as the input to this post process.
  65425. var source;
  65426. if (this._shareOutputWithPostProcess) {
  65427. source = this._shareOutputWithPostProcess.inputTexture;
  65428. }
  65429. else if (this._forcedOutputTexture) {
  65430. source = this._forcedOutputTexture;
  65431. }
  65432. else {
  65433. source = this.inputTexture;
  65434. }
  65435. this._effect._bindTexture("textureSampler", source);
  65436. // Parameters
  65437. this._effect.setVector2("scale", this._scaleRatio);
  65438. this.onApplyObservable.notifyObservers(this._effect);
  65439. return this._effect;
  65440. };
  65441. PostProcess.prototype._disposeTextures = function () {
  65442. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65443. return;
  65444. }
  65445. if (this._textures.length > 0) {
  65446. for (var i = 0; i < this._textures.length; i++) {
  65447. this._engine._releaseTexture(this._textures.data[i]);
  65448. }
  65449. }
  65450. this._textures.dispose();
  65451. };
  65452. /**
  65453. * Disposes the post process.
  65454. * @param camera The camera to dispose the post process on.
  65455. */
  65456. PostProcess.prototype.dispose = function (camera) {
  65457. camera = camera || this._camera;
  65458. this._disposeTextures();
  65459. if (this._scene) {
  65460. var index_1 = this._scene.postProcesses.indexOf(this);
  65461. if (index_1 !== -1) {
  65462. this._scene.postProcesses.splice(index_1, 1);
  65463. }
  65464. }
  65465. else {
  65466. var index_2 = this._engine.postProcesses.indexOf(this);
  65467. if (index_2 !== -1) {
  65468. this._engine.postProcesses.splice(index_2, 1);
  65469. }
  65470. }
  65471. if (!camera) {
  65472. return;
  65473. }
  65474. camera.detachPostProcess(this);
  65475. var index = camera._postProcesses.indexOf(this);
  65476. if (index === 0 && camera._postProcesses.length > 0) {
  65477. var firstPostProcess = this._camera._getFirstPostProcess();
  65478. if (firstPostProcess) {
  65479. firstPostProcess.markTextureDirty();
  65480. }
  65481. }
  65482. this.onActivateObservable.clear();
  65483. this.onAfterRenderObservable.clear();
  65484. this.onApplyObservable.clear();
  65485. this.onBeforeRenderObservable.clear();
  65486. this.onSizeChangedObservable.clear();
  65487. };
  65488. return PostProcess;
  65489. }());
  65490. BABYLON.PostProcess = PostProcess;
  65491. })(BABYLON || (BABYLON = {}));
  65492. //# sourceMappingURL=babylon.postProcess.js.map
  65493. var BABYLON;
  65494. (function (BABYLON) {
  65495. var PassPostProcess = /** @class */ (function (_super) {
  65496. __extends(PassPostProcess, _super);
  65497. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65498. if (camera === void 0) { camera = null; }
  65499. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65500. if (blockCompilation === void 0) { blockCompilation = false; }
  65501. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65502. }
  65503. return PassPostProcess;
  65504. }(BABYLON.PostProcess));
  65505. BABYLON.PassPostProcess = PassPostProcess;
  65506. })(BABYLON || (BABYLON = {}));
  65507. //# sourceMappingURL=babylon.passPostProcess.js.map
  65508. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65509. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65510. s = arguments[i];
  65511. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65512. t[p] = s[p];
  65513. }
  65514. return t;
  65515. };
  65516. var BABYLON;
  65517. (function (BABYLON) {
  65518. /**
  65519. * Default implementation IShadowGenerator.
  65520. * This is the main object responsible of generating shadows in the framework.
  65521. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65522. */
  65523. var ShadowGenerator = /** @class */ (function () {
  65524. /**
  65525. * Creates a ShadowGenerator object.
  65526. * A ShadowGenerator is the required tool to use the shadows.
  65527. * Each light casting shadows needs to use its own ShadowGenerator.
  65528. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65529. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65530. * @param light The light object generating the shadows.
  65531. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  65532. */
  65533. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65534. this._bias = 0.00005;
  65535. this._normalBias = 0;
  65536. this._blurBoxOffset = 1;
  65537. this._blurScale = 2;
  65538. this._blurKernel = 1;
  65539. this._useKernelBlur = false;
  65540. this._filter = ShadowGenerator.FILTER_NONE;
  65541. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65542. this._contactHardeningLightSizeUVRatio = 0.1;
  65543. this._darkness = 0;
  65544. this._transparencyShadow = false;
  65545. /**
  65546. * Controls the extent to which the shadows fade out at the edge of the frustum
  65547. * Used only by directionals and spots
  65548. */
  65549. this.frustumEdgeFalloff = 0;
  65550. /**
  65551. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65552. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65553. * It might on the other hand introduce peter panning.
  65554. */
  65555. this.forceBackFacesOnly = false;
  65556. this._lightDirection = BABYLON.Vector3.Zero();
  65557. this._viewMatrix = BABYLON.Matrix.Zero();
  65558. this._projectionMatrix = BABYLON.Matrix.Zero();
  65559. this._transformMatrix = BABYLON.Matrix.Zero();
  65560. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65561. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65562. this._currentFaceIndex = 0;
  65563. this._currentFaceIndexCache = 0;
  65564. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65565. this._mapSize = mapSize;
  65566. this._light = light;
  65567. this._scene = light.getScene();
  65568. light._shadowGenerator = this;
  65569. // Texture type fallback from float to int if not supported.
  65570. var caps = this._scene.getEngine().getCaps();
  65571. if (!useFullFloatFirst) {
  65572. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65573. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65574. }
  65575. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65576. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65577. }
  65578. else {
  65579. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65580. }
  65581. }
  65582. else {
  65583. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65584. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65585. }
  65586. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65587. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65588. }
  65589. else {
  65590. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65591. }
  65592. }
  65593. this._initializeGenerator();
  65594. this._applyFilterValues();
  65595. }
  65596. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65597. /**
  65598. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65599. */
  65600. get: function () {
  65601. return this._bias;
  65602. },
  65603. /**
  65604. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65605. */
  65606. set: function (bias) {
  65607. this._bias = bias;
  65608. },
  65609. enumerable: true,
  65610. configurable: true
  65611. });
  65612. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65613. /**
  65614. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65615. */
  65616. get: function () {
  65617. return this._normalBias;
  65618. },
  65619. /**
  65620. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65621. */
  65622. set: function (normalBias) {
  65623. this._normalBias = normalBias;
  65624. },
  65625. enumerable: true,
  65626. configurable: true
  65627. });
  65628. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65629. /**
  65630. * Gets the blur box offset: offset applied during the blur pass.
  65631. * Only usefull if useKernelBlur = false
  65632. */
  65633. get: function () {
  65634. return this._blurBoxOffset;
  65635. },
  65636. /**
  65637. * Sets the blur box offset: offset applied during the blur pass.
  65638. * Only usefull if useKernelBlur = false
  65639. */
  65640. set: function (value) {
  65641. if (this._blurBoxOffset === value) {
  65642. return;
  65643. }
  65644. this._blurBoxOffset = value;
  65645. this._disposeBlurPostProcesses();
  65646. },
  65647. enumerable: true,
  65648. configurable: true
  65649. });
  65650. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65651. /**
  65652. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65653. * 2 means half of the size.
  65654. */
  65655. get: function () {
  65656. return this._blurScale;
  65657. },
  65658. /**
  65659. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65660. * 2 means half of the size.
  65661. */
  65662. set: function (value) {
  65663. if (this._blurScale === value) {
  65664. return;
  65665. }
  65666. this._blurScale = value;
  65667. this._disposeBlurPostProcesses();
  65668. },
  65669. enumerable: true,
  65670. configurable: true
  65671. });
  65672. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65673. /**
  65674. * Gets the blur kernel: kernel size of the blur pass.
  65675. * Only usefull if useKernelBlur = true
  65676. */
  65677. get: function () {
  65678. return this._blurKernel;
  65679. },
  65680. /**
  65681. * Sets the blur kernel: kernel size of the blur pass.
  65682. * Only usefull if useKernelBlur = true
  65683. */
  65684. set: function (value) {
  65685. if (this._blurKernel === value) {
  65686. return;
  65687. }
  65688. this._blurKernel = value;
  65689. this._disposeBlurPostProcesses();
  65690. },
  65691. enumerable: true,
  65692. configurable: true
  65693. });
  65694. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65695. /**
  65696. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65697. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65698. */
  65699. get: function () {
  65700. return this._useKernelBlur;
  65701. },
  65702. /**
  65703. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65704. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65705. */
  65706. set: function (value) {
  65707. if (this._useKernelBlur === value) {
  65708. return;
  65709. }
  65710. this._useKernelBlur = value;
  65711. this._disposeBlurPostProcesses();
  65712. },
  65713. enumerable: true,
  65714. configurable: true
  65715. });
  65716. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65717. /**
  65718. * Gets the depth scale used in ESM mode.
  65719. */
  65720. get: function () {
  65721. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65722. },
  65723. /**
  65724. * Sets the depth scale used in ESM mode.
  65725. * This can override the scale stored on the light.
  65726. */
  65727. set: function (value) {
  65728. this._depthScale = value;
  65729. },
  65730. enumerable: true,
  65731. configurable: true
  65732. });
  65733. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65734. /**
  65735. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65736. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65737. */
  65738. get: function () {
  65739. return this._filter;
  65740. },
  65741. /**
  65742. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65743. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65744. */
  65745. set: function (value) {
  65746. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65747. if (this._light.needCube()) {
  65748. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65749. this.useExponentialShadowMap = true;
  65750. return;
  65751. }
  65752. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65753. this.useCloseExponentialShadowMap = true;
  65754. return;
  65755. }
  65756. // PCF on cubemap would also be expensive
  65757. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65758. this.usePoissonSampling = true;
  65759. return;
  65760. }
  65761. }
  65762. // Weblg1 fallback for PCF.
  65763. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65764. if (this._scene.getEngine().webGLVersion === 1) {
  65765. this.usePoissonSampling = true;
  65766. return;
  65767. }
  65768. }
  65769. if (this._filter === value) {
  65770. return;
  65771. }
  65772. this._filter = value;
  65773. this._disposeBlurPostProcesses();
  65774. this._applyFilterValues();
  65775. this._light._markMeshesAsLightDirty();
  65776. },
  65777. enumerable: true,
  65778. configurable: true
  65779. });
  65780. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65781. /**
  65782. * Gets if the current filter is set to Poisson Sampling.
  65783. */
  65784. get: function () {
  65785. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65786. },
  65787. /**
  65788. * Sets the current filter to Poisson Sampling.
  65789. */
  65790. set: function (value) {
  65791. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65792. return;
  65793. }
  65794. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65795. },
  65796. enumerable: true,
  65797. configurable: true
  65798. });
  65799. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65800. /**
  65801. * Gets if the current filter is set to VSM.
  65802. * DEPRECATED. Should use useExponentialShadowMap instead.
  65803. */
  65804. get: function () {
  65805. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65806. return this.useExponentialShadowMap;
  65807. },
  65808. /**
  65809. * Sets the current filter is to VSM.
  65810. * DEPRECATED. Should use useExponentialShadowMap instead.
  65811. */
  65812. set: function (value) {
  65813. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65814. this.useExponentialShadowMap = value;
  65815. },
  65816. enumerable: true,
  65817. configurable: true
  65818. });
  65819. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65820. /**
  65821. * Gets if the current filter is set to blurred VSM.
  65822. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65823. */
  65824. get: function () {
  65825. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65826. return this.useBlurExponentialShadowMap;
  65827. },
  65828. /**
  65829. * Sets the current filter is to blurred VSM.
  65830. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65831. */
  65832. set: function (value) {
  65833. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65834. this.useBlurExponentialShadowMap = value;
  65835. },
  65836. enumerable: true,
  65837. configurable: true
  65838. });
  65839. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65840. /**
  65841. * Gets if the current filter is set to ESM.
  65842. */
  65843. get: function () {
  65844. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65845. },
  65846. /**
  65847. * Sets the current filter is to ESM.
  65848. */
  65849. set: function (value) {
  65850. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65851. return;
  65852. }
  65853. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65854. },
  65855. enumerable: true,
  65856. configurable: true
  65857. });
  65858. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65859. /**
  65860. * Gets if the current filter is set to filtered ESM.
  65861. */
  65862. get: function () {
  65863. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65864. },
  65865. /**
  65866. * Gets if the current filter is set to filtered ESM.
  65867. */
  65868. set: function (value) {
  65869. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65870. return;
  65871. }
  65872. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65873. },
  65874. enumerable: true,
  65875. configurable: true
  65876. });
  65877. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65878. /**
  65879. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65880. * exponential to prevent steep falloff artifacts).
  65881. */
  65882. get: function () {
  65883. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65884. },
  65885. /**
  65886. * Sets the current filter to "close ESM" (using the inverse of the
  65887. * exponential to prevent steep falloff artifacts).
  65888. */
  65889. set: function (value) {
  65890. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65891. return;
  65892. }
  65893. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65894. },
  65895. enumerable: true,
  65896. configurable: true
  65897. });
  65898. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65899. /**
  65900. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65901. * exponential to prevent steep falloff artifacts).
  65902. */
  65903. get: function () {
  65904. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65905. },
  65906. /**
  65907. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65908. * exponential to prevent steep falloff artifacts).
  65909. */
  65910. set: function (value) {
  65911. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65912. return;
  65913. }
  65914. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65915. },
  65916. enumerable: true,
  65917. configurable: true
  65918. });
  65919. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65920. /**
  65921. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65922. */
  65923. get: function () {
  65924. return this.filter === ShadowGenerator.FILTER_PCF;
  65925. },
  65926. /**
  65927. * Sets the current filter to "PCF" (percentage closer filtering).
  65928. */
  65929. set: function (value) {
  65930. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65931. return;
  65932. }
  65933. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65934. },
  65935. enumerable: true,
  65936. configurable: true
  65937. });
  65938. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65939. /**
  65940. * Gets the PCF or PCSS Quality.
  65941. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65942. */
  65943. get: function () {
  65944. return this._filteringQuality;
  65945. },
  65946. /**
  65947. * Sets the PCF or PCSS Quality.
  65948. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65949. */
  65950. set: function (filteringQuality) {
  65951. this._filteringQuality = filteringQuality;
  65952. },
  65953. enumerable: true,
  65954. configurable: true
  65955. });
  65956. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65957. /**
  65958. * Gets if the current filter is set to "PCSS" (contact hardening).
  65959. */
  65960. get: function () {
  65961. return this.filter === ShadowGenerator.FILTER_PCSS;
  65962. },
  65963. /**
  65964. * Sets the current filter to "PCSS" (contact hardening).
  65965. */
  65966. set: function (value) {
  65967. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65968. return;
  65969. }
  65970. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65971. },
  65972. enumerable: true,
  65973. configurable: true
  65974. });
  65975. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65976. /**
  65977. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65978. * Using a ratio helps keeping shape stability independently of the map size.
  65979. *
  65980. * It does not account for the light projection as it was having too much
  65981. * instability during the light setup or during light position changes.
  65982. *
  65983. * Only valid if useContactHardeningShadow is true.
  65984. */
  65985. get: function () {
  65986. return this._contactHardeningLightSizeUVRatio;
  65987. },
  65988. /**
  65989. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65990. * Using a ratio helps keeping shape stability independently of the map size.
  65991. *
  65992. * It does not account for the light projection as it was having too much
  65993. * instability during the light setup or during light position changes.
  65994. *
  65995. * Only valid if useContactHardeningShadow is true.
  65996. */
  65997. set: function (contactHardeningLightSizeUVRatio) {
  65998. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65999. },
  66000. enumerable: true,
  66001. configurable: true
  66002. });
  66003. /**
  66004. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66005. * 0 means strongest and 1 would means no shadow.
  66006. * @returns the darkness.
  66007. */
  66008. ShadowGenerator.prototype.getDarkness = function () {
  66009. return this._darkness;
  66010. };
  66011. /**
  66012. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66013. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66014. * @returns the shadow generator allowing fluent coding.
  66015. */
  66016. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66017. if (darkness >= 1.0)
  66018. this._darkness = 1.0;
  66019. else if (darkness <= 0.0)
  66020. this._darkness = 0.0;
  66021. else
  66022. this._darkness = darkness;
  66023. return this;
  66024. };
  66025. /**
  66026. * Sets the ability to have transparent shadow (boolean).
  66027. * @param transparent True if transparent else False
  66028. * @returns the shadow generator allowing fluent coding
  66029. */
  66030. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66031. this._transparencyShadow = transparent;
  66032. return this;
  66033. };
  66034. /**
  66035. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66036. * @returns The render target texture if present otherwise, null
  66037. */
  66038. ShadowGenerator.prototype.getShadowMap = function () {
  66039. return this._shadowMap;
  66040. };
  66041. /**
  66042. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66043. * @returns The render target texture if the shadow map is present otherwise, null
  66044. */
  66045. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66046. if (this._shadowMap2) {
  66047. return this._shadowMap2;
  66048. }
  66049. return this._shadowMap;
  66050. };
  66051. /**
  66052. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66053. * @param mesh Mesh to add
  66054. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66055. * @returns the Shadow Generator itself
  66056. */
  66057. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66058. if (includeDescendants === void 0) { includeDescendants = true; }
  66059. if (!this._shadowMap) {
  66060. return this;
  66061. }
  66062. if (!this._shadowMap.renderList) {
  66063. this._shadowMap.renderList = [];
  66064. }
  66065. this._shadowMap.renderList.push(mesh);
  66066. if (includeDescendants) {
  66067. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66068. }
  66069. return this;
  66070. var _a;
  66071. };
  66072. /**
  66073. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66074. * @param mesh Mesh to remove
  66075. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66076. * @returns the Shadow Generator itself
  66077. */
  66078. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66079. if (includeDescendants === void 0) { includeDescendants = true; }
  66080. if (!this._shadowMap || !this._shadowMap.renderList) {
  66081. return this;
  66082. }
  66083. var index = this._shadowMap.renderList.indexOf(mesh);
  66084. if (index !== -1) {
  66085. this._shadowMap.renderList.splice(index, 1);
  66086. }
  66087. if (includeDescendants) {
  66088. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66089. var child = _a[_i];
  66090. this.removeShadowCaster(child);
  66091. }
  66092. }
  66093. return this;
  66094. };
  66095. /**
  66096. * Returns the associated light object.
  66097. * @returns the light generating the shadow
  66098. */
  66099. ShadowGenerator.prototype.getLight = function () {
  66100. return this._light;
  66101. };
  66102. ShadowGenerator.prototype._initializeGenerator = function () {
  66103. this._light._markMeshesAsLightDirty();
  66104. this._initializeShadowMap();
  66105. };
  66106. ShadowGenerator.prototype._initializeShadowMap = function () {
  66107. var _this = this;
  66108. // Render target
  66109. var engine = this._scene.getEngine();
  66110. if (engine.webGLVersion > 1) {
  66111. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66112. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66113. }
  66114. else {
  66115. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66116. }
  66117. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66118. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66119. this._shadowMap.anisotropicFilteringLevel = 1;
  66120. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66121. this._shadowMap.renderParticles = false;
  66122. this._shadowMap.ignoreCameraViewport = true;
  66123. // Record Face Index before render.
  66124. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66125. _this._currentFaceIndex = faceIndex;
  66126. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66127. engine.setColorWrite(false);
  66128. }
  66129. });
  66130. // Custom render function.
  66131. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66132. // Blur if required afer render.
  66133. this._shadowMap.onAfterUnbindObservable.add(function () {
  66134. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66135. engine.setColorWrite(true);
  66136. }
  66137. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66138. return;
  66139. }
  66140. var shadowMap = _this.getShadowMapForRendering();
  66141. if (shadowMap) {
  66142. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66143. }
  66144. });
  66145. // Clear according to the chosen filter.
  66146. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66147. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66148. this._shadowMap.onClearObservable.add(function (engine) {
  66149. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66150. engine.clear(clearOne, false, true, false);
  66151. }
  66152. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66153. engine.clear(clearZero, true, true, false);
  66154. }
  66155. else {
  66156. engine.clear(clearOne, true, true, false);
  66157. }
  66158. });
  66159. };
  66160. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66161. var _this = this;
  66162. var engine = this._scene.getEngine();
  66163. var targetSize = this._mapSize / this.blurScale;
  66164. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66165. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66166. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66167. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66168. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66169. }
  66170. if (this.useKernelBlur) {
  66171. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  66172. this._kernelBlurXPostprocess.width = targetSize;
  66173. this._kernelBlurXPostprocess.height = targetSize;
  66174. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66175. effect.setTexture("textureSampler", _this._shadowMap);
  66176. });
  66177. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  66178. this._kernelBlurXPostprocess.autoClear = false;
  66179. this._kernelBlurYPostprocess.autoClear = false;
  66180. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66181. this._kernelBlurXPostprocess.packedFloat = true;
  66182. this._kernelBlurYPostprocess.packedFloat = true;
  66183. }
  66184. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66185. }
  66186. else {
  66187. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  66188. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66189. effect.setFloat2("screenSize", targetSize, targetSize);
  66190. effect.setTexture("textureSampler", _this._shadowMap);
  66191. });
  66192. this._boxBlurPostprocess.autoClear = false;
  66193. this._blurPostProcesses = [this._boxBlurPostprocess];
  66194. }
  66195. };
  66196. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66197. var index;
  66198. var engine = this._scene.getEngine();
  66199. if (depthOnlySubMeshes.length) {
  66200. engine.setColorWrite(false);
  66201. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66202. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66203. }
  66204. engine.setColorWrite(true);
  66205. }
  66206. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66207. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66208. }
  66209. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66210. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66211. }
  66212. if (this._transparencyShadow) {
  66213. for (index = 0; index < transparentSubMeshes.length; index++) {
  66214. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66215. }
  66216. }
  66217. };
  66218. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66219. var _this = this;
  66220. var mesh = subMesh.getRenderingMesh();
  66221. var scene = this._scene;
  66222. var engine = scene.getEngine();
  66223. var material = subMesh.getMaterial();
  66224. if (!material) {
  66225. return;
  66226. }
  66227. // Culling
  66228. engine.setState(material.backFaceCulling);
  66229. // Managing instances
  66230. var batch = mesh._getInstancesRenderList(subMesh._id);
  66231. if (batch.mustReturn) {
  66232. return;
  66233. }
  66234. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66235. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66236. engine.enableEffect(this._effect);
  66237. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66238. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66239. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66240. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66241. this._effect.setVector3("lightData", this._cachedDirection);
  66242. }
  66243. else {
  66244. this._effect.setVector3("lightData", this._cachedPosition);
  66245. }
  66246. if (scene.activeCamera) {
  66247. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66248. }
  66249. // Alpha test
  66250. if (material && material.needAlphaTesting()) {
  66251. var alphaTexture = material.getAlphaTestTexture();
  66252. if (alphaTexture) {
  66253. this._effect.setTexture("diffuseSampler", alphaTexture);
  66254. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66255. }
  66256. }
  66257. // Bones
  66258. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66259. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66260. }
  66261. // Morph targets
  66262. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66263. if (this.forceBackFacesOnly) {
  66264. engine.setState(true, 0, false, true);
  66265. }
  66266. // Draw
  66267. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66268. if (this.forceBackFacesOnly) {
  66269. engine.setState(true, 0, false, false);
  66270. }
  66271. }
  66272. else {
  66273. // Need to reset refresh rate of the shadowMap
  66274. if (this._shadowMap) {
  66275. this._shadowMap.resetRefreshCounter();
  66276. }
  66277. }
  66278. };
  66279. ShadowGenerator.prototype._applyFilterValues = function () {
  66280. if (!this._shadowMap) {
  66281. return;
  66282. }
  66283. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66284. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66285. }
  66286. else {
  66287. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66288. }
  66289. };
  66290. /**
  66291. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66292. * @param onCompiled Callback triggered at the and of the effects compilation
  66293. * @param options Sets of optional options forcing the compilation with different modes
  66294. */
  66295. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66296. var _this = this;
  66297. var localOptions = __assign({ useInstances: false }, options);
  66298. var shadowMap = this.getShadowMap();
  66299. if (!shadowMap) {
  66300. if (onCompiled) {
  66301. onCompiled(this);
  66302. }
  66303. return;
  66304. }
  66305. var renderList = shadowMap.renderList;
  66306. if (!renderList) {
  66307. if (onCompiled) {
  66308. onCompiled(this);
  66309. }
  66310. return;
  66311. }
  66312. var subMeshes = new Array();
  66313. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66314. var mesh = renderList_1[_i];
  66315. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66316. }
  66317. if (subMeshes.length === 0) {
  66318. if (onCompiled) {
  66319. onCompiled(this);
  66320. }
  66321. return;
  66322. }
  66323. var currentIndex = 0;
  66324. var checkReady = function () {
  66325. if (!_this._scene || !_this._scene.getEngine()) {
  66326. return;
  66327. }
  66328. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66329. currentIndex++;
  66330. if (currentIndex >= subMeshes.length) {
  66331. if (onCompiled) {
  66332. onCompiled(_this);
  66333. }
  66334. return;
  66335. }
  66336. }
  66337. setTimeout(checkReady, 16);
  66338. };
  66339. checkReady();
  66340. };
  66341. /**
  66342. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66343. * @param options Sets of optional options forcing the compilation with different modes
  66344. * @returns A promise that resolves when the compilation completes
  66345. */
  66346. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66347. var _this = this;
  66348. return new Promise(function (resolve) {
  66349. _this.forceCompilation(function () {
  66350. resolve();
  66351. }, options);
  66352. });
  66353. };
  66354. /**
  66355. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66356. * @param subMesh The submesh we want to render in the shadow map
  66357. * @param useInstances Defines wether will draw in the map using instances
  66358. * @returns true if ready otherwise, false
  66359. */
  66360. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66361. var defines = [];
  66362. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66363. defines.push("#define FLOAT");
  66364. }
  66365. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66366. defines.push("#define ESM");
  66367. }
  66368. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66369. defines.push("#define DEPTHTEXTURE");
  66370. }
  66371. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66372. var mesh = subMesh.getMesh();
  66373. var material = subMesh.getMaterial();
  66374. // Normal bias.
  66375. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66376. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66377. defines.push("#define NORMAL");
  66378. if (mesh.nonUniformScaling) {
  66379. defines.push("#define NONUNIFORMSCALING");
  66380. }
  66381. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66382. defines.push("#define DIRECTIONINLIGHTDATA");
  66383. }
  66384. }
  66385. // Alpha test
  66386. if (material && material.needAlphaTesting()) {
  66387. var alphaTexture = material.getAlphaTestTexture();
  66388. if (alphaTexture) {
  66389. defines.push("#define ALPHATEST");
  66390. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66391. attribs.push(BABYLON.VertexBuffer.UVKind);
  66392. defines.push("#define UV1");
  66393. }
  66394. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66395. if (alphaTexture.coordinatesIndex === 1) {
  66396. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66397. defines.push("#define UV2");
  66398. }
  66399. }
  66400. }
  66401. }
  66402. // Bones
  66403. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66404. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66405. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66406. if (mesh.numBoneInfluencers > 4) {
  66407. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66408. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66409. }
  66410. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66411. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66412. }
  66413. else {
  66414. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66415. }
  66416. // Morph targets
  66417. var manager = mesh.morphTargetManager;
  66418. var morphInfluencers = 0;
  66419. if (manager) {
  66420. if (manager.numInfluencers > 0) {
  66421. defines.push("#define MORPHTARGETS");
  66422. morphInfluencers = manager.numInfluencers;
  66423. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66424. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66425. }
  66426. }
  66427. // Instances
  66428. if (useInstances) {
  66429. defines.push("#define INSTANCES");
  66430. attribs.push("world0");
  66431. attribs.push("world1");
  66432. attribs.push("world2");
  66433. attribs.push("world3");
  66434. }
  66435. // Get correct effect
  66436. var join = defines.join("\n");
  66437. if (this._cachedDefines !== join) {
  66438. this._cachedDefines = join;
  66439. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66440. }
  66441. if (!this._effect.isReady()) {
  66442. return false;
  66443. }
  66444. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66445. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66446. this._initializeBlurRTTAndPostProcesses();
  66447. }
  66448. }
  66449. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66450. return false;
  66451. }
  66452. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66453. return false;
  66454. }
  66455. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66456. return false;
  66457. }
  66458. return true;
  66459. };
  66460. /**
  66461. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66462. * @param defines Defines of the material we want to update
  66463. * @param lightIndex Index of the light in the enabled light list of the material
  66464. */
  66465. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66466. var scene = this._scene;
  66467. var light = this._light;
  66468. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66469. return;
  66470. }
  66471. defines["SHADOW" + lightIndex] = true;
  66472. if (this.useContactHardeningShadow) {
  66473. defines["SHADOWPCSS" + lightIndex] = true;
  66474. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66475. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66476. }
  66477. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66478. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66479. }
  66480. // else default to high.
  66481. }
  66482. if (this.usePercentageCloserFiltering) {
  66483. defines["SHADOWPCF" + lightIndex] = true;
  66484. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66485. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66486. }
  66487. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66488. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66489. }
  66490. // else default to high.
  66491. }
  66492. else if (this.usePoissonSampling) {
  66493. defines["SHADOWPOISSON" + lightIndex] = true;
  66494. }
  66495. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66496. defines["SHADOWESM" + lightIndex] = true;
  66497. }
  66498. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66499. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66500. }
  66501. if (light.needCube()) {
  66502. defines["SHADOWCUBE" + lightIndex] = true;
  66503. }
  66504. };
  66505. /**
  66506. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66507. * defined in the generator but impacting the effect).
  66508. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66509. * @param effect The effect we are binfing the information for
  66510. */
  66511. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66512. var light = this._light;
  66513. var scene = this._scene;
  66514. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66515. return;
  66516. }
  66517. var camera = scene.activeCamera;
  66518. if (!camera) {
  66519. return;
  66520. }
  66521. var shadowMap = this.getShadowMap();
  66522. if (!shadowMap) {
  66523. return;
  66524. }
  66525. if (!light.needCube()) {
  66526. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66527. }
  66528. // Only PCF uses depth stencil texture.
  66529. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66530. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66531. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66532. }
  66533. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66534. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66535. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66536. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66537. }
  66538. else {
  66539. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66540. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66541. }
  66542. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66543. };
  66544. /**
  66545. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66546. * (eq to shadow prjection matrix * light transform matrix)
  66547. * @returns The transform matrix used to create the shadow map
  66548. */
  66549. ShadowGenerator.prototype.getTransformMatrix = function () {
  66550. var scene = this._scene;
  66551. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66552. return this._transformMatrix;
  66553. }
  66554. this._currentRenderID = scene.getRenderId();
  66555. this._currentFaceIndexCache = this._currentFaceIndex;
  66556. var lightPosition = this._light.position;
  66557. if (this._light.computeTransformedInformation()) {
  66558. lightPosition = this._light.transformedPosition;
  66559. }
  66560. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66561. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66562. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66563. }
  66564. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66565. this._cachedPosition.copyFrom(lightPosition);
  66566. this._cachedDirection.copyFrom(this._lightDirection);
  66567. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66568. var shadowMap = this.getShadowMap();
  66569. if (shadowMap) {
  66570. var renderList = shadowMap.renderList;
  66571. if (renderList) {
  66572. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66573. }
  66574. }
  66575. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66576. }
  66577. return this._transformMatrix;
  66578. };
  66579. /**
  66580. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66581. * Cube and 2D textures for instance.
  66582. */
  66583. ShadowGenerator.prototype.recreateShadowMap = function () {
  66584. var shadowMap = this._shadowMap;
  66585. if (!shadowMap) {
  66586. return;
  66587. }
  66588. // Track render list.
  66589. var renderList = shadowMap.renderList;
  66590. // Clean up existing data.
  66591. this._disposeRTTandPostProcesses();
  66592. // Reinitializes.
  66593. this._initializeGenerator();
  66594. // Reaffect the filter to ensure a correct fallback if necessary.
  66595. this.filter = this.filter;
  66596. // Reaffect the filter.
  66597. this._applyFilterValues();
  66598. // Reaffect Render List.
  66599. this._shadowMap.renderList = renderList;
  66600. };
  66601. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66602. if (this._shadowMap2) {
  66603. this._shadowMap2.dispose();
  66604. this._shadowMap2 = null;
  66605. }
  66606. if (this._boxBlurPostprocess) {
  66607. this._boxBlurPostprocess.dispose();
  66608. this._boxBlurPostprocess = null;
  66609. }
  66610. if (this._kernelBlurXPostprocess) {
  66611. this._kernelBlurXPostprocess.dispose();
  66612. this._kernelBlurXPostprocess = null;
  66613. }
  66614. if (this._kernelBlurYPostprocess) {
  66615. this._kernelBlurYPostprocess.dispose();
  66616. this._kernelBlurYPostprocess = null;
  66617. }
  66618. this._blurPostProcesses = [];
  66619. };
  66620. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66621. if (this._shadowMap) {
  66622. this._shadowMap.dispose();
  66623. this._shadowMap = null;
  66624. }
  66625. this._disposeBlurPostProcesses();
  66626. };
  66627. /**
  66628. * Disposes the ShadowGenerator.
  66629. * Returns nothing.
  66630. */
  66631. ShadowGenerator.prototype.dispose = function () {
  66632. this._disposeRTTandPostProcesses();
  66633. if (this._light) {
  66634. this._light._shadowGenerator = null;
  66635. this._light._markMeshesAsLightDirty();
  66636. }
  66637. };
  66638. /**
  66639. * Serializes the shadow generator setup to a json object.
  66640. * @returns The serialized JSON object
  66641. */
  66642. ShadowGenerator.prototype.serialize = function () {
  66643. var serializationObject = {};
  66644. var shadowMap = this.getShadowMap();
  66645. if (!shadowMap) {
  66646. return serializationObject;
  66647. }
  66648. serializationObject.lightId = this._light.id;
  66649. serializationObject.mapSize = shadowMap.getRenderSize();
  66650. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66651. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66652. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66653. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66654. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66655. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66656. serializationObject.depthScale = this.depthScale;
  66657. serializationObject.darkness = this.getDarkness();
  66658. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66659. serializationObject.blurKernel = this.blurKernel;
  66660. serializationObject.blurScale = this.blurScale;
  66661. serializationObject.useKernelBlur = this.useKernelBlur;
  66662. serializationObject.transparencyShadow = this._transparencyShadow;
  66663. serializationObject.bias = this.bias;
  66664. serializationObject.normalBias = this.normalBias;
  66665. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66666. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66667. serializationObject.filteringQuality = this.filteringQuality;
  66668. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66669. serializationObject.renderList = [];
  66670. if (shadowMap.renderList) {
  66671. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66672. var mesh = shadowMap.renderList[meshIndex];
  66673. serializationObject.renderList.push(mesh.id);
  66674. }
  66675. }
  66676. return serializationObject;
  66677. };
  66678. /**
  66679. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66680. * @param parsedShadowGenerator The JSON object to parse
  66681. * @param scene The scene to create the shadow map for
  66682. * @returns The parsed shadow generator
  66683. */
  66684. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66685. //casting to point light, as light is missing the position attr and typescript complains.
  66686. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66687. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66688. var shadowMap = shadowGenerator.getShadowMap();
  66689. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66690. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66691. meshes.forEach(function (mesh) {
  66692. if (!shadowMap) {
  66693. return;
  66694. }
  66695. if (!shadowMap.renderList) {
  66696. shadowMap.renderList = [];
  66697. }
  66698. shadowMap.renderList.push(mesh);
  66699. });
  66700. }
  66701. if (parsedShadowGenerator.usePoissonSampling) {
  66702. shadowGenerator.usePoissonSampling = true;
  66703. }
  66704. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66705. shadowGenerator.useExponentialShadowMap = true;
  66706. }
  66707. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66708. shadowGenerator.useBlurExponentialShadowMap = true;
  66709. }
  66710. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66711. shadowGenerator.useCloseExponentialShadowMap = true;
  66712. }
  66713. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66714. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66715. }
  66716. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66717. shadowGenerator.usePercentageCloserFiltering = true;
  66718. }
  66719. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66720. shadowGenerator.useContactHardeningShadow = true;
  66721. }
  66722. if (parsedShadowGenerator.filteringQuality) {
  66723. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66724. }
  66725. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66726. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66727. }
  66728. // Backward compat
  66729. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66730. shadowGenerator.useExponentialShadowMap = true;
  66731. }
  66732. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66733. shadowGenerator.useBlurExponentialShadowMap = true;
  66734. }
  66735. if (parsedShadowGenerator.depthScale) {
  66736. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66737. }
  66738. if (parsedShadowGenerator.blurScale) {
  66739. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66740. }
  66741. if (parsedShadowGenerator.blurBoxOffset) {
  66742. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66743. }
  66744. if (parsedShadowGenerator.useKernelBlur) {
  66745. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66746. }
  66747. if (parsedShadowGenerator.blurKernel) {
  66748. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66749. }
  66750. if (parsedShadowGenerator.bias !== undefined) {
  66751. shadowGenerator.bias = parsedShadowGenerator.bias;
  66752. }
  66753. if (parsedShadowGenerator.normalBias !== undefined) {
  66754. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66755. }
  66756. if (parsedShadowGenerator.darkness) {
  66757. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66758. }
  66759. if (parsedShadowGenerator.transparencyShadow) {
  66760. shadowGenerator.setTransparencyShadow(true);
  66761. }
  66762. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66763. return shadowGenerator;
  66764. };
  66765. /**
  66766. * Shadow generator mode None: no filtering applied.
  66767. */
  66768. ShadowGenerator.FILTER_NONE = 0;
  66769. /**
  66770. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66771. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66772. */
  66773. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66774. /**
  66775. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66776. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66777. */
  66778. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66779. /**
  66780. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66781. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66782. */
  66783. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66784. /**
  66785. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66786. * edge artifacts on steep falloff.
  66787. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66788. */
  66789. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66790. /**
  66791. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66792. * edge artifacts on steep falloff.
  66793. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66794. */
  66795. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66796. /**
  66797. * Shadow generator mode PCF: Percentage Closer Filtering
  66798. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66799. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66800. */
  66801. ShadowGenerator.FILTER_PCF = 6;
  66802. /**
  66803. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66804. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66805. * Contact Hardening
  66806. */
  66807. ShadowGenerator.FILTER_PCSS = 7;
  66808. /**
  66809. * Reserved for PCF and PCSS
  66810. * Highest Quality.
  66811. *
  66812. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66813. *
  66814. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66815. */
  66816. ShadowGenerator.QUALITY_HIGH = 0;
  66817. /**
  66818. * Reserved for PCF and PCSS
  66819. * Good tradeoff for quality/perf cross devices
  66820. *
  66821. * Execute PCF on a 3*3 kernel.
  66822. *
  66823. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66824. */
  66825. ShadowGenerator.QUALITY_MEDIUM = 1;
  66826. /**
  66827. * Reserved for PCF and PCSS
  66828. * The lowest quality but the fastest.
  66829. *
  66830. * Execute PCF on a 1*1 kernel.
  66831. *
  66832. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66833. */
  66834. ShadowGenerator.QUALITY_LOW = 2;
  66835. return ShadowGenerator;
  66836. }());
  66837. BABYLON.ShadowGenerator = ShadowGenerator;
  66838. })(BABYLON || (BABYLON = {}));
  66839. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66840. var BABYLON;
  66841. (function (BABYLON) {
  66842. var DefaultLoadingScreen = /** @class */ (function () {
  66843. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66844. if (_loadingText === void 0) { _loadingText = ""; }
  66845. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66846. var _this = this;
  66847. this._renderingCanvas = _renderingCanvas;
  66848. this._loadingText = _loadingText;
  66849. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66850. // Resize
  66851. this._resizeLoadingUI = function () {
  66852. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66853. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66854. if (!_this._loadingDiv) {
  66855. return;
  66856. }
  66857. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66858. _this._loadingDiv.style.left = canvasRect.left + "px";
  66859. _this._loadingDiv.style.top = canvasRect.top + "px";
  66860. _this._loadingDiv.style.width = canvasRect.width + "px";
  66861. _this._loadingDiv.style.height = canvasRect.height + "px";
  66862. };
  66863. }
  66864. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66865. if (this._loadingDiv) {
  66866. // Do not add a loading screen if there is already one
  66867. return;
  66868. }
  66869. this._loadingDiv = document.createElement("div");
  66870. this._loadingDiv.id = "babylonjsLoadingDiv";
  66871. this._loadingDiv.style.opacity = "0";
  66872. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66873. this._loadingDiv.style.pointerEvents = "none";
  66874. // Loading text
  66875. this._loadingTextDiv = document.createElement("div");
  66876. this._loadingTextDiv.style.position = "absolute";
  66877. this._loadingTextDiv.style.left = "0";
  66878. this._loadingTextDiv.style.top = "50%";
  66879. this._loadingTextDiv.style.marginTop = "80px";
  66880. this._loadingTextDiv.style.width = "100%";
  66881. this._loadingTextDiv.style.height = "20px";
  66882. this._loadingTextDiv.style.fontFamily = "Arial";
  66883. this._loadingTextDiv.style.fontSize = "14px";
  66884. this._loadingTextDiv.style.color = "white";
  66885. this._loadingTextDiv.style.textAlign = "center";
  66886. this._loadingTextDiv.innerHTML = "Loading";
  66887. this._loadingDiv.appendChild(this._loadingTextDiv);
  66888. //set the predefined text
  66889. this._loadingTextDiv.innerHTML = this._loadingText;
  66890. // Generating keyframes
  66891. var style = document.createElement('style');
  66892. style.type = 'text/css';
  66893. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  66894. style.innerHTML = keyFrames;
  66895. document.getElementsByTagName('head')[0].appendChild(style);
  66896. // Loading img
  66897. var imgBack = new Image();
  66898. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  66899. imgBack.style.position = "absolute";
  66900. imgBack.style.left = "50%";
  66901. imgBack.style.top = "50%";
  66902. imgBack.style.marginLeft = "-60px";
  66903. imgBack.style.marginTop = "-60px";
  66904. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66905. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66906. imgBack.style.transformOrigin = "50% 50%";
  66907. imgBack.style.webkitTransformOrigin = "50% 50%";
  66908. this._loadingDiv.appendChild(imgBack);
  66909. this._resizeLoadingUI();
  66910. window.addEventListener("resize", this._resizeLoadingUI);
  66911. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66912. document.body.appendChild(this._loadingDiv);
  66913. this._loadingDiv.style.opacity = "1";
  66914. };
  66915. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66916. var _this = this;
  66917. if (!this._loadingDiv) {
  66918. return;
  66919. }
  66920. var onTransitionEnd = function () {
  66921. if (!_this._loadingDiv) {
  66922. return;
  66923. }
  66924. document.body.removeChild(_this._loadingDiv);
  66925. window.removeEventListener("resize", _this._resizeLoadingUI);
  66926. _this._loadingDiv = null;
  66927. };
  66928. this._loadingDiv.style.opacity = "0";
  66929. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66930. };
  66931. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66932. set: function (text) {
  66933. this._loadingText = text;
  66934. if (this._loadingTextDiv) {
  66935. this._loadingTextDiv.innerHTML = this._loadingText;
  66936. }
  66937. },
  66938. enumerable: true,
  66939. configurable: true
  66940. });
  66941. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66942. get: function () {
  66943. return this._loadingDivBackgroundColor;
  66944. },
  66945. set: function (color) {
  66946. this._loadingDivBackgroundColor = color;
  66947. if (!this._loadingDiv) {
  66948. return;
  66949. }
  66950. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66951. },
  66952. enumerable: true,
  66953. configurable: true
  66954. });
  66955. return DefaultLoadingScreen;
  66956. }());
  66957. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66958. })(BABYLON || (BABYLON = {}));
  66959. //# sourceMappingURL=babylon.loadingScreen.js.map
  66960. var BABYLON;
  66961. (function (BABYLON) {
  66962. var SceneLoaderProgressEvent = /** @class */ (function () {
  66963. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66964. this.lengthComputable = lengthComputable;
  66965. this.loaded = loaded;
  66966. this.total = total;
  66967. }
  66968. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66969. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66970. };
  66971. return SceneLoaderProgressEvent;
  66972. }());
  66973. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66974. var SceneLoader = /** @class */ (function () {
  66975. function SceneLoader() {
  66976. }
  66977. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66978. get: function () {
  66979. return 0;
  66980. },
  66981. enumerable: true,
  66982. configurable: true
  66983. });
  66984. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66985. get: function () {
  66986. return 1;
  66987. },
  66988. enumerable: true,
  66989. configurable: true
  66990. });
  66991. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66992. get: function () {
  66993. return 2;
  66994. },
  66995. enumerable: true,
  66996. configurable: true
  66997. });
  66998. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66999. get: function () {
  67000. return 3;
  67001. },
  67002. enumerable: true,
  67003. configurable: true
  67004. });
  67005. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67006. get: function () {
  67007. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67008. },
  67009. set: function (value) {
  67010. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67011. },
  67012. enumerable: true,
  67013. configurable: true
  67014. });
  67015. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67016. get: function () {
  67017. return SceneLoader._ShowLoadingScreen;
  67018. },
  67019. set: function (value) {
  67020. SceneLoader._ShowLoadingScreen = value;
  67021. },
  67022. enumerable: true,
  67023. configurable: true
  67024. });
  67025. Object.defineProperty(SceneLoader, "loggingLevel", {
  67026. get: function () {
  67027. return SceneLoader._loggingLevel;
  67028. },
  67029. set: function (value) {
  67030. SceneLoader._loggingLevel = value;
  67031. },
  67032. enumerable: true,
  67033. configurable: true
  67034. });
  67035. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67036. get: function () {
  67037. return SceneLoader._CleanBoneMatrixWeights;
  67038. },
  67039. set: function (value) {
  67040. SceneLoader._CleanBoneMatrixWeights = value;
  67041. },
  67042. enumerable: true,
  67043. configurable: true
  67044. });
  67045. SceneLoader._getDefaultPlugin = function () {
  67046. return SceneLoader._registeredPlugins[".babylon"];
  67047. };
  67048. SceneLoader._getPluginForExtension = function (extension) {
  67049. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67050. if (registeredPlugin) {
  67051. return registeredPlugin;
  67052. }
  67053. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  67054. return SceneLoader._getDefaultPlugin();
  67055. };
  67056. SceneLoader._getPluginForDirectLoad = function (data) {
  67057. for (var extension in SceneLoader._registeredPlugins) {
  67058. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67059. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67060. return SceneLoader._registeredPlugins[extension];
  67061. }
  67062. }
  67063. return SceneLoader._getDefaultPlugin();
  67064. };
  67065. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67066. if (sceneFilename.name) {
  67067. sceneFilename = sceneFilename.name;
  67068. }
  67069. var queryStringPosition = sceneFilename.indexOf("?");
  67070. if (queryStringPosition !== -1) {
  67071. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67072. }
  67073. var dotPosition = sceneFilename.lastIndexOf(".");
  67074. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67075. return SceneLoader._getPluginForExtension(extension);
  67076. };
  67077. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67078. SceneLoader._getDirectLoad = function (sceneFilename) {
  67079. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67080. return sceneFilename.substr(5);
  67081. }
  67082. return null;
  67083. };
  67084. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67085. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67086. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67087. var plugin;
  67088. if (registeredPlugin.plugin.createPlugin) {
  67089. plugin = registeredPlugin.plugin.createPlugin();
  67090. }
  67091. else {
  67092. plugin = registeredPlugin.plugin;
  67093. }
  67094. var useArrayBuffer = registeredPlugin.isBinary;
  67095. var database;
  67096. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67097. var dataCallback = function (data, responseURL) {
  67098. if (scene.isDisposed) {
  67099. onError("Scene has been disposed");
  67100. return;
  67101. }
  67102. scene.database = database;
  67103. onSuccess(plugin, data, responseURL);
  67104. };
  67105. var request = null;
  67106. var pluginDisposed = false;
  67107. var onDisposeObservable = plugin.onDisposeObservable;
  67108. if (onDisposeObservable) {
  67109. onDisposeObservable.add(function () {
  67110. pluginDisposed = true;
  67111. if (request) {
  67112. request.abort();
  67113. request = null;
  67114. }
  67115. onDispose();
  67116. });
  67117. }
  67118. var manifestChecked = function () {
  67119. if (pluginDisposed) {
  67120. return;
  67121. }
  67122. var url = rootUrl + sceneFilename;
  67123. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67124. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67125. } : undefined, database, useArrayBuffer, function (request, exception) {
  67126. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67127. });
  67128. };
  67129. if (directLoad) {
  67130. dataCallback(directLoad);
  67131. return plugin;
  67132. }
  67133. if (rootUrl.indexOf("file:") === -1) {
  67134. var engine = scene.getEngine();
  67135. var canUseOfflineSupport = engine.enableOfflineSupport;
  67136. if (canUseOfflineSupport) {
  67137. // Also check for exceptions
  67138. var exceptionFound = false;
  67139. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67140. var regex = _a[_i];
  67141. if (regex.test(rootUrl + sceneFilename)) {
  67142. exceptionFound = true;
  67143. break;
  67144. }
  67145. }
  67146. canUseOfflineSupport = !exceptionFound;
  67147. }
  67148. if (canUseOfflineSupport) {
  67149. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67150. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67151. }
  67152. else {
  67153. manifestChecked();
  67154. }
  67155. }
  67156. // Loading file from disk via input file or drag'n'drop
  67157. else {
  67158. var fileOrString = sceneFilename;
  67159. if (fileOrString.name) { // File
  67160. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67161. }
  67162. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67163. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67164. }
  67165. else {
  67166. onError("Unable to find file named " + sceneFilename);
  67167. }
  67168. }
  67169. return plugin;
  67170. };
  67171. // Public functions
  67172. SceneLoader.GetPluginForExtension = function (extension) {
  67173. return SceneLoader._getPluginForExtension(extension).plugin;
  67174. };
  67175. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67176. return !!SceneLoader._registeredPlugins[extension];
  67177. };
  67178. SceneLoader.RegisterPlugin = function (plugin) {
  67179. if (typeof plugin.extensions === "string") {
  67180. var extension = plugin.extensions;
  67181. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67182. plugin: plugin,
  67183. isBinary: false
  67184. };
  67185. }
  67186. else {
  67187. var extensions = plugin.extensions;
  67188. Object.keys(extensions).forEach(function (extension) {
  67189. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67190. plugin: plugin,
  67191. isBinary: extensions[extension].isBinary
  67192. };
  67193. });
  67194. }
  67195. };
  67196. /**
  67197. * Import meshes into a scene
  67198. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67199. * @param rootUrl a string that defines the root url for scene and resources
  67200. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67201. * @param scene the instance of BABYLON.Scene to append to
  67202. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67203. * @param onProgress a callback with a progress event for each file being loaded
  67204. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67205. * @param pluginExtension the extension used to determine the plugin
  67206. * @returns The loaded plugin
  67207. */
  67208. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67209. if (onSuccess === void 0) { onSuccess = null; }
  67210. if (onProgress === void 0) { onProgress = null; }
  67211. if (onError === void 0) { onError = null; }
  67212. if (pluginExtension === void 0) { pluginExtension = null; }
  67213. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67214. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67215. return null;
  67216. }
  67217. var loadingToken = {};
  67218. scene._addPendingData(loadingToken);
  67219. var disposeHandler = function () {
  67220. scene._removePendingData(loadingToken);
  67221. };
  67222. var errorHandler = function (message, exception) {
  67223. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67224. if (onError) {
  67225. onError(scene, errorMessage, exception);
  67226. }
  67227. else {
  67228. BABYLON.Tools.Error(errorMessage);
  67229. // should the exception be thrown?
  67230. }
  67231. disposeHandler();
  67232. };
  67233. var progressHandler = onProgress ? function (event) {
  67234. try {
  67235. onProgress(event);
  67236. }
  67237. catch (e) {
  67238. errorHandler("Error in onProgress callback", e);
  67239. }
  67240. } : undefined;
  67241. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67242. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67243. if (onSuccess) {
  67244. try {
  67245. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67246. }
  67247. catch (e) {
  67248. errorHandler("Error in onSuccess callback", e);
  67249. }
  67250. }
  67251. scene._removePendingData(loadingToken);
  67252. };
  67253. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67254. if (plugin.rewriteRootURL) {
  67255. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67256. }
  67257. if (sceneFilename === "") {
  67258. if (sceneFilename === "") {
  67259. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67260. }
  67261. }
  67262. if (plugin.importMesh) {
  67263. var syncedPlugin = plugin;
  67264. var meshes = new Array();
  67265. var particleSystems = new Array();
  67266. var skeletons = new Array();
  67267. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67268. return;
  67269. }
  67270. scene.loadingPluginName = plugin.name;
  67271. successHandler(meshes, particleSystems, skeletons, []);
  67272. }
  67273. else {
  67274. var asyncedPlugin = plugin;
  67275. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67276. scene.loadingPluginName = plugin.name;
  67277. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67278. }).catch(function (error) {
  67279. errorHandler(error.message, error);
  67280. });
  67281. }
  67282. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67283. };
  67284. /**
  67285. * Import meshes into a scene
  67286. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67287. * @param rootUrl a string that defines the root url for scene and resources
  67288. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67289. * @param scene the instance of BABYLON.Scene to append to
  67290. * @param onProgress a callback with a progress event for each file being loaded
  67291. * @param pluginExtension the extension used to determine the plugin
  67292. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67293. */
  67294. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67295. if (onProgress === void 0) { onProgress = null; }
  67296. if (pluginExtension === void 0) { pluginExtension = null; }
  67297. return new Promise(function (resolve, reject) {
  67298. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67299. resolve({
  67300. meshes: meshes,
  67301. particleSystems: particleSystems,
  67302. skeletons: skeletons,
  67303. animationGroups: animationGroups
  67304. });
  67305. }, onProgress, function (scene, message, exception) {
  67306. reject(exception || new Error(message));
  67307. }, pluginExtension);
  67308. });
  67309. };
  67310. /**
  67311. * Load a scene
  67312. * @param rootUrl a string that defines the root url for scene and resources
  67313. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67314. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67315. * @param onSuccess a callback with the scene when import succeeds
  67316. * @param onProgress a callback with a progress event for each file being loaded
  67317. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67318. * @param pluginExtension the extension used to determine the plugin
  67319. * @returns The loaded plugin
  67320. */
  67321. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67322. if (onSuccess === void 0) { onSuccess = null; }
  67323. if (onProgress === void 0) { onProgress = null; }
  67324. if (onError === void 0) { onError = null; }
  67325. if (pluginExtension === void 0) { pluginExtension = null; }
  67326. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67327. };
  67328. /**
  67329. * Load a scene
  67330. * @param rootUrl a string that defines the root url for scene and resources
  67331. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67332. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67333. * @param onProgress a callback with a progress event for each file being loaded
  67334. * @param pluginExtension the extension used to determine the plugin
  67335. * @returns The loaded scene
  67336. */
  67337. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67338. if (onProgress === void 0) { onProgress = null; }
  67339. if (pluginExtension === void 0) { pluginExtension = null; }
  67340. return new Promise(function (resolve, reject) {
  67341. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67342. resolve(scene);
  67343. }, onProgress, function (scene, message, exception) {
  67344. reject(exception || new Error(message));
  67345. }, pluginExtension);
  67346. });
  67347. };
  67348. /**
  67349. * Append a scene
  67350. * @param rootUrl a string that defines the root url for scene and resources
  67351. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67352. * @param scene is the instance of BABYLON.Scene to append to
  67353. * @param onSuccess a callback with the scene when import succeeds
  67354. * @param onProgress a callback with a progress event for each file being loaded
  67355. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67356. * @param pluginExtension the extension used to determine the plugin
  67357. * @returns The loaded plugin
  67358. */
  67359. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67360. if (onSuccess === void 0) { onSuccess = null; }
  67361. if (onProgress === void 0) { onProgress = null; }
  67362. if (onError === void 0) { onError = null; }
  67363. if (pluginExtension === void 0) { pluginExtension = null; }
  67364. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67365. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67366. return null;
  67367. }
  67368. if (SceneLoader.ShowLoadingScreen) {
  67369. scene.getEngine().displayLoadingUI();
  67370. }
  67371. var loadingToken = {};
  67372. scene._addPendingData(loadingToken);
  67373. var disposeHandler = function () {
  67374. scene._removePendingData(loadingToken);
  67375. scene.getEngine().hideLoadingUI();
  67376. };
  67377. var errorHandler = function (message, exception) {
  67378. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67379. if (onError) {
  67380. onError(scene, errorMessage, exception);
  67381. }
  67382. else {
  67383. BABYLON.Tools.Error(errorMessage);
  67384. // should the exception be thrown?
  67385. }
  67386. disposeHandler();
  67387. };
  67388. var progressHandler = onProgress ? function (event) {
  67389. try {
  67390. onProgress(event);
  67391. }
  67392. catch (e) {
  67393. errorHandler("Error in onProgress callback", e);
  67394. }
  67395. } : undefined;
  67396. var successHandler = function () {
  67397. if (onSuccess) {
  67398. try {
  67399. onSuccess(scene);
  67400. }
  67401. catch (e) {
  67402. errorHandler("Error in onSuccess callback", e);
  67403. }
  67404. }
  67405. scene._removePendingData(loadingToken);
  67406. };
  67407. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67408. if (sceneFilename === "") {
  67409. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67410. }
  67411. if (plugin.load) {
  67412. var syncedPlugin = plugin;
  67413. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67414. return;
  67415. }
  67416. scene.loadingPluginName = plugin.name;
  67417. successHandler();
  67418. }
  67419. else {
  67420. var asyncedPlugin = plugin;
  67421. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67422. scene.loadingPluginName = plugin.name;
  67423. successHandler();
  67424. }).catch(function (error) {
  67425. errorHandler(error.message, error);
  67426. });
  67427. }
  67428. if (SceneLoader.ShowLoadingScreen) {
  67429. scene.executeWhenReady(function () {
  67430. scene.getEngine().hideLoadingUI();
  67431. });
  67432. }
  67433. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67434. };
  67435. /**
  67436. * Append a scene
  67437. * @param rootUrl a string that defines the root url for scene and resources
  67438. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67439. * @param scene is the instance of BABYLON.Scene to append to
  67440. * @param onProgress a callback with a progress event for each file being loaded
  67441. * @param pluginExtension the extension used to determine the plugin
  67442. * @returns The given scene
  67443. */
  67444. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67445. if (onProgress === void 0) { onProgress = null; }
  67446. if (pluginExtension === void 0) { pluginExtension = null; }
  67447. return new Promise(function (resolve, reject) {
  67448. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67449. resolve(scene);
  67450. }, onProgress, function (scene, message, exception) {
  67451. reject(exception || new Error(message));
  67452. }, pluginExtension);
  67453. });
  67454. };
  67455. /**
  67456. * Load a scene into an asset container
  67457. * @param rootUrl a string that defines the root url for scene and resources
  67458. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67459. * @param scene is the instance of BABYLON.Scene to append to
  67460. * @param onSuccess a callback with the scene when import succeeds
  67461. * @param onProgress a callback with a progress event for each file being loaded
  67462. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67463. * @param pluginExtension the extension used to determine the plugin
  67464. * @returns The loaded plugin
  67465. */
  67466. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67467. if (onSuccess === void 0) { onSuccess = null; }
  67468. if (onProgress === void 0) { onProgress = null; }
  67469. if (onError === void 0) { onError = null; }
  67470. if (pluginExtension === void 0) { pluginExtension = null; }
  67471. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67472. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67473. return null;
  67474. }
  67475. var loadingToken = {};
  67476. scene._addPendingData(loadingToken);
  67477. var disposeHandler = function () {
  67478. scene._removePendingData(loadingToken);
  67479. };
  67480. var errorHandler = function (message, exception) {
  67481. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67482. if (onError) {
  67483. onError(scene, errorMessage, exception);
  67484. }
  67485. else {
  67486. BABYLON.Tools.Error(errorMessage);
  67487. // should the exception be thrown?
  67488. }
  67489. disposeHandler();
  67490. };
  67491. var progressHandler = onProgress ? function (event) {
  67492. try {
  67493. onProgress(event);
  67494. }
  67495. catch (e) {
  67496. errorHandler("Error in onProgress callback", e);
  67497. }
  67498. } : undefined;
  67499. var successHandler = function (assets) {
  67500. if (onSuccess) {
  67501. try {
  67502. onSuccess(assets);
  67503. }
  67504. catch (e) {
  67505. errorHandler("Error in onSuccess callback", e);
  67506. }
  67507. }
  67508. scene._removePendingData(loadingToken);
  67509. };
  67510. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67511. if (plugin.loadAssetContainer) {
  67512. var syncedPlugin = plugin;
  67513. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67514. if (!assetContainer) {
  67515. return;
  67516. }
  67517. scene.loadingPluginName = plugin.name;
  67518. successHandler(assetContainer);
  67519. }
  67520. else if (plugin.loadAssetContainerAsync) {
  67521. var asyncedPlugin = plugin;
  67522. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67523. scene.loadingPluginName = plugin.name;
  67524. successHandler(assetContainer);
  67525. }).catch(function (error) {
  67526. errorHandler(error.message, error);
  67527. });
  67528. }
  67529. else {
  67530. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67531. }
  67532. if (SceneLoader.ShowLoadingScreen) {
  67533. scene.executeWhenReady(function () {
  67534. scene.getEngine().hideLoadingUI();
  67535. });
  67536. }
  67537. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67538. };
  67539. /**
  67540. * Load a scene into an asset container
  67541. * @param rootUrl a string that defines the root url for scene and resources
  67542. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67543. * @param scene is the instance of BABYLON.Scene to append to
  67544. * @param onProgress a callback with a progress event for each file being loaded
  67545. * @param pluginExtension the extension used to determine the plugin
  67546. * @returns The loaded asset container
  67547. */
  67548. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67549. if (onProgress === void 0) { onProgress = null; }
  67550. if (pluginExtension === void 0) { pluginExtension = null; }
  67551. return new Promise(function (resolve, reject) {
  67552. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67553. resolve(assetContainer);
  67554. }, onProgress, function (scene, message, exception) {
  67555. reject(exception || new Error(message));
  67556. }, pluginExtension);
  67557. });
  67558. };
  67559. // Flags
  67560. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67561. SceneLoader._ShowLoadingScreen = true;
  67562. SceneLoader._CleanBoneMatrixWeights = false;
  67563. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67564. // Members
  67565. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67566. SceneLoader._registeredPlugins = {};
  67567. return SceneLoader;
  67568. }());
  67569. BABYLON.SceneLoader = SceneLoader;
  67570. ;
  67571. })(BABYLON || (BABYLON = {}));
  67572. //# sourceMappingURL=babylon.sceneLoader.js.map
  67573. var BABYLON;
  67574. (function (BABYLON) {
  67575. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67576. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67577. var parsedMaterial = parsedData.materials[index];
  67578. if (parsedMaterial.id === id) {
  67579. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67580. }
  67581. }
  67582. return null;
  67583. };
  67584. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67585. for (var i in names) {
  67586. if (mesh.name === names[i]) {
  67587. hierarchyIds.push(mesh.id);
  67588. return true;
  67589. }
  67590. }
  67591. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67592. hierarchyIds.push(mesh.id);
  67593. return true;
  67594. }
  67595. return false;
  67596. };
  67597. var logOperation = function (operation, producer) {
  67598. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67599. };
  67600. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67601. if (addToScene === void 0) { addToScene = false; }
  67602. var container = new BABYLON.AssetContainer(scene);
  67603. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67604. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67605. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67606. // and avoid problems with multiple concurrent .babylon loads.
  67607. var log = "importScene has failed JSON parse";
  67608. try {
  67609. var parsedData = JSON.parse(data);
  67610. log = "";
  67611. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67612. var index;
  67613. var cache;
  67614. // Lights
  67615. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67616. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67617. var parsedLight = parsedData.lights[index];
  67618. var light = BABYLON.Light.Parse(parsedLight, scene);
  67619. if (light) {
  67620. container.lights.push(light);
  67621. log += (index === 0 ? "\n\tLights:" : "");
  67622. log += "\n\t\t" + light.toString(fullDetails);
  67623. }
  67624. }
  67625. }
  67626. // Animations
  67627. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67628. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67629. var parsedAnimation = parsedData.animations[index];
  67630. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67631. scene.animations.push(animation);
  67632. container.animations.push(animation);
  67633. log += (index === 0 ? "\n\tAnimations:" : "");
  67634. log += "\n\t\t" + animation.toString(fullDetails);
  67635. }
  67636. }
  67637. // Materials
  67638. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67639. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67640. var parsedMaterial = parsedData.materials[index];
  67641. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67642. container.materials.push(mat);
  67643. log += (index === 0 ? "\n\tMaterials:" : "");
  67644. log += "\n\t\t" + mat.toString(fullDetails);
  67645. }
  67646. }
  67647. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67648. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67649. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67650. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67651. container.multiMaterials.push(mmat);
  67652. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67653. log += "\n\t\t" + mmat.toString(fullDetails);
  67654. }
  67655. }
  67656. // Morph targets
  67657. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67658. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67659. var managerData = _a[_i];
  67660. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67661. }
  67662. }
  67663. // Skeletons
  67664. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67665. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67666. var parsedSkeleton = parsedData.skeletons[index];
  67667. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67668. container.skeletons.push(skeleton);
  67669. log += (index === 0 ? "\n\tSkeletons:" : "");
  67670. log += "\n\t\t" + skeleton.toString(fullDetails);
  67671. }
  67672. }
  67673. // Geometries
  67674. var geometries = parsedData.geometries;
  67675. if (geometries !== undefined && geometries !== null) {
  67676. var addedGeometry = new Array();
  67677. // Boxes
  67678. var boxes = geometries.boxes;
  67679. if (boxes !== undefined && boxes !== null) {
  67680. for (index = 0, cache = boxes.length; index < cache; index++) {
  67681. var parsedBox = boxes[index];
  67682. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67683. }
  67684. }
  67685. // Spheres
  67686. var spheres = geometries.spheres;
  67687. if (spheres !== undefined && spheres !== null) {
  67688. for (index = 0, cache = spheres.length; index < cache; index++) {
  67689. var parsedSphere = spheres[index];
  67690. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67691. }
  67692. }
  67693. // Cylinders
  67694. var cylinders = geometries.cylinders;
  67695. if (cylinders !== undefined && cylinders !== null) {
  67696. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67697. var parsedCylinder = cylinders[index];
  67698. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67699. }
  67700. }
  67701. // Toruses
  67702. var toruses = geometries.toruses;
  67703. if (toruses !== undefined && toruses !== null) {
  67704. for (index = 0, cache = toruses.length; index < cache; index++) {
  67705. var parsedTorus = toruses[index];
  67706. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67707. }
  67708. }
  67709. // Grounds
  67710. var grounds = geometries.grounds;
  67711. if (grounds !== undefined && grounds !== null) {
  67712. for (index = 0, cache = grounds.length; index < cache; index++) {
  67713. var parsedGround = grounds[index];
  67714. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67715. }
  67716. }
  67717. // Planes
  67718. var planes = geometries.planes;
  67719. if (planes !== undefined && planes !== null) {
  67720. for (index = 0, cache = planes.length; index < cache; index++) {
  67721. var parsedPlane = planes[index];
  67722. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67723. }
  67724. }
  67725. // TorusKnots
  67726. var torusKnots = geometries.torusKnots;
  67727. if (torusKnots !== undefined && torusKnots !== null) {
  67728. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67729. var parsedTorusKnot = torusKnots[index];
  67730. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67731. }
  67732. }
  67733. // VertexData
  67734. var vertexData = geometries.vertexData;
  67735. if (vertexData !== undefined && vertexData !== null) {
  67736. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67737. var parsedVertexData = vertexData[index];
  67738. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67739. }
  67740. }
  67741. addedGeometry.forEach(function (g) {
  67742. if (g) {
  67743. container.geometries.push(g);
  67744. }
  67745. });
  67746. }
  67747. // Transform nodes
  67748. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67749. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67750. var parsedTransformNode = parsedData.transformNodes[index];
  67751. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67752. container.transformNodes.push(node);
  67753. }
  67754. }
  67755. // Meshes
  67756. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67757. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67758. var parsedMesh = parsedData.meshes[index];
  67759. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67760. container.meshes.push(mesh);
  67761. log += (index === 0 ? "\n\tMeshes:" : "");
  67762. log += "\n\t\t" + mesh.toString(fullDetails);
  67763. }
  67764. }
  67765. // Cameras
  67766. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67767. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67768. var parsedCamera = parsedData.cameras[index];
  67769. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67770. container.cameras.push(camera);
  67771. log += (index === 0 ? "\n\tCameras:" : "");
  67772. log += "\n\t\t" + camera.toString(fullDetails);
  67773. }
  67774. }
  67775. // Browsing all the graph to connect the dots
  67776. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67777. var camera = scene.cameras[index];
  67778. if (camera._waitingParentId) {
  67779. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67780. camera._waitingParentId = null;
  67781. }
  67782. }
  67783. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67784. var light_1 = scene.lights[index];
  67785. if (light_1 && light_1._waitingParentId) {
  67786. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67787. light_1._waitingParentId = null;
  67788. }
  67789. }
  67790. // Sounds
  67791. // TODO: add sound
  67792. var loadedSounds = [];
  67793. var loadedSound;
  67794. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67795. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67796. var parsedSound = parsedData.sounds[index];
  67797. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67798. if (!parsedSound.url)
  67799. parsedSound.url = parsedSound.name;
  67800. if (!loadedSounds[parsedSound.url]) {
  67801. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67802. loadedSounds[parsedSound.url] = loadedSound;
  67803. container.sounds.push(loadedSound);
  67804. }
  67805. else {
  67806. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67807. }
  67808. }
  67809. else {
  67810. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67811. }
  67812. }
  67813. }
  67814. loadedSounds = [];
  67815. // Connect parents & children and parse actions
  67816. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67817. var transformNode = scene.transformNodes[index];
  67818. if (transformNode._waitingParentId) {
  67819. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67820. transformNode._waitingParentId = null;
  67821. }
  67822. }
  67823. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67824. var mesh = scene.meshes[index];
  67825. if (mesh._waitingParentId) {
  67826. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67827. mesh._waitingParentId = null;
  67828. }
  67829. if (mesh._waitingActions) {
  67830. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67831. mesh._waitingActions = null;
  67832. }
  67833. }
  67834. // freeze world matrix application
  67835. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67836. var currentMesh = scene.meshes[index];
  67837. if (currentMesh._waitingFreezeWorldMatrix) {
  67838. currentMesh.freezeWorldMatrix();
  67839. currentMesh._waitingFreezeWorldMatrix = null;
  67840. }
  67841. else {
  67842. currentMesh.computeWorldMatrix(true);
  67843. }
  67844. }
  67845. // Particles Systems
  67846. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67847. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67848. var parsedParticleSystem = parsedData.particleSystems[index];
  67849. if (parsedParticleSystem.activeParticleCount) {
  67850. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67851. container.particleSystems.push(ps);
  67852. }
  67853. else {
  67854. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67855. container.particleSystems.push(ps);
  67856. }
  67857. }
  67858. }
  67859. // Lens flares
  67860. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67861. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67862. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67863. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67864. container.lensFlareSystems.push(lf);
  67865. }
  67866. }
  67867. // Shadows
  67868. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67869. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67870. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67871. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67872. container.shadowGenerators.push(sg);
  67873. }
  67874. }
  67875. // Lights exclusions / inclusions
  67876. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67877. var light_2 = scene.lights[index];
  67878. // Excluded check
  67879. if (light_2._excludedMeshesIds.length > 0) {
  67880. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67881. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67882. if (excludedMesh) {
  67883. light_2.excludedMeshes.push(excludedMesh);
  67884. }
  67885. }
  67886. light_2._excludedMeshesIds = [];
  67887. }
  67888. // Included check
  67889. if (light_2._includedOnlyMeshesIds.length > 0) {
  67890. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67891. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67892. if (includedOnlyMesh) {
  67893. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67894. }
  67895. }
  67896. light_2._includedOnlyMeshesIds = [];
  67897. }
  67898. }
  67899. // Effect layers
  67900. if (parsedData.effectLayers) {
  67901. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67902. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67903. container.effectLayers.push(effectLayer);
  67904. }
  67905. }
  67906. // Actions (scene)
  67907. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67908. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67909. }
  67910. if (!addToScene) {
  67911. container.removeAllFromScene();
  67912. }
  67913. }
  67914. catch (err) {
  67915. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67916. if (onError) {
  67917. onError(msg, err);
  67918. }
  67919. else {
  67920. BABYLON.Tools.Log(msg);
  67921. throw err;
  67922. }
  67923. }
  67924. finally {
  67925. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67926. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67927. }
  67928. }
  67929. return container;
  67930. };
  67931. BABYLON.SceneLoader.RegisterPlugin({
  67932. name: "babylon.js",
  67933. extensions: ".babylon",
  67934. canDirectLoad: function (data) {
  67935. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67936. return true;
  67937. }
  67938. return false;
  67939. },
  67940. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67941. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67942. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67943. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67944. // and avoid problems with multiple concurrent .babylon loads.
  67945. var log = "importMesh has failed JSON parse";
  67946. try {
  67947. var parsedData = JSON.parse(data);
  67948. log = "";
  67949. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67950. if (!meshesNames) {
  67951. meshesNames = null;
  67952. }
  67953. else if (!Array.isArray(meshesNames)) {
  67954. meshesNames = [meshesNames];
  67955. }
  67956. var hierarchyIds = new Array();
  67957. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67958. var loadedSkeletonsIds = [];
  67959. var loadedMaterialsIds = [];
  67960. var index;
  67961. var cache;
  67962. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67963. var parsedMesh = parsedData.meshes[index];
  67964. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67965. if (meshesNames !== null) {
  67966. // Remove found mesh name from list.
  67967. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67968. }
  67969. //Geometry?
  67970. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67971. //does the file contain geometries?
  67972. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67973. //find the correct geometry and add it to the scene
  67974. var found = false;
  67975. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67976. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67977. return;
  67978. }
  67979. else {
  67980. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67981. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67982. switch (geometryType) {
  67983. case "boxes":
  67984. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67985. break;
  67986. case "spheres":
  67987. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67988. break;
  67989. case "cylinders":
  67990. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67991. break;
  67992. case "toruses":
  67993. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67994. break;
  67995. case "grounds":
  67996. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67997. break;
  67998. case "planes":
  67999. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68000. break;
  68001. case "torusKnots":
  68002. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68003. break;
  68004. case "vertexData":
  68005. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68006. break;
  68007. }
  68008. found = true;
  68009. }
  68010. });
  68011. }
  68012. });
  68013. if (found === false) {
  68014. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68015. }
  68016. }
  68017. }
  68018. // Material ?
  68019. if (parsedMesh.materialId) {
  68020. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68021. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68022. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68023. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68024. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68025. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68026. var subMatId = parsedMultiMaterial.materials[matIndex];
  68027. loadedMaterialsIds.push(subMatId);
  68028. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68029. if (mat) {
  68030. log += "\n\tMaterial " + mat.toString(fullDetails);
  68031. }
  68032. }
  68033. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68034. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68035. if (mmat) {
  68036. materialFound = true;
  68037. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68038. }
  68039. break;
  68040. }
  68041. }
  68042. }
  68043. if (materialFound === false) {
  68044. loadedMaterialsIds.push(parsedMesh.materialId);
  68045. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68046. if (!mat) {
  68047. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68048. }
  68049. else {
  68050. log += "\n\tMaterial " + mat.toString(fullDetails);
  68051. }
  68052. }
  68053. }
  68054. // Skeleton ?
  68055. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68056. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68057. if (skeletonAlreadyLoaded === false) {
  68058. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68059. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68060. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68061. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68062. skeletons.push(skeleton);
  68063. loadedSkeletonsIds.push(parsedSkeleton.id);
  68064. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68065. }
  68066. }
  68067. }
  68068. }
  68069. // Morph targets ?
  68070. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68071. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68072. var managerData = _a[_i];
  68073. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68074. }
  68075. }
  68076. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68077. meshes.push(mesh);
  68078. log += "\n\tMesh " + mesh.toString(fullDetails);
  68079. }
  68080. }
  68081. // Connecting parents
  68082. var currentMesh;
  68083. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68084. currentMesh = scene.meshes[index];
  68085. if (currentMesh._waitingParentId) {
  68086. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68087. currentMesh._waitingParentId = null;
  68088. }
  68089. }
  68090. // freeze and compute world matrix application
  68091. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68092. currentMesh = scene.meshes[index];
  68093. if (currentMesh._waitingFreezeWorldMatrix) {
  68094. currentMesh.freezeWorldMatrix();
  68095. currentMesh._waitingFreezeWorldMatrix = null;
  68096. }
  68097. else {
  68098. currentMesh.computeWorldMatrix(true);
  68099. }
  68100. }
  68101. }
  68102. // Particles
  68103. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68104. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68105. var parsedParticleSystem = parsedData.particleSystems[index];
  68106. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68107. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68108. }
  68109. }
  68110. }
  68111. return true;
  68112. }
  68113. catch (err) {
  68114. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68115. if (onError) {
  68116. onError(msg, err);
  68117. }
  68118. else {
  68119. BABYLON.Tools.Log(msg);
  68120. throw err;
  68121. }
  68122. }
  68123. finally {
  68124. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68125. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68126. }
  68127. }
  68128. return false;
  68129. },
  68130. load: function (scene, data, rootUrl, onError) {
  68131. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68132. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68133. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68134. // and avoid problems with multiple concurrent .babylon loads.
  68135. var log = "importScene has failed JSON parse";
  68136. try {
  68137. var parsedData = JSON.parse(data);
  68138. log = "";
  68139. // Scene
  68140. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68141. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68142. }
  68143. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68144. scene.autoClear = parsedData.autoClear;
  68145. }
  68146. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68147. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68148. }
  68149. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68150. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68151. }
  68152. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68153. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68154. }
  68155. // Fog
  68156. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68157. scene.fogMode = parsedData.fogMode;
  68158. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68159. scene.fogStart = parsedData.fogStart;
  68160. scene.fogEnd = parsedData.fogEnd;
  68161. scene.fogDensity = parsedData.fogDensity;
  68162. log += "\tFog mode for scene: ";
  68163. switch (scene.fogMode) {
  68164. // getters not compiling, so using hardcoded
  68165. case 1:
  68166. log += "exp\n";
  68167. break;
  68168. case 2:
  68169. log += "exp2\n";
  68170. break;
  68171. case 3:
  68172. log += "linear\n";
  68173. break;
  68174. }
  68175. }
  68176. //Physics
  68177. if (parsedData.physicsEnabled) {
  68178. var physicsPlugin;
  68179. if (parsedData.physicsEngine === "cannon") {
  68180. physicsPlugin = new BABYLON.CannonJSPlugin();
  68181. }
  68182. else if (parsedData.physicsEngine === "oimo") {
  68183. physicsPlugin = new BABYLON.OimoJSPlugin();
  68184. }
  68185. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68186. //else - default engine, which is currently oimo
  68187. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68188. scene.enablePhysics(physicsGravity, physicsPlugin);
  68189. }
  68190. // Metadata
  68191. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68192. scene.metadata = parsedData.metadata;
  68193. }
  68194. //collisions, if defined. otherwise, default is true
  68195. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68196. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68197. }
  68198. scene.workerCollisions = !!parsedData.workerCollisions;
  68199. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68200. if (!container) {
  68201. return false;
  68202. }
  68203. if (parsedData.autoAnimate) {
  68204. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68205. }
  68206. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68207. scene.setActiveCameraByID(parsedData.activeCameraID);
  68208. }
  68209. // Environment texture
  68210. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68211. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68212. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68213. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68214. if (parsedData.environmentTextureRotationY) {
  68215. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68216. }
  68217. scene.environmentTexture = hdrTexture;
  68218. }
  68219. else {
  68220. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68221. if (parsedData.environmentTextureRotationY) {
  68222. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68223. }
  68224. scene.environmentTexture = cubeTexture;
  68225. }
  68226. if (parsedData.createDefaultSkybox === true) {
  68227. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68228. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68229. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68230. }
  68231. }
  68232. // Finish
  68233. return true;
  68234. }
  68235. catch (err) {
  68236. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68237. if (onError) {
  68238. onError(msg, err);
  68239. }
  68240. else {
  68241. BABYLON.Tools.Log(msg);
  68242. throw err;
  68243. }
  68244. }
  68245. finally {
  68246. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68247. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68248. }
  68249. }
  68250. return false;
  68251. },
  68252. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68253. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68254. return container;
  68255. }
  68256. });
  68257. })(BABYLON || (BABYLON = {}));
  68258. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68259. var BABYLON;
  68260. (function (BABYLON) {
  68261. var FilesInput = /** @class */ (function () {
  68262. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68263. this.onProcessFileCallback = function () { return true; };
  68264. this._engine = engine;
  68265. this._currentScene = scene;
  68266. this._sceneLoadedCallback = sceneLoadedCallback;
  68267. this._progressCallback = progressCallback;
  68268. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68269. this._textureLoadingCallback = textureLoadingCallback;
  68270. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68271. this._onReloadCallback = onReloadCallback;
  68272. this._errorCallback = errorCallback;
  68273. }
  68274. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68275. var _this = this;
  68276. if (elementToMonitor) {
  68277. this._elementToMonitor = elementToMonitor;
  68278. this._dragEnterHandler = function (e) { _this.drag(e); };
  68279. this._dragOverHandler = function (e) { _this.drag(e); };
  68280. this._dropHandler = function (e) { _this.drop(e); };
  68281. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68282. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68283. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68284. }
  68285. };
  68286. FilesInput.prototype.dispose = function () {
  68287. if (!this._elementToMonitor) {
  68288. return;
  68289. }
  68290. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68291. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68292. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68293. };
  68294. FilesInput.prototype.renderFunction = function () {
  68295. if (this._additionalRenderLoopLogicCallback) {
  68296. this._additionalRenderLoopLogicCallback();
  68297. }
  68298. if (this._currentScene) {
  68299. if (this._textureLoadingCallback) {
  68300. var remaining = this._currentScene.getWaitingItemsCount();
  68301. if (remaining > 0) {
  68302. this._textureLoadingCallback(remaining);
  68303. }
  68304. }
  68305. this._currentScene.render();
  68306. }
  68307. };
  68308. FilesInput.prototype.drag = function (e) {
  68309. e.stopPropagation();
  68310. e.preventDefault();
  68311. };
  68312. FilesInput.prototype.drop = function (eventDrop) {
  68313. eventDrop.stopPropagation();
  68314. eventDrop.preventDefault();
  68315. this.loadFiles(eventDrop);
  68316. };
  68317. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68318. var _this = this;
  68319. var reader = folder.createReader();
  68320. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68321. reader.readEntries(function (entries) {
  68322. remaining.count += entries.length;
  68323. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68324. var entry = entries_1[_i];
  68325. if (entry.isFile) {
  68326. entry.file(function (file) {
  68327. file.correctName = relativePath + file.name;
  68328. files.push(file);
  68329. if (--remaining.count === 0) {
  68330. callback();
  68331. }
  68332. });
  68333. }
  68334. else if (entry.isDirectory) {
  68335. _this._traverseFolder(entry, files, remaining, callback);
  68336. }
  68337. }
  68338. if (--remaining.count) {
  68339. callback();
  68340. }
  68341. });
  68342. };
  68343. FilesInput.prototype._processFiles = function (files) {
  68344. for (var i = 0; i < files.length; i++) {
  68345. var name = files[i].correctName.toLowerCase();
  68346. var extension = name.split('.').pop();
  68347. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68348. continue;
  68349. }
  68350. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68351. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68352. this._sceneFileToLoad = files[i];
  68353. }
  68354. else {
  68355. FilesInput.FilesToLoad[name] = files[i];
  68356. }
  68357. }
  68358. };
  68359. FilesInput.prototype.loadFiles = function (event) {
  68360. var _this = this;
  68361. if (this._startingProcessingFilesCallback)
  68362. this._startingProcessingFilesCallback();
  68363. // Handling data transfer via drag'n'drop
  68364. if (event && event.dataTransfer && event.dataTransfer.files) {
  68365. this._filesToLoad = event.dataTransfer.files;
  68366. }
  68367. // Handling files from input files
  68368. if (event && event.target && event.target.files) {
  68369. this._filesToLoad = event.target.files;
  68370. }
  68371. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68372. var files_1 = new Array();
  68373. var folders = [];
  68374. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68375. for (var i = 0; i < this._filesToLoad.length; i++) {
  68376. var fileToLoad = this._filesToLoad[i];
  68377. var name_1 = fileToLoad.name.toLowerCase();
  68378. var entry = void 0;
  68379. fileToLoad.correctName = name_1;
  68380. if (items) {
  68381. var item = items[i];
  68382. if (item.getAsEntry) {
  68383. entry = item.getAsEntry();
  68384. }
  68385. else if (item.webkitGetAsEntry) {
  68386. entry = item.webkitGetAsEntry();
  68387. }
  68388. }
  68389. if (!entry) {
  68390. files_1.push(fileToLoad);
  68391. }
  68392. else {
  68393. if (entry.isDirectory) {
  68394. folders.push(entry);
  68395. }
  68396. else {
  68397. files_1.push(fileToLoad);
  68398. }
  68399. }
  68400. }
  68401. if (folders.length === 0) {
  68402. this._processFiles(files_1);
  68403. this._processReload();
  68404. }
  68405. else {
  68406. var remaining = { count: folders.length };
  68407. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68408. var folder = folders_1[_i];
  68409. this._traverseFolder(folder, files_1, remaining, function () {
  68410. _this._processFiles(files_1);
  68411. if (remaining.count === 0) {
  68412. _this._processReload();
  68413. }
  68414. });
  68415. }
  68416. }
  68417. }
  68418. };
  68419. FilesInput.prototype._processReload = function () {
  68420. if (this._onReloadCallback) {
  68421. this._onReloadCallback(this._sceneFileToLoad);
  68422. }
  68423. else {
  68424. this.reload();
  68425. }
  68426. };
  68427. FilesInput.prototype.reload = function () {
  68428. var _this = this;
  68429. // If a scene file has been provided
  68430. if (this._sceneFileToLoad) {
  68431. if (this._currentScene) {
  68432. if (BABYLON.Tools.errorsCount > 0) {
  68433. BABYLON.Tools.ClearLogCache();
  68434. }
  68435. this._engine.stopRenderLoop();
  68436. this._currentScene.dispose();
  68437. }
  68438. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68439. if (_this._progressCallback) {
  68440. _this._progressCallback(progress);
  68441. }
  68442. }).then(function (scene) {
  68443. _this._currentScene = scene;
  68444. if (_this._sceneLoadedCallback) {
  68445. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68446. }
  68447. // Wait for textures and shaders to be ready
  68448. _this._currentScene.executeWhenReady(function () {
  68449. _this._engine.runRenderLoop(function () {
  68450. _this.renderFunction();
  68451. });
  68452. });
  68453. }).catch(function (error) {
  68454. if (_this._errorCallback) {
  68455. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68456. }
  68457. });
  68458. }
  68459. else {
  68460. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68461. }
  68462. };
  68463. FilesInput.FilesToLoad = {};
  68464. return FilesInput;
  68465. }());
  68466. BABYLON.FilesInput = FilesInput;
  68467. })(BABYLON || (BABYLON = {}));
  68468. //# sourceMappingURL=babylon.filesInput.js.map
  68469. var BABYLON;
  68470. (function (BABYLON) {
  68471. /**
  68472. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68473. * The underlying implementation relies on an associative array to ensure the best performances.
  68474. * The value can be anything including 'null' but except 'undefined'
  68475. */
  68476. var StringDictionary = /** @class */ (function () {
  68477. function StringDictionary() {
  68478. this._count = 0;
  68479. this._data = {};
  68480. }
  68481. /**
  68482. * This will clear this dictionary and copy the content from the 'source' one.
  68483. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68484. * @param source the dictionary to take the content from and copy to this dictionary
  68485. */
  68486. StringDictionary.prototype.copyFrom = function (source) {
  68487. var _this = this;
  68488. this.clear();
  68489. source.forEach(function (t, v) { return _this.add(t, v); });
  68490. };
  68491. /**
  68492. * Get a value based from its key
  68493. * @param key the given key to get the matching value from
  68494. * @return the value if found, otherwise undefined is returned
  68495. */
  68496. StringDictionary.prototype.get = function (key) {
  68497. var val = this._data[key];
  68498. if (val !== undefined) {
  68499. return val;
  68500. }
  68501. return undefined;
  68502. };
  68503. /**
  68504. * Get a value from its key or add it if it doesn't exist.
  68505. * This method will ensure you that a given key/data will be present in the dictionary.
  68506. * @param key the given key to get the matching value from
  68507. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68508. * The factory will only be invoked if there's no data for the given key.
  68509. * @return the value corresponding to the key.
  68510. */
  68511. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68512. var val = this.get(key);
  68513. if (val !== undefined) {
  68514. return val;
  68515. }
  68516. val = factory(key);
  68517. if (val) {
  68518. this.add(key, val);
  68519. }
  68520. return val;
  68521. };
  68522. /**
  68523. * Get a value from its key if present in the dictionary otherwise add it
  68524. * @param key the key to get the value from
  68525. * @param val if there's no such key/value pair in the dictionary add it with this value
  68526. * @return the value corresponding to the key
  68527. */
  68528. StringDictionary.prototype.getOrAdd = function (key, val) {
  68529. var curVal = this.get(key);
  68530. if (curVal !== undefined) {
  68531. return curVal;
  68532. }
  68533. this.add(key, val);
  68534. return val;
  68535. };
  68536. /**
  68537. * Check if there's a given key in the dictionary
  68538. * @param key the key to check for
  68539. * @return true if the key is present, false otherwise
  68540. */
  68541. StringDictionary.prototype.contains = function (key) {
  68542. return this._data[key] !== undefined;
  68543. };
  68544. /**
  68545. * Add a new key and its corresponding value
  68546. * @param key the key to add
  68547. * @param value the value corresponding to the key
  68548. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  68549. */
  68550. StringDictionary.prototype.add = function (key, value) {
  68551. if (this._data[key] !== undefined) {
  68552. return false;
  68553. }
  68554. this._data[key] = value;
  68555. ++this._count;
  68556. return true;
  68557. };
  68558. StringDictionary.prototype.set = function (key, value) {
  68559. if (this._data[key] === undefined) {
  68560. return false;
  68561. }
  68562. this._data[key] = value;
  68563. return true;
  68564. };
  68565. /**
  68566. * Get the element of the given key and remove it from the dictionary
  68567. * @param key
  68568. */
  68569. StringDictionary.prototype.getAndRemove = function (key) {
  68570. var val = this.get(key);
  68571. if (val !== undefined) {
  68572. delete this._data[key];
  68573. --this._count;
  68574. return val;
  68575. }
  68576. return null;
  68577. };
  68578. /**
  68579. * Remove a key/value from the dictionary.
  68580. * @param key the key to remove
  68581. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68582. */
  68583. StringDictionary.prototype.remove = function (key) {
  68584. if (this.contains(key)) {
  68585. delete this._data[key];
  68586. --this._count;
  68587. return true;
  68588. }
  68589. return false;
  68590. };
  68591. /**
  68592. * Clear the whole content of the dictionary
  68593. */
  68594. StringDictionary.prototype.clear = function () {
  68595. this._data = {};
  68596. this._count = 0;
  68597. };
  68598. Object.defineProperty(StringDictionary.prototype, "count", {
  68599. get: function () {
  68600. return this._count;
  68601. },
  68602. enumerable: true,
  68603. configurable: true
  68604. });
  68605. /**
  68606. * Execute a callback on each key/val of the dictionary.
  68607. * Note that you can remove any element in this dictionary in the callback implementation
  68608. * @param callback the callback to execute on a given key/value pair
  68609. */
  68610. StringDictionary.prototype.forEach = function (callback) {
  68611. for (var cur in this._data) {
  68612. var val = this._data[cur];
  68613. callback(cur, val);
  68614. }
  68615. };
  68616. /**
  68617. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68618. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68619. * Note that you can remove any element in this dictionary in the callback implementation
  68620. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68621. */
  68622. StringDictionary.prototype.first = function (callback) {
  68623. for (var cur in this._data) {
  68624. var val = this._data[cur];
  68625. var res = callback(cur, val);
  68626. if (res) {
  68627. return res;
  68628. }
  68629. }
  68630. return null;
  68631. };
  68632. return StringDictionary;
  68633. }());
  68634. BABYLON.StringDictionary = StringDictionary;
  68635. })(BABYLON || (BABYLON = {}));
  68636. //# sourceMappingURL=babylon.stringDictionary.js.map
  68637. var BABYLON;
  68638. (function (BABYLON) {
  68639. var Tags = /** @class */ (function () {
  68640. function Tags() {
  68641. }
  68642. Tags.EnableFor = function (obj) {
  68643. obj._tags = obj._tags || {};
  68644. obj.hasTags = function () {
  68645. return Tags.HasTags(obj);
  68646. };
  68647. obj.addTags = function (tagsString) {
  68648. return Tags.AddTagsTo(obj, tagsString);
  68649. };
  68650. obj.removeTags = function (tagsString) {
  68651. return Tags.RemoveTagsFrom(obj, tagsString);
  68652. };
  68653. obj.matchesTagsQuery = function (tagsQuery) {
  68654. return Tags.MatchesQuery(obj, tagsQuery);
  68655. };
  68656. };
  68657. Tags.DisableFor = function (obj) {
  68658. delete obj._tags;
  68659. delete obj.hasTags;
  68660. delete obj.addTags;
  68661. delete obj.removeTags;
  68662. delete obj.matchesTagsQuery;
  68663. };
  68664. Tags.HasTags = function (obj) {
  68665. if (!obj._tags) {
  68666. return false;
  68667. }
  68668. return !BABYLON.Tools.IsEmpty(obj._tags);
  68669. };
  68670. Tags.GetTags = function (obj, asString) {
  68671. if (asString === void 0) { asString = true; }
  68672. if (!obj._tags) {
  68673. return null;
  68674. }
  68675. if (asString) {
  68676. var tagsArray = [];
  68677. for (var tag in obj._tags) {
  68678. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68679. tagsArray.push(tag);
  68680. }
  68681. }
  68682. return tagsArray.join(" ");
  68683. }
  68684. else {
  68685. return obj._tags;
  68686. }
  68687. };
  68688. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68689. // a tag cannot start with '||', '&&', and '!'
  68690. // it cannot contain whitespaces
  68691. Tags.AddTagsTo = function (obj, tagsString) {
  68692. if (!tagsString) {
  68693. return;
  68694. }
  68695. if (typeof tagsString !== "string") {
  68696. return;
  68697. }
  68698. var tags = tagsString.split(" ");
  68699. tags.forEach(function (tag, index, array) {
  68700. Tags._AddTagTo(obj, tag);
  68701. });
  68702. };
  68703. Tags._AddTagTo = function (obj, tag) {
  68704. tag = tag.trim();
  68705. if (tag === "" || tag === "true" || tag === "false") {
  68706. return;
  68707. }
  68708. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68709. return;
  68710. }
  68711. Tags.EnableFor(obj);
  68712. obj._tags[tag] = true;
  68713. };
  68714. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68715. if (!Tags.HasTags(obj)) {
  68716. return;
  68717. }
  68718. var tags = tagsString.split(" ");
  68719. for (var t in tags) {
  68720. Tags._RemoveTagFrom(obj, tags[t]);
  68721. }
  68722. };
  68723. Tags._RemoveTagFrom = function (obj, tag) {
  68724. delete obj._tags[tag];
  68725. };
  68726. Tags.MatchesQuery = function (obj, tagsQuery) {
  68727. if (tagsQuery === undefined) {
  68728. return true;
  68729. }
  68730. if (tagsQuery === "") {
  68731. return Tags.HasTags(obj);
  68732. }
  68733. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68734. };
  68735. return Tags;
  68736. }());
  68737. BABYLON.Tags = Tags;
  68738. })(BABYLON || (BABYLON = {}));
  68739. //# sourceMappingURL=babylon.tags.js.map
  68740. var BABYLON;
  68741. (function (BABYLON) {
  68742. /**
  68743. * Class used to evalaute queries containing `and` and `or` operators
  68744. */
  68745. var AndOrNotEvaluator = /** @class */ (function () {
  68746. function AndOrNotEvaluator() {
  68747. }
  68748. /**
  68749. * Evaluate a query
  68750. * @param query defines the query to evaluate
  68751. * @param evaluateCallback defines the callback used to filter result
  68752. * @returns true if the query matches
  68753. */
  68754. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68755. if (!query.match(/\([^\(\)]*\)/g)) {
  68756. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68757. }
  68758. else {
  68759. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68760. // remove parenthesis
  68761. r = r.slice(1, r.length - 1);
  68762. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68763. });
  68764. }
  68765. if (query === "true") {
  68766. return true;
  68767. }
  68768. if (query === "false") {
  68769. return false;
  68770. }
  68771. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68772. };
  68773. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68774. evaluateCallback = evaluateCallback || (function (r) {
  68775. return r === "true" ? true : false;
  68776. });
  68777. var result;
  68778. var or = parenthesisContent.split("||");
  68779. for (var i in or) {
  68780. if (or.hasOwnProperty(i)) {
  68781. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68782. var and = ori.split("&&");
  68783. if (and.length > 1) {
  68784. for (var j = 0; j < and.length; ++j) {
  68785. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68786. if (andj !== "true" && andj !== "false") {
  68787. if (andj[0] === "!") {
  68788. result = !evaluateCallback(andj.substring(1));
  68789. }
  68790. else {
  68791. result = evaluateCallback(andj);
  68792. }
  68793. }
  68794. else {
  68795. result = andj === "true" ? true : false;
  68796. }
  68797. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68798. ori = "false";
  68799. break;
  68800. }
  68801. }
  68802. }
  68803. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68804. result = true;
  68805. break;
  68806. }
  68807. // result equals false (or undefined)
  68808. if (ori !== "true" && ori !== "false") {
  68809. if (ori[0] === "!") {
  68810. result = !evaluateCallback(ori.substring(1));
  68811. }
  68812. else {
  68813. result = evaluateCallback(ori);
  68814. }
  68815. }
  68816. else {
  68817. result = ori === "true" ? true : false;
  68818. }
  68819. }
  68820. }
  68821. // the whole parenthesis scope is replaced by 'true' or 'false'
  68822. return result ? "true" : "false";
  68823. };
  68824. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68825. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68826. // remove whitespaces
  68827. r = r.replace(/[\s]/g, function () { return ""; });
  68828. return r.length % 2 ? "!" : "";
  68829. });
  68830. booleanString = booleanString.trim();
  68831. if (booleanString === "!true") {
  68832. booleanString = "false";
  68833. }
  68834. else if (booleanString === "!false") {
  68835. booleanString = "true";
  68836. }
  68837. return booleanString;
  68838. };
  68839. return AndOrNotEvaluator;
  68840. }());
  68841. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68842. })(BABYLON || (BABYLON = {}));
  68843. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68844. var BABYLON;
  68845. (function (BABYLON) {
  68846. /**
  68847. * Class used to enable access to IndexedDB
  68848. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68849. */
  68850. var Database = /** @class */ (function () {
  68851. /**
  68852. * Creates a new Database
  68853. * @param urlToScene defines the url to load the scene
  68854. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68855. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68856. */
  68857. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68858. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68859. var _this = this;
  68860. // Handling various flavors of prefixed version of IndexedDB
  68861. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68862. this.callbackManifestChecked = callbackManifestChecked;
  68863. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68864. this.db = null;
  68865. this._enableSceneOffline = false;
  68866. this._enableTexturesOffline = false;
  68867. this.manifestVersionFound = 0;
  68868. this.mustUpdateRessources = false;
  68869. this.hasReachedQuota = false;
  68870. if (!Database.IDBStorageEnabled) {
  68871. this.callbackManifestChecked(true);
  68872. }
  68873. else {
  68874. if (disableManifestCheck) {
  68875. this._enableSceneOffline = true;
  68876. this._enableTexturesOffline = true;
  68877. this.manifestVersionFound = 1;
  68878. BABYLON.Tools.SetImmediate(function () {
  68879. _this.callbackManifestChecked(true);
  68880. });
  68881. }
  68882. else {
  68883. this._checkManifestFile();
  68884. }
  68885. }
  68886. }
  68887. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68888. /**
  68889. * Gets a boolean indicating if scene must be saved in the database
  68890. */
  68891. get: function () {
  68892. return this._enableSceneOffline;
  68893. },
  68894. enumerable: true,
  68895. configurable: true
  68896. });
  68897. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68898. /**
  68899. * Gets a boolean indicating if textures must be saved in the database
  68900. */
  68901. get: function () {
  68902. return this._enableTexturesOffline;
  68903. },
  68904. enumerable: true,
  68905. configurable: true
  68906. });
  68907. Database.prototype._checkManifestFile = function () {
  68908. var _this = this;
  68909. var noManifestFile = function () {
  68910. _this._enableSceneOffline = false;
  68911. _this._enableTexturesOffline = false;
  68912. _this.callbackManifestChecked(false);
  68913. };
  68914. var timeStampUsed = false;
  68915. var manifestURL = this.currentSceneUrl + ".manifest";
  68916. var xhr = new XMLHttpRequest();
  68917. if (navigator.onLine) {
  68918. // Adding a timestamp to by-pass browsers' cache
  68919. timeStampUsed = true;
  68920. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68921. }
  68922. xhr.open("GET", manifestURL, true);
  68923. xhr.addEventListener("load", function () {
  68924. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68925. try {
  68926. var manifestFile = JSON.parse(xhr.response);
  68927. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68928. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68929. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68930. _this.manifestVersionFound = manifestFile.version;
  68931. }
  68932. if (_this.callbackManifestChecked) {
  68933. _this.callbackManifestChecked(true);
  68934. }
  68935. }
  68936. catch (ex) {
  68937. noManifestFile();
  68938. }
  68939. }
  68940. else {
  68941. noManifestFile();
  68942. }
  68943. }, false);
  68944. xhr.addEventListener("error", function (event) {
  68945. if (timeStampUsed) {
  68946. timeStampUsed = false;
  68947. // Let's retry without the timeStamp
  68948. // It could fail when coupled with HTML5 Offline API
  68949. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68950. xhr.open("GET", retryManifestURL, true);
  68951. xhr.send();
  68952. }
  68953. else {
  68954. noManifestFile();
  68955. }
  68956. }, false);
  68957. try {
  68958. xhr.send();
  68959. }
  68960. catch (ex) {
  68961. BABYLON.Tools.Error("Error on XHR send request.");
  68962. this.callbackManifestChecked(false);
  68963. }
  68964. };
  68965. /**
  68966. * Open the database and make it available
  68967. * @param successCallback defines the callback to call on success
  68968. * @param errorCallback defines the callback to call on error
  68969. */
  68970. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68971. var _this = this;
  68972. var handleError = function () {
  68973. _this.isSupported = false;
  68974. if (errorCallback)
  68975. errorCallback();
  68976. };
  68977. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68978. // Your browser doesn't support IndexedDB
  68979. this.isSupported = false;
  68980. if (errorCallback)
  68981. errorCallback();
  68982. }
  68983. else {
  68984. // If the DB hasn't been opened or created yet
  68985. if (!this.db) {
  68986. this.hasReachedQuota = false;
  68987. this.isSupported = true;
  68988. var request = this.idbFactory.open("babylonjs", 1);
  68989. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68990. request.onerror = function (event) {
  68991. handleError();
  68992. };
  68993. // executes when a version change transaction cannot complete due to other active transactions
  68994. request.onblocked = function (event) {
  68995. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68996. handleError();
  68997. };
  68998. // DB has been opened successfully
  68999. request.onsuccess = function (event) {
  69000. _this.db = request.result;
  69001. successCallback();
  69002. };
  69003. // Initialization of the DB. Creating Scenes & Textures stores
  69004. request.onupgradeneeded = function (event) {
  69005. _this.db = (event.target).result;
  69006. if (_this.db) {
  69007. try {
  69008. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69009. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69010. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69011. }
  69012. catch (ex) {
  69013. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69014. handleError();
  69015. }
  69016. }
  69017. };
  69018. }
  69019. // DB has already been created and opened
  69020. else {
  69021. if (successCallback)
  69022. successCallback();
  69023. }
  69024. }
  69025. };
  69026. /**
  69027. * Loads an image from the database
  69028. * @param url defines the url to load from
  69029. * @param image defines the target DOM image
  69030. */
  69031. Database.prototype.loadImageFromDB = function (url, image) {
  69032. var _this = this;
  69033. var completeURL = Database._ReturnFullUrlLocation(url);
  69034. var saveAndLoadImage = function () {
  69035. if (!_this.hasReachedQuota && _this.db !== null) {
  69036. // the texture is not yet in the DB, let's try to save it
  69037. _this._saveImageIntoDBAsync(completeURL, image);
  69038. }
  69039. // If the texture is not in the DB and we've reached the DB quota limit
  69040. // let's load it directly from the web
  69041. else {
  69042. image.src = url;
  69043. }
  69044. };
  69045. if (!this.mustUpdateRessources) {
  69046. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69047. }
  69048. // First time we're download the images or update requested in the manifest file by a version change
  69049. else {
  69050. saveAndLoadImage();
  69051. }
  69052. };
  69053. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69054. if (this.isSupported && this.db !== null) {
  69055. var texture;
  69056. var transaction = this.db.transaction(["textures"]);
  69057. transaction.onabort = function (event) {
  69058. image.src = url;
  69059. };
  69060. transaction.oncomplete = function (event) {
  69061. var blobTextureURL;
  69062. if (texture) {
  69063. var URL = window.URL || window.webkitURL;
  69064. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69065. image.onerror = function () {
  69066. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69067. image.src = url;
  69068. };
  69069. image.src = blobTextureURL;
  69070. }
  69071. else {
  69072. notInDBCallback();
  69073. }
  69074. };
  69075. var getRequest = transaction.objectStore("textures").get(url);
  69076. getRequest.onsuccess = function (event) {
  69077. texture = (event.target).result;
  69078. };
  69079. getRequest.onerror = function (event) {
  69080. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69081. image.src = url;
  69082. };
  69083. }
  69084. else {
  69085. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69086. image.src = url;
  69087. }
  69088. };
  69089. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69090. var _this = this;
  69091. if (this.isSupported) {
  69092. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69093. var generateBlobUrl = function () {
  69094. var blobTextureURL;
  69095. if (blob) {
  69096. var URL = window.URL || window.webkitURL;
  69097. try {
  69098. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69099. }
  69100. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69101. catch (ex) {
  69102. blobTextureURL = URL.createObjectURL(blob);
  69103. }
  69104. }
  69105. if (blobTextureURL) {
  69106. image.src = blobTextureURL;
  69107. }
  69108. };
  69109. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69110. var xhr = new XMLHttpRequest(), blob;
  69111. xhr.open("GET", url, true);
  69112. xhr.responseType = "blob";
  69113. xhr.addEventListener("load", function () {
  69114. if (xhr.status === 200 && _this.db) {
  69115. // Blob as response (XHR2)
  69116. blob = xhr.response;
  69117. var transaction = _this.db.transaction(["textures"], "readwrite");
  69118. // the transaction could abort because of a QuotaExceededError error
  69119. transaction.onabort = function (event) {
  69120. try {
  69121. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69122. var srcElement = (event.srcElement || event.target);
  69123. var error = srcElement.error;
  69124. if (error && error.name === "QuotaExceededError") {
  69125. _this.hasReachedQuota = true;
  69126. }
  69127. }
  69128. catch (ex) { }
  69129. generateBlobUrl();
  69130. };
  69131. transaction.oncomplete = function (event) {
  69132. generateBlobUrl();
  69133. };
  69134. var newTexture = { textureUrl: url, data: blob };
  69135. try {
  69136. // Put the blob into the dabase
  69137. var addRequest = transaction.objectStore("textures").put(newTexture);
  69138. addRequest.onsuccess = function (event) {
  69139. };
  69140. addRequest.onerror = function (event) {
  69141. generateBlobUrl();
  69142. };
  69143. }
  69144. catch (ex) {
  69145. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69146. if (ex.code === 25) {
  69147. Database.IsUASupportingBlobStorage = false;
  69148. }
  69149. image.src = url;
  69150. }
  69151. }
  69152. else {
  69153. image.src = url;
  69154. }
  69155. }, false);
  69156. xhr.addEventListener("error", function (event) {
  69157. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69158. image.src = url;
  69159. }, false);
  69160. xhr.send();
  69161. }
  69162. else {
  69163. image.src = url;
  69164. }
  69165. }
  69166. else {
  69167. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69168. image.src = url;
  69169. }
  69170. };
  69171. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69172. var _this = this;
  69173. var updateVersion = function () {
  69174. // the version is not yet in the DB or we need to update it
  69175. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69176. };
  69177. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69178. };
  69179. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69180. var _this = this;
  69181. if (this.isSupported && this.db) {
  69182. var version;
  69183. try {
  69184. var transaction = this.db.transaction(["versions"]);
  69185. transaction.oncomplete = function (event) {
  69186. if (version) {
  69187. // If the version in the JSON file is different from the version in DB
  69188. if (_this.manifestVersionFound !== version.data) {
  69189. _this.mustUpdateRessources = true;
  69190. updateInDBCallback();
  69191. }
  69192. else {
  69193. callback(version.data);
  69194. }
  69195. }
  69196. // version was not found in DB
  69197. else {
  69198. _this.mustUpdateRessources = true;
  69199. updateInDBCallback();
  69200. }
  69201. };
  69202. transaction.onabort = function (event) {
  69203. callback(-1);
  69204. };
  69205. var getRequest = transaction.objectStore("versions").get(url);
  69206. getRequest.onsuccess = function (event) {
  69207. version = (event.target).result;
  69208. };
  69209. getRequest.onerror = function (event) {
  69210. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69211. callback(-1);
  69212. };
  69213. }
  69214. catch (ex) {
  69215. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69216. callback(-1);
  69217. }
  69218. }
  69219. else {
  69220. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69221. callback(-1);
  69222. }
  69223. };
  69224. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69225. var _this = this;
  69226. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69227. try {
  69228. // Open a transaction to the database
  69229. var transaction = this.db.transaction(["versions"], "readwrite");
  69230. // the transaction could abort because of a QuotaExceededError error
  69231. transaction.onabort = function (event) {
  69232. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69233. var error = event.srcElement['error'];
  69234. if (error && error.name === "QuotaExceededError") {
  69235. _this.hasReachedQuota = true;
  69236. }
  69237. }
  69238. catch (ex) { }
  69239. callback(-1);
  69240. };
  69241. transaction.oncomplete = function (event) {
  69242. callback(_this.manifestVersionFound);
  69243. };
  69244. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69245. // Put the scene into the database
  69246. var addRequest = transaction.objectStore("versions").put(newVersion);
  69247. addRequest.onsuccess = function (event) {
  69248. };
  69249. addRequest.onerror = function (event) {
  69250. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69251. };
  69252. }
  69253. catch (ex) {
  69254. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69255. callback(-1);
  69256. }
  69257. }
  69258. else {
  69259. callback(-1);
  69260. }
  69261. };
  69262. /**
  69263. * Loads a file from database
  69264. * @param url defines the URL to load from
  69265. * @param sceneLoaded defines a callback to call on success
  69266. * @param progressCallBack defines a callback to call when progress changed
  69267. * @param errorCallback defines a callback to call on error
  69268. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69269. */
  69270. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69271. var _this = this;
  69272. var completeUrl = Database._ReturnFullUrlLocation(url);
  69273. var saveAndLoadFile = function () {
  69274. // the scene is not yet in the DB, let's try to save it
  69275. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69276. };
  69277. this._checkVersionFromDB(completeUrl, function (version) {
  69278. if (version !== -1) {
  69279. if (!_this.mustUpdateRessources) {
  69280. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69281. }
  69282. else {
  69283. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69284. }
  69285. }
  69286. else {
  69287. if (errorCallback) {
  69288. errorCallback();
  69289. }
  69290. }
  69291. });
  69292. };
  69293. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69294. if (this.isSupported && this.db) {
  69295. var targetStore;
  69296. if (url.indexOf(".babylon") !== -1) {
  69297. targetStore = "scenes";
  69298. }
  69299. else {
  69300. targetStore = "textures";
  69301. }
  69302. var file;
  69303. var transaction = this.db.transaction([targetStore]);
  69304. transaction.oncomplete = function (event) {
  69305. if (file) {
  69306. callback(file.data);
  69307. }
  69308. // file was not found in DB
  69309. else {
  69310. notInDBCallback();
  69311. }
  69312. };
  69313. transaction.onabort = function (event) {
  69314. notInDBCallback();
  69315. };
  69316. var getRequest = transaction.objectStore(targetStore).get(url);
  69317. getRequest.onsuccess = function (event) {
  69318. file = (event.target).result;
  69319. };
  69320. getRequest.onerror = function (event) {
  69321. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69322. notInDBCallback();
  69323. };
  69324. }
  69325. else {
  69326. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69327. callback();
  69328. }
  69329. };
  69330. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69331. var _this = this;
  69332. if (this.isSupported) {
  69333. var targetStore;
  69334. if (url.indexOf(".babylon") !== -1) {
  69335. targetStore = "scenes";
  69336. }
  69337. else {
  69338. targetStore = "textures";
  69339. }
  69340. // Create XHR
  69341. var xhr = new XMLHttpRequest();
  69342. var fileData;
  69343. xhr.open("GET", url, true);
  69344. if (useArrayBuffer) {
  69345. xhr.responseType = "arraybuffer";
  69346. }
  69347. if (progressCallback) {
  69348. xhr.onprogress = progressCallback;
  69349. }
  69350. xhr.addEventListener("load", function () {
  69351. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69352. // Blob as response (XHR2)
  69353. //fileData = xhr.responseText;
  69354. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69355. if (!_this.hasReachedQuota && _this.db) {
  69356. // Open a transaction to the database
  69357. var transaction = _this.db.transaction([targetStore], "readwrite");
  69358. // the transaction could abort because of a QuotaExceededError error
  69359. transaction.onabort = function (event) {
  69360. try {
  69361. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69362. var error = event.srcElement['error'];
  69363. if (error && error.name === "QuotaExceededError") {
  69364. _this.hasReachedQuota = true;
  69365. }
  69366. }
  69367. catch (ex) { }
  69368. callback(fileData);
  69369. };
  69370. transaction.oncomplete = function (event) {
  69371. callback(fileData);
  69372. };
  69373. var newFile;
  69374. if (targetStore === "scenes") {
  69375. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69376. }
  69377. else {
  69378. newFile = { textureUrl: url, data: fileData };
  69379. }
  69380. try {
  69381. // Put the scene into the database
  69382. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69383. addRequest.onsuccess = function (event) {
  69384. };
  69385. addRequest.onerror = function (event) {
  69386. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69387. };
  69388. }
  69389. catch (ex) {
  69390. callback(fileData);
  69391. }
  69392. }
  69393. else {
  69394. callback(fileData);
  69395. }
  69396. }
  69397. else {
  69398. callback();
  69399. }
  69400. }, false);
  69401. xhr.addEventListener("error", function (event) {
  69402. BABYLON.Tools.Error("error on XHR request.");
  69403. callback();
  69404. }, false);
  69405. xhr.send();
  69406. }
  69407. else {
  69408. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69409. callback();
  69410. }
  69411. };
  69412. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69413. Database.IsUASupportingBlobStorage = true;
  69414. /** Gets a boolean indicating if Database storate is enabled */
  69415. Database.IDBStorageEnabled = true;
  69416. Database._ParseURL = function (url) {
  69417. var a = document.createElement('a');
  69418. a.href = url;
  69419. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69420. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69421. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69422. return absLocation;
  69423. };
  69424. Database._ReturnFullUrlLocation = function (url) {
  69425. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69426. return (Database._ParseURL(window.location.href) + url);
  69427. }
  69428. else {
  69429. return url;
  69430. }
  69431. };
  69432. return Database;
  69433. }());
  69434. BABYLON.Database = Database;
  69435. })(BABYLON || (BABYLON = {}));
  69436. //# sourceMappingURL=babylon.database.js.map
  69437. var BABYLON;
  69438. (function (BABYLON) {
  69439. var FresnelParameters = /** @class */ (function () {
  69440. function FresnelParameters() {
  69441. this._isEnabled = true;
  69442. this.leftColor = BABYLON.Color3.White();
  69443. this.rightColor = BABYLON.Color3.Black();
  69444. this.bias = 0;
  69445. this.power = 1;
  69446. }
  69447. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69448. get: function () {
  69449. return this._isEnabled;
  69450. },
  69451. set: function (value) {
  69452. if (this._isEnabled === value) {
  69453. return;
  69454. }
  69455. this._isEnabled = value;
  69456. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69457. },
  69458. enumerable: true,
  69459. configurable: true
  69460. });
  69461. FresnelParameters.prototype.clone = function () {
  69462. var newFresnelParameters = new FresnelParameters();
  69463. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69464. return newFresnelParameters;
  69465. };
  69466. FresnelParameters.prototype.serialize = function () {
  69467. var serializationObject = {};
  69468. serializationObject.isEnabled = this.isEnabled;
  69469. serializationObject.leftColor = this.leftColor.asArray();
  69470. serializationObject.rightColor = this.rightColor.asArray();
  69471. serializationObject.bias = this.bias;
  69472. serializationObject.power = this.power;
  69473. return serializationObject;
  69474. };
  69475. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69476. var fresnelParameters = new FresnelParameters();
  69477. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69478. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69479. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69480. fresnelParameters.bias = parsedFresnelParameters.bias;
  69481. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69482. return fresnelParameters;
  69483. };
  69484. return FresnelParameters;
  69485. }());
  69486. BABYLON.FresnelParameters = FresnelParameters;
  69487. })(BABYLON || (BABYLON = {}));
  69488. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69489. var BABYLON;
  69490. (function (BABYLON) {
  69491. var MultiMaterial = /** @class */ (function (_super) {
  69492. __extends(MultiMaterial, _super);
  69493. function MultiMaterial(name, scene) {
  69494. var _this = _super.call(this, name, scene, true) || this;
  69495. scene.multiMaterials.push(_this);
  69496. _this.subMaterials = new Array();
  69497. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69498. return _this;
  69499. }
  69500. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69501. get: function () {
  69502. return this._subMaterials;
  69503. },
  69504. set: function (value) {
  69505. this._subMaterials = value;
  69506. this._hookArray(value);
  69507. },
  69508. enumerable: true,
  69509. configurable: true
  69510. });
  69511. MultiMaterial.prototype._hookArray = function (array) {
  69512. var _this = this;
  69513. var oldPush = array.push;
  69514. array.push = function () {
  69515. var items = [];
  69516. for (var _i = 0; _i < arguments.length; _i++) {
  69517. items[_i] = arguments[_i];
  69518. }
  69519. var result = oldPush.apply(array, items);
  69520. _this._markAllSubMeshesAsTexturesDirty();
  69521. return result;
  69522. };
  69523. var oldSplice = array.splice;
  69524. array.splice = function (index, deleteCount) {
  69525. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69526. _this._markAllSubMeshesAsTexturesDirty();
  69527. return deleted;
  69528. };
  69529. };
  69530. // Properties
  69531. MultiMaterial.prototype.getSubMaterial = function (index) {
  69532. if (index < 0 || index >= this.subMaterials.length) {
  69533. return this.getScene().defaultMaterial;
  69534. }
  69535. return this.subMaterials[index];
  69536. };
  69537. MultiMaterial.prototype.getActiveTextures = function () {
  69538. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69539. if (subMaterial) {
  69540. return subMaterial.getActiveTextures();
  69541. }
  69542. else {
  69543. return [];
  69544. }
  69545. }));
  69546. var _a;
  69547. };
  69548. // Methods
  69549. MultiMaterial.prototype.getClassName = function () {
  69550. return "MultiMaterial";
  69551. };
  69552. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69553. for (var index = 0; index < this.subMaterials.length; index++) {
  69554. var subMaterial = this.subMaterials[index];
  69555. if (subMaterial) {
  69556. if (subMaterial.storeEffectOnSubMeshes) {
  69557. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69558. return false;
  69559. }
  69560. continue;
  69561. }
  69562. if (!subMaterial.isReady(mesh)) {
  69563. return false;
  69564. }
  69565. }
  69566. }
  69567. return true;
  69568. };
  69569. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69570. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69571. for (var index = 0; index < this.subMaterials.length; index++) {
  69572. var subMaterial = null;
  69573. var current = this.subMaterials[index];
  69574. if (cloneChildren && current) {
  69575. subMaterial = current.clone(name + "-" + current.name);
  69576. }
  69577. else {
  69578. subMaterial = this.subMaterials[index];
  69579. }
  69580. newMultiMaterial.subMaterials.push(subMaterial);
  69581. }
  69582. return newMultiMaterial;
  69583. };
  69584. MultiMaterial.prototype.serialize = function () {
  69585. var serializationObject = {};
  69586. serializationObject.name = this.name;
  69587. serializationObject.id = this.id;
  69588. if (BABYLON.Tags) {
  69589. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69590. }
  69591. serializationObject.materials = [];
  69592. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69593. var subMat = this.subMaterials[matIndex];
  69594. if (subMat) {
  69595. serializationObject.materials.push(subMat.id);
  69596. }
  69597. else {
  69598. serializationObject.materials.push(null);
  69599. }
  69600. }
  69601. return serializationObject;
  69602. };
  69603. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69604. var scene = this.getScene();
  69605. if (!scene) {
  69606. return;
  69607. }
  69608. var index = scene.multiMaterials.indexOf(this);
  69609. if (index >= 0) {
  69610. scene.multiMaterials.splice(index, 1);
  69611. }
  69612. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69613. };
  69614. return MultiMaterial;
  69615. }(BABYLON.Material));
  69616. BABYLON.MultiMaterial = MultiMaterial;
  69617. })(BABYLON || (BABYLON = {}));
  69618. //# sourceMappingURL=babylon.multiMaterial.js.map
  69619. var BABYLON;
  69620. (function (BABYLON) {
  69621. var FreeCameraTouchInput = /** @class */ (function () {
  69622. function FreeCameraTouchInput() {
  69623. this._offsetX = null;
  69624. this._offsetY = null;
  69625. this._pointerPressed = new Array();
  69626. this.touchAngularSensibility = 200000.0;
  69627. this.touchMoveSensibility = 250.0;
  69628. }
  69629. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69630. var _this = this;
  69631. var previousPosition = null;
  69632. if (this._pointerInput === undefined) {
  69633. this._onLostFocus = function (evt) {
  69634. _this._offsetX = null;
  69635. _this._offsetY = null;
  69636. };
  69637. this._pointerInput = function (p, s) {
  69638. var evt = p.event;
  69639. if (evt.pointerType === "mouse") {
  69640. return;
  69641. }
  69642. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69643. if (!noPreventDefault) {
  69644. evt.preventDefault();
  69645. }
  69646. _this._pointerPressed.push(evt.pointerId);
  69647. if (_this._pointerPressed.length !== 1) {
  69648. return;
  69649. }
  69650. previousPosition = {
  69651. x: evt.clientX,
  69652. y: evt.clientY
  69653. };
  69654. }
  69655. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69656. if (!noPreventDefault) {
  69657. evt.preventDefault();
  69658. }
  69659. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69660. if (index === -1) {
  69661. return;
  69662. }
  69663. _this._pointerPressed.splice(index, 1);
  69664. if (index != 0) {
  69665. return;
  69666. }
  69667. previousPosition = null;
  69668. _this._offsetX = null;
  69669. _this._offsetY = null;
  69670. }
  69671. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69672. if (!noPreventDefault) {
  69673. evt.preventDefault();
  69674. }
  69675. if (!previousPosition) {
  69676. return;
  69677. }
  69678. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69679. if (index != 0) {
  69680. return;
  69681. }
  69682. _this._offsetX = evt.clientX - previousPosition.x;
  69683. _this._offsetY = -(evt.clientY - previousPosition.y);
  69684. }
  69685. };
  69686. }
  69687. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69688. if (this._onLostFocus) {
  69689. element.addEventListener("blur", this._onLostFocus);
  69690. }
  69691. };
  69692. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69693. if (this._pointerInput && element) {
  69694. if (this._observer) {
  69695. this.camera.getScene().onPointerObservable.remove(this._observer);
  69696. this._observer = null;
  69697. }
  69698. if (this._onLostFocus) {
  69699. element.removeEventListener("blur", this._onLostFocus);
  69700. this._onLostFocus = null;
  69701. }
  69702. this._pointerPressed = [];
  69703. this._offsetX = null;
  69704. this._offsetY = null;
  69705. }
  69706. };
  69707. FreeCameraTouchInput.prototype.checkInputs = function () {
  69708. if (this._offsetX && this._offsetY) {
  69709. var camera = this.camera;
  69710. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69711. if (this._pointerPressed.length > 1) {
  69712. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69713. }
  69714. else {
  69715. var speed = camera._computeLocalCameraSpeed();
  69716. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69717. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69718. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69719. }
  69720. }
  69721. };
  69722. FreeCameraTouchInput.prototype.getClassName = function () {
  69723. return "FreeCameraTouchInput";
  69724. };
  69725. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69726. return "touch";
  69727. };
  69728. __decorate([
  69729. BABYLON.serialize()
  69730. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69731. __decorate([
  69732. BABYLON.serialize()
  69733. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69734. return FreeCameraTouchInput;
  69735. }());
  69736. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69737. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69738. })(BABYLON || (BABYLON = {}));
  69739. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69740. var BABYLON;
  69741. (function (BABYLON) {
  69742. // We're mainly based on the logic defined into the FreeCamera code
  69743. var TouchCamera = /** @class */ (function (_super) {
  69744. __extends(TouchCamera, _super);
  69745. //-- end properties for backward compatibility for inputs
  69746. function TouchCamera(name, position, scene) {
  69747. var _this = _super.call(this, name, position, scene) || this;
  69748. _this.inputs.addTouch();
  69749. _this._setupInputs();
  69750. return _this;
  69751. }
  69752. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69753. //-- Begin properties for backward compatibility for inputs
  69754. get: function () {
  69755. var touch = this.inputs.attached["touch"];
  69756. if (touch)
  69757. return touch.touchAngularSensibility;
  69758. return 0;
  69759. },
  69760. set: function (value) {
  69761. var touch = this.inputs.attached["touch"];
  69762. if (touch)
  69763. touch.touchAngularSensibility = value;
  69764. },
  69765. enumerable: true,
  69766. configurable: true
  69767. });
  69768. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69769. get: function () {
  69770. var touch = this.inputs.attached["touch"];
  69771. if (touch)
  69772. return touch.touchMoveSensibility;
  69773. return 0;
  69774. },
  69775. set: function (value) {
  69776. var touch = this.inputs.attached["touch"];
  69777. if (touch)
  69778. touch.touchMoveSensibility = value;
  69779. },
  69780. enumerable: true,
  69781. configurable: true
  69782. });
  69783. TouchCamera.prototype.getClassName = function () {
  69784. return "TouchCamera";
  69785. };
  69786. TouchCamera.prototype._setupInputs = function () {
  69787. var mouse = this.inputs.attached["mouse"];
  69788. if (mouse) {
  69789. mouse.touchEnabled = false;
  69790. }
  69791. };
  69792. return TouchCamera;
  69793. }(BABYLON.FreeCamera));
  69794. BABYLON.TouchCamera = TouchCamera;
  69795. })(BABYLON || (BABYLON = {}));
  69796. //# sourceMappingURL=babylon.touchCamera.js.map
  69797. var BABYLON;
  69798. (function (BABYLON) {
  69799. var ProceduralTexture = /** @class */ (function (_super) {
  69800. __extends(ProceduralTexture, _super);
  69801. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69802. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69803. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69804. if (isCube === void 0) { isCube = false; }
  69805. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69806. _this.isCube = isCube;
  69807. _this.isEnabled = true;
  69808. _this._currentRefreshId = -1;
  69809. _this._refreshRate = 1;
  69810. _this._vertexBuffers = {};
  69811. _this._uniforms = new Array();
  69812. _this._samplers = new Array();
  69813. _this._textures = {};
  69814. _this._floats = {};
  69815. _this._floatsArrays = {};
  69816. _this._colors3 = {};
  69817. _this._colors4 = {};
  69818. _this._vectors2 = {};
  69819. _this._vectors3 = {};
  69820. _this._matrices = {};
  69821. _this._fallbackTextureUsed = false;
  69822. scene.proceduralTextures.push(_this);
  69823. _this._engine = scene.getEngine();
  69824. _this.name = name;
  69825. _this.isRenderTarget = true;
  69826. _this._size = size;
  69827. _this._generateMipMaps = generateMipMaps;
  69828. _this.setFragment(fragment);
  69829. _this._fallbackTexture = fallbackTexture;
  69830. if (isCube) {
  69831. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69832. _this.setFloat("face", 0);
  69833. }
  69834. else {
  69835. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69836. }
  69837. // VBO
  69838. var vertices = [];
  69839. vertices.push(1, 1);
  69840. vertices.push(-1, 1);
  69841. vertices.push(-1, -1);
  69842. vertices.push(1, -1);
  69843. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69844. _this._createIndexBuffer();
  69845. return _this;
  69846. }
  69847. ProceduralTexture.prototype._createIndexBuffer = function () {
  69848. var engine = this._engine;
  69849. // Indices
  69850. var indices = [];
  69851. indices.push(0);
  69852. indices.push(1);
  69853. indices.push(2);
  69854. indices.push(0);
  69855. indices.push(2);
  69856. indices.push(3);
  69857. this._indexBuffer = engine.createIndexBuffer(indices);
  69858. };
  69859. ProceduralTexture.prototype._rebuild = function () {
  69860. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69861. if (vb) {
  69862. vb._rebuild();
  69863. }
  69864. this._createIndexBuffer();
  69865. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69866. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69867. }
  69868. };
  69869. ProceduralTexture.prototype.reset = function () {
  69870. if (this._effect === undefined) {
  69871. return;
  69872. }
  69873. var engine = this._engine;
  69874. engine._releaseEffect(this._effect);
  69875. };
  69876. ProceduralTexture.prototype.isReady = function () {
  69877. var _this = this;
  69878. var engine = this._engine;
  69879. var shaders;
  69880. if (!this._fragment) {
  69881. return false;
  69882. }
  69883. if (this._fallbackTextureUsed) {
  69884. return true;
  69885. }
  69886. if (this._fragment.fragmentElement !== undefined) {
  69887. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69888. }
  69889. else {
  69890. shaders = { vertex: "procedural", fragment: this._fragment };
  69891. }
  69892. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69893. _this.releaseInternalTexture();
  69894. if (_this._fallbackTexture) {
  69895. _this._texture = _this._fallbackTexture._texture;
  69896. if (_this._texture) {
  69897. _this._texture.incrementReferences();
  69898. }
  69899. }
  69900. _this._fallbackTextureUsed = true;
  69901. });
  69902. return this._effect.isReady();
  69903. };
  69904. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69905. this._currentRefreshId = -1;
  69906. };
  69907. ProceduralTexture.prototype.setFragment = function (fragment) {
  69908. this._fragment = fragment;
  69909. };
  69910. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69911. get: function () {
  69912. return this._refreshRate;
  69913. },
  69914. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69915. set: function (value) {
  69916. this._refreshRate = value;
  69917. this.resetRefreshCounter();
  69918. },
  69919. enumerable: true,
  69920. configurable: true
  69921. });
  69922. ProceduralTexture.prototype._shouldRender = function () {
  69923. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69924. return false;
  69925. }
  69926. if (this._fallbackTextureUsed) {
  69927. return false;
  69928. }
  69929. if (this._currentRefreshId === -1) { // At least render once
  69930. this._currentRefreshId = 1;
  69931. return true;
  69932. }
  69933. if (this.refreshRate === this._currentRefreshId) {
  69934. this._currentRefreshId = 1;
  69935. return true;
  69936. }
  69937. this._currentRefreshId++;
  69938. return false;
  69939. };
  69940. ProceduralTexture.prototype.getRenderSize = function () {
  69941. return this._size;
  69942. };
  69943. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69944. if (this._fallbackTextureUsed) {
  69945. return;
  69946. }
  69947. this.releaseInternalTexture();
  69948. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69949. };
  69950. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69951. if (this._uniforms.indexOf(uniformName) === -1) {
  69952. this._uniforms.push(uniformName);
  69953. }
  69954. };
  69955. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69956. if (this._samplers.indexOf(name) === -1) {
  69957. this._samplers.push(name);
  69958. }
  69959. this._textures[name] = texture;
  69960. return this;
  69961. };
  69962. ProceduralTexture.prototype.setFloat = function (name, value) {
  69963. this._checkUniform(name);
  69964. this._floats[name] = value;
  69965. return this;
  69966. };
  69967. ProceduralTexture.prototype.setFloats = function (name, value) {
  69968. this._checkUniform(name);
  69969. this._floatsArrays[name] = value;
  69970. return this;
  69971. };
  69972. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69973. this._checkUniform(name);
  69974. this._colors3[name] = value;
  69975. return this;
  69976. };
  69977. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69978. this._checkUniform(name);
  69979. this._colors4[name] = value;
  69980. return this;
  69981. };
  69982. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69983. this._checkUniform(name);
  69984. this._vectors2[name] = value;
  69985. return this;
  69986. };
  69987. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69988. this._checkUniform(name);
  69989. this._vectors3[name] = value;
  69990. return this;
  69991. };
  69992. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69993. this._checkUniform(name);
  69994. this._matrices[name] = value;
  69995. return this;
  69996. };
  69997. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69998. var scene = this.getScene();
  69999. if (!scene) {
  70000. return;
  70001. }
  70002. var engine = this._engine;
  70003. // Render
  70004. engine.enableEffect(this._effect);
  70005. engine.setState(false);
  70006. // Texture
  70007. for (var name in this._textures) {
  70008. this._effect.setTexture(name, this._textures[name]);
  70009. }
  70010. // Float
  70011. for (name in this._floats) {
  70012. this._effect.setFloat(name, this._floats[name]);
  70013. }
  70014. // Floats
  70015. for (name in this._floatsArrays) {
  70016. this._effect.setArray(name, this._floatsArrays[name]);
  70017. }
  70018. // Color3
  70019. for (name in this._colors3) {
  70020. this._effect.setColor3(name, this._colors3[name]);
  70021. }
  70022. // Color4
  70023. for (name in this._colors4) {
  70024. var color = this._colors4[name];
  70025. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70026. }
  70027. // Vector2
  70028. for (name in this._vectors2) {
  70029. this._effect.setVector2(name, this._vectors2[name]);
  70030. }
  70031. // Vector3
  70032. for (name in this._vectors3) {
  70033. this._effect.setVector3(name, this._vectors3[name]);
  70034. }
  70035. // Matrix
  70036. for (name in this._matrices) {
  70037. this._effect.setMatrix(name, this._matrices[name]);
  70038. }
  70039. if (!this._texture) {
  70040. return;
  70041. }
  70042. if (this.isCube) {
  70043. for (var face = 0; face < 6; face++) {
  70044. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70045. // VBOs
  70046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70047. this._effect.setFloat("face", face);
  70048. // Clear
  70049. engine.clear(scene.clearColor, true, true, true);
  70050. // Draw order
  70051. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70052. // Mipmaps
  70053. if (face === 5) {
  70054. engine.generateMipMapsForCubemap(this._texture);
  70055. }
  70056. }
  70057. }
  70058. else {
  70059. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70060. // VBOs
  70061. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70062. // Clear
  70063. engine.clear(scene.clearColor, true, true, true);
  70064. // Draw order
  70065. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70066. }
  70067. // Unbind
  70068. engine.unBindFramebuffer(this._texture, this.isCube);
  70069. if (this.onGenerated) {
  70070. this.onGenerated();
  70071. }
  70072. };
  70073. ProceduralTexture.prototype.clone = function () {
  70074. var textureSize = this.getSize();
  70075. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70076. // Base texture
  70077. newTexture.hasAlpha = this.hasAlpha;
  70078. newTexture.level = this.level;
  70079. // RenderTarget Texture
  70080. newTexture.coordinatesMode = this.coordinatesMode;
  70081. return newTexture;
  70082. };
  70083. ProceduralTexture.prototype.dispose = function () {
  70084. var scene = this.getScene();
  70085. if (!scene) {
  70086. return;
  70087. }
  70088. var index = scene.proceduralTextures.indexOf(this);
  70089. if (index >= 0) {
  70090. scene.proceduralTextures.splice(index, 1);
  70091. }
  70092. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70093. if (vertexBuffer) {
  70094. vertexBuffer.dispose();
  70095. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70096. }
  70097. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70098. this._indexBuffer = null;
  70099. }
  70100. _super.prototype.dispose.call(this);
  70101. };
  70102. return ProceduralTexture;
  70103. }(BABYLON.Texture));
  70104. BABYLON.ProceduralTexture = ProceduralTexture;
  70105. })(BABYLON || (BABYLON = {}));
  70106. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70107. var BABYLON;
  70108. (function (BABYLON) {
  70109. var CustomProceduralTexture = /** @class */ (function (_super) {
  70110. __extends(CustomProceduralTexture, _super);
  70111. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70112. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70113. _this._animate = true;
  70114. _this._time = 0;
  70115. _this._texturePath = texturePath;
  70116. //Try to load json
  70117. _this.loadJson(texturePath);
  70118. _this.refreshRate = 1;
  70119. return _this;
  70120. }
  70121. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70122. var _this = this;
  70123. var noConfigFile = function () {
  70124. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70125. try {
  70126. _this.setFragment(_this._texturePath);
  70127. }
  70128. catch (ex) {
  70129. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70130. }
  70131. };
  70132. var configFileUrl = jsonUrl + "/config.json";
  70133. var xhr = new XMLHttpRequest();
  70134. xhr.open("GET", configFileUrl, true);
  70135. xhr.addEventListener("load", function () {
  70136. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70137. try {
  70138. _this._config = JSON.parse(xhr.response);
  70139. _this.updateShaderUniforms();
  70140. _this.updateTextures();
  70141. _this.setFragment(_this._texturePath + "/custom");
  70142. _this._animate = _this._config.animate;
  70143. _this.refreshRate = _this._config.refreshrate;
  70144. }
  70145. catch (ex) {
  70146. noConfigFile();
  70147. }
  70148. }
  70149. else {
  70150. noConfigFile();
  70151. }
  70152. }, false);
  70153. xhr.addEventListener("error", function () {
  70154. noConfigFile();
  70155. }, false);
  70156. try {
  70157. xhr.send();
  70158. }
  70159. catch (ex) {
  70160. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70161. }
  70162. };
  70163. CustomProceduralTexture.prototype.isReady = function () {
  70164. if (!_super.prototype.isReady.call(this)) {
  70165. return false;
  70166. }
  70167. for (var name in this._textures) {
  70168. var texture = this._textures[name];
  70169. if (!texture.isReady()) {
  70170. return false;
  70171. }
  70172. }
  70173. return true;
  70174. };
  70175. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70176. var scene = this.getScene();
  70177. if (this._animate && scene) {
  70178. this._time += scene.getAnimationRatio() * 0.03;
  70179. this.updateShaderUniforms();
  70180. }
  70181. _super.prototype.render.call(this, useCameraPostProcess);
  70182. };
  70183. CustomProceduralTexture.prototype.updateTextures = function () {
  70184. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70185. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70186. }
  70187. };
  70188. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70189. if (this._config) {
  70190. for (var j = 0; j < this._config.uniforms.length; j++) {
  70191. var uniform = this._config.uniforms[j];
  70192. switch (uniform.type) {
  70193. case "float":
  70194. this.setFloat(uniform.name, uniform.value);
  70195. break;
  70196. case "color3":
  70197. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70198. break;
  70199. case "color4":
  70200. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70201. break;
  70202. case "vector2":
  70203. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70204. break;
  70205. case "vector3":
  70206. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70207. break;
  70208. }
  70209. }
  70210. }
  70211. this.setFloat("time", this._time);
  70212. };
  70213. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70214. get: function () {
  70215. return this._animate;
  70216. },
  70217. set: function (value) {
  70218. this._animate = value;
  70219. },
  70220. enumerable: true,
  70221. configurable: true
  70222. });
  70223. return CustomProceduralTexture;
  70224. }(BABYLON.ProceduralTexture));
  70225. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70226. })(BABYLON || (BABYLON = {}));
  70227. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70228. var BABYLON;
  70229. (function (BABYLON) {
  70230. var FreeCameraGamepadInput = /** @class */ (function () {
  70231. function FreeCameraGamepadInput() {
  70232. this.gamepadAngularSensibility = 200;
  70233. this.gamepadMoveSensibility = 40;
  70234. // private members
  70235. this._cameraTransform = BABYLON.Matrix.Identity();
  70236. this._deltaTransform = BABYLON.Vector3.Zero();
  70237. this._vector3 = BABYLON.Vector3.Zero();
  70238. this._vector2 = BABYLON.Vector2.Zero();
  70239. }
  70240. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70241. var _this = this;
  70242. var manager = this.camera.getScene().gamepadManager;
  70243. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70244. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70245. // prioritize XBOX gamepads.
  70246. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70247. _this.gamepad = gamepad;
  70248. }
  70249. }
  70250. });
  70251. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70252. if (_this.gamepad === gamepad) {
  70253. _this.gamepad = null;
  70254. }
  70255. });
  70256. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70257. };
  70258. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70259. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70260. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70261. this.gamepad = null;
  70262. };
  70263. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70264. if (this.gamepad && this.gamepad.leftStick) {
  70265. var camera = this.camera;
  70266. var LSValues = this.gamepad.leftStick;
  70267. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70268. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70269. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70270. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70271. var RSValues = this.gamepad.rightStick;
  70272. if (RSValues) {
  70273. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70274. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70275. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70276. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70277. }
  70278. else {
  70279. RSValues = { x: 0, y: 0 };
  70280. }
  70281. if (!camera.rotationQuaternion) {
  70282. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70283. }
  70284. else {
  70285. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70286. }
  70287. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70288. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70289. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70290. camera.cameraDirection.addInPlace(this._deltaTransform);
  70291. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70292. camera.cameraRotation.addInPlace(this._vector2);
  70293. }
  70294. };
  70295. FreeCameraGamepadInput.prototype.getClassName = function () {
  70296. return "FreeCameraGamepadInput";
  70297. };
  70298. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70299. return "gamepad";
  70300. };
  70301. __decorate([
  70302. BABYLON.serialize()
  70303. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70304. __decorate([
  70305. BABYLON.serialize()
  70306. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70307. return FreeCameraGamepadInput;
  70308. }());
  70309. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70310. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70311. })(BABYLON || (BABYLON = {}));
  70312. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70313. var BABYLON;
  70314. (function (BABYLON) {
  70315. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70316. function ArcRotateCameraGamepadInput() {
  70317. this.gamepadRotationSensibility = 80;
  70318. this.gamepadMoveSensibility = 40;
  70319. }
  70320. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70321. var _this = this;
  70322. var manager = this.camera.getScene().gamepadManager;
  70323. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70324. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70325. // prioritize XBOX gamepads.
  70326. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70327. _this.gamepad = gamepad;
  70328. }
  70329. }
  70330. });
  70331. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70332. if (_this.gamepad === gamepad) {
  70333. _this.gamepad = null;
  70334. }
  70335. });
  70336. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70337. };
  70338. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70339. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70340. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70341. this.gamepad = null;
  70342. };
  70343. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70344. if (this.gamepad) {
  70345. var camera = this.camera;
  70346. var RSValues = this.gamepad.rightStick;
  70347. if (RSValues) {
  70348. if (RSValues.x != 0) {
  70349. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70350. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70351. camera.inertialAlphaOffset += normalizedRX;
  70352. }
  70353. }
  70354. if (RSValues.y != 0) {
  70355. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70356. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70357. camera.inertialBetaOffset += normalizedRY;
  70358. }
  70359. }
  70360. }
  70361. var LSValues = this.gamepad.leftStick;
  70362. if (LSValues && LSValues.y != 0) {
  70363. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70364. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70365. this.camera.inertialRadiusOffset -= normalizedLY;
  70366. }
  70367. }
  70368. }
  70369. };
  70370. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70371. return "ArcRotateCameraGamepadInput";
  70372. };
  70373. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70374. return "gamepad";
  70375. };
  70376. __decorate([
  70377. BABYLON.serialize()
  70378. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70379. __decorate([
  70380. BABYLON.serialize()
  70381. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70382. return ArcRotateCameraGamepadInput;
  70383. }());
  70384. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70385. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70386. })(BABYLON || (BABYLON = {}));
  70387. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70388. var BABYLON;
  70389. (function (BABYLON) {
  70390. var GamepadManager = /** @class */ (function () {
  70391. function GamepadManager(_scene) {
  70392. var _this = this;
  70393. this._scene = _scene;
  70394. this._babylonGamepads = [];
  70395. this._oneGamepadConnected = false;
  70396. this._isMonitoring = false;
  70397. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70398. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70399. this._gamepadEventSupported = false;
  70400. }
  70401. else {
  70402. this._gamepadEventSupported = 'GamepadEvent' in window;
  70403. this._gamepadSupport = (navigator.getGamepads ||
  70404. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70405. }
  70406. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70407. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70408. for (var i in _this._babylonGamepads) {
  70409. var gamepad = _this._babylonGamepads[i];
  70410. if (gamepad && gamepad._isConnected) {
  70411. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70412. }
  70413. }
  70414. });
  70415. this._onGamepadConnectedEvent = function (evt) {
  70416. var gamepad = evt.gamepad;
  70417. if (gamepad.index in _this._babylonGamepads) {
  70418. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70419. return;
  70420. }
  70421. }
  70422. var newGamepad;
  70423. if (_this._babylonGamepads[gamepad.index]) {
  70424. newGamepad = _this._babylonGamepads[gamepad.index];
  70425. newGamepad.browserGamepad = gamepad;
  70426. newGamepad._isConnected = true;
  70427. }
  70428. else {
  70429. newGamepad = _this._addNewGamepad(gamepad);
  70430. }
  70431. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70432. _this._startMonitoringGamepads();
  70433. };
  70434. this._onGamepadDisconnectedEvent = function (evt) {
  70435. var gamepad = evt.gamepad;
  70436. // Remove the gamepad from the list of gamepads to monitor.
  70437. for (var i in _this._babylonGamepads) {
  70438. if (_this._babylonGamepads[i].index === gamepad.index) {
  70439. var disconnectedGamepad = _this._babylonGamepads[i];
  70440. disconnectedGamepad._isConnected = false;
  70441. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70442. break;
  70443. }
  70444. }
  70445. };
  70446. if (this._gamepadSupport) {
  70447. //first add already-connected gamepads
  70448. this._updateGamepadObjects();
  70449. if (this._babylonGamepads.length) {
  70450. this._startMonitoringGamepads();
  70451. }
  70452. // Checking if the gamepad connected event is supported (like in Firefox)
  70453. if (this._gamepadEventSupported) {
  70454. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70455. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70456. }
  70457. else {
  70458. this._startMonitoringGamepads();
  70459. }
  70460. }
  70461. }
  70462. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70463. get: function () {
  70464. return this._babylonGamepads;
  70465. },
  70466. enumerable: true,
  70467. configurable: true
  70468. });
  70469. GamepadManager.prototype.getGamepadByType = function (type) {
  70470. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70471. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70472. var gamepad = _a[_i];
  70473. if (gamepad && gamepad.type === type) {
  70474. return gamepad;
  70475. }
  70476. }
  70477. return null;
  70478. };
  70479. GamepadManager.prototype.dispose = function () {
  70480. if (this._gamepadEventSupported) {
  70481. if (this._onGamepadConnectedEvent) {
  70482. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70483. }
  70484. if (this._onGamepadDisconnectedEvent) {
  70485. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70486. }
  70487. this._onGamepadConnectedEvent = null;
  70488. this._onGamepadDisconnectedEvent = null;
  70489. }
  70490. this._babylonGamepads.forEach(function (gamepad) {
  70491. gamepad.dispose();
  70492. });
  70493. this.onGamepadConnectedObservable.clear();
  70494. this.onGamepadDisconnectedObservable.clear();
  70495. this._oneGamepadConnected = false;
  70496. this._stopMonitoringGamepads();
  70497. this._babylonGamepads = [];
  70498. };
  70499. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70500. if (!this._oneGamepadConnected) {
  70501. this._oneGamepadConnected = true;
  70502. }
  70503. var newGamepad;
  70504. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70505. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70506. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70507. }
  70508. // if pose is supported, use the (WebVR) pose enabled controller
  70509. else if (gamepad.pose) {
  70510. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70511. }
  70512. else {
  70513. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70514. }
  70515. this._babylonGamepads[newGamepad.index] = newGamepad;
  70516. return newGamepad;
  70517. };
  70518. GamepadManager.prototype._startMonitoringGamepads = function () {
  70519. if (!this._isMonitoring) {
  70520. this._isMonitoring = true;
  70521. //back-comp
  70522. if (!this._scene) {
  70523. this._checkGamepadsStatus();
  70524. }
  70525. }
  70526. };
  70527. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70528. this._isMonitoring = false;
  70529. };
  70530. GamepadManager.prototype._checkGamepadsStatus = function () {
  70531. var _this = this;
  70532. // Hack to be compatible Chrome
  70533. this._updateGamepadObjects();
  70534. for (var i in this._babylonGamepads) {
  70535. var gamepad = this._babylonGamepads[i];
  70536. if (!gamepad || !gamepad.isConnected) {
  70537. continue;
  70538. }
  70539. gamepad.update();
  70540. }
  70541. if (this._isMonitoring && !this._scene) {
  70542. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70543. }
  70544. };
  70545. // This function is called only on Chrome, which does not properly support
  70546. // connection/disconnection events and forces you to recopy again the gamepad object
  70547. GamepadManager.prototype._updateGamepadObjects = function () {
  70548. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70549. for (var i = 0; i < gamepads.length; i++) {
  70550. var gamepad = gamepads[i];
  70551. if (gamepad) {
  70552. if (!this._babylonGamepads[gamepad.index]) {
  70553. var newGamepad = this._addNewGamepad(gamepad);
  70554. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70555. }
  70556. else {
  70557. // Forced to copy again this object for Chrome for unknown reason
  70558. this._babylonGamepads[i].browserGamepad = gamepad;
  70559. if (!this._babylonGamepads[i].isConnected) {
  70560. this._babylonGamepads[i]._isConnected = true;
  70561. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70562. }
  70563. }
  70564. }
  70565. }
  70566. };
  70567. return GamepadManager;
  70568. }());
  70569. BABYLON.GamepadManager = GamepadManager;
  70570. })(BABYLON || (BABYLON = {}));
  70571. //# sourceMappingURL=babylon.gamepadManager.js.map
  70572. var BABYLON;
  70573. (function (BABYLON) {
  70574. var StickValues = /** @class */ (function () {
  70575. function StickValues(x, y) {
  70576. this.x = x;
  70577. this.y = y;
  70578. }
  70579. return StickValues;
  70580. }());
  70581. BABYLON.StickValues = StickValues;
  70582. var Gamepad = /** @class */ (function () {
  70583. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70584. if (leftStickX === void 0) { leftStickX = 0; }
  70585. if (leftStickY === void 0) { leftStickY = 1; }
  70586. if (rightStickX === void 0) { rightStickX = 2; }
  70587. if (rightStickY === void 0) { rightStickY = 3; }
  70588. this.id = id;
  70589. this.index = index;
  70590. this.browserGamepad = browserGamepad;
  70591. this._isConnected = true;
  70592. this._invertLeftStickY = false;
  70593. this.type = Gamepad.GAMEPAD;
  70594. this._leftStickAxisX = leftStickX;
  70595. this._leftStickAxisY = leftStickY;
  70596. this._rightStickAxisX = rightStickX;
  70597. this._rightStickAxisY = rightStickY;
  70598. if (this.browserGamepad.axes.length >= 2) {
  70599. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70600. }
  70601. if (this.browserGamepad.axes.length >= 4) {
  70602. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70603. }
  70604. }
  70605. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70606. get: function () {
  70607. return this._isConnected;
  70608. },
  70609. enumerable: true,
  70610. configurable: true
  70611. });
  70612. Gamepad.prototype.onleftstickchanged = function (callback) {
  70613. this._onleftstickchanged = callback;
  70614. };
  70615. Gamepad.prototype.onrightstickchanged = function (callback) {
  70616. this._onrightstickchanged = callback;
  70617. };
  70618. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70619. get: function () {
  70620. return this._leftStick;
  70621. },
  70622. set: function (newValues) {
  70623. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70624. this._onleftstickchanged(newValues);
  70625. }
  70626. this._leftStick = newValues;
  70627. },
  70628. enumerable: true,
  70629. configurable: true
  70630. });
  70631. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70632. get: function () {
  70633. return this._rightStick;
  70634. },
  70635. set: function (newValues) {
  70636. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70637. this._onrightstickchanged(newValues);
  70638. }
  70639. this._rightStick = newValues;
  70640. },
  70641. enumerable: true,
  70642. configurable: true
  70643. });
  70644. Gamepad.prototype.update = function () {
  70645. if (this._leftStick) {
  70646. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70647. if (this._invertLeftStickY) {
  70648. this.leftStick.y *= -1;
  70649. }
  70650. }
  70651. if (this._rightStick) {
  70652. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70653. }
  70654. };
  70655. Gamepad.prototype.dispose = function () {
  70656. };
  70657. Gamepad.GAMEPAD = 0;
  70658. Gamepad.GENERIC = 1;
  70659. Gamepad.XBOX = 2;
  70660. Gamepad.POSE_ENABLED = 3;
  70661. return Gamepad;
  70662. }());
  70663. BABYLON.Gamepad = Gamepad;
  70664. var GenericPad = /** @class */ (function (_super) {
  70665. __extends(GenericPad, _super);
  70666. function GenericPad(id, index, browserGamepad) {
  70667. var _this = _super.call(this, id, index, browserGamepad) || this;
  70668. _this.onButtonDownObservable = new BABYLON.Observable();
  70669. _this.onButtonUpObservable = new BABYLON.Observable();
  70670. _this.type = Gamepad.GENERIC;
  70671. _this._buttons = new Array(browserGamepad.buttons.length);
  70672. return _this;
  70673. }
  70674. GenericPad.prototype.onbuttondown = function (callback) {
  70675. this._onbuttondown = callback;
  70676. };
  70677. GenericPad.prototype.onbuttonup = function (callback) {
  70678. this._onbuttonup = callback;
  70679. };
  70680. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70681. if (newValue !== currentValue) {
  70682. if (newValue === 1) {
  70683. if (this._onbuttondown) {
  70684. this._onbuttondown(buttonIndex);
  70685. }
  70686. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70687. }
  70688. if (newValue === 0) {
  70689. if (this._onbuttonup) {
  70690. this._onbuttonup(buttonIndex);
  70691. }
  70692. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70693. }
  70694. }
  70695. return newValue;
  70696. };
  70697. GenericPad.prototype.update = function () {
  70698. _super.prototype.update.call(this);
  70699. for (var index = 0; index < this._buttons.length; index++) {
  70700. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70701. }
  70702. };
  70703. GenericPad.prototype.dispose = function () {
  70704. _super.prototype.dispose.call(this);
  70705. this.onButtonDownObservable.clear();
  70706. this.onButtonUpObservable.clear();
  70707. };
  70708. return GenericPad;
  70709. }(Gamepad));
  70710. BABYLON.GenericPad = GenericPad;
  70711. })(BABYLON || (BABYLON = {}));
  70712. //# sourceMappingURL=babylon.gamepad.js.map
  70713. var BABYLON;
  70714. (function (BABYLON) {
  70715. /**
  70716. * Defines supported buttons for XBox360 compatible gamepads
  70717. */
  70718. var Xbox360Button;
  70719. (function (Xbox360Button) {
  70720. /** A */
  70721. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70722. /** B */
  70723. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70724. /** X */
  70725. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70726. /** Y */
  70727. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70728. /** Start */
  70729. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70730. /** Back */
  70731. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70732. /** Left button */
  70733. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70734. /** Right button */
  70735. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70736. /** Left stick */
  70737. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70738. /** Right stick */
  70739. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70740. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70741. /** Defines values for XBox360 DPad */
  70742. var Xbox360Dpad;
  70743. (function (Xbox360Dpad) {
  70744. /** Up */
  70745. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70746. /** Down */
  70747. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70748. /** Left */
  70749. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70750. /** Right */
  70751. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70752. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70753. /**
  70754. * Defines a XBox360 gamepad
  70755. */
  70756. var Xbox360Pad = /** @class */ (function (_super) {
  70757. __extends(Xbox360Pad, _super);
  70758. /**
  70759. * Creates a new XBox360 gamepad object
  70760. * @param id defines the id of this gamepad
  70761. * @param index defines its index
  70762. * @param gamepad defines the internal HTML gamepad object
  70763. * @param xboxOne defines if it is a XBox One gamepad
  70764. */
  70765. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70766. if (xboxOne === void 0) { xboxOne = false; }
  70767. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70768. _this._leftTrigger = 0;
  70769. _this._rightTrigger = 0;
  70770. /** Observable raised when a button is pressed */
  70771. _this.onButtonDownObservable = new BABYLON.Observable();
  70772. /** Observable raised when a button is released */
  70773. _this.onButtonUpObservable = new BABYLON.Observable();
  70774. /** Observable raised when a pad is pressed */
  70775. _this.onPadDownObservable = new BABYLON.Observable();
  70776. /** Observable raised when a pad is released */
  70777. _this.onPadUpObservable = new BABYLON.Observable();
  70778. _this._buttonA = 0;
  70779. _this._buttonB = 0;
  70780. _this._buttonX = 0;
  70781. _this._buttonY = 0;
  70782. _this._buttonBack = 0;
  70783. _this._buttonStart = 0;
  70784. _this._buttonLB = 0;
  70785. _this._buttonRB = 0;
  70786. _this._buttonLeftStick = 0;
  70787. _this._buttonRightStick = 0;
  70788. _this._dPadUp = 0;
  70789. _this._dPadDown = 0;
  70790. _this._dPadLeft = 0;
  70791. _this._dPadRight = 0;
  70792. _this._isXboxOnePad = false;
  70793. _this.type = BABYLON.Gamepad.XBOX;
  70794. _this._isXboxOnePad = xboxOne;
  70795. return _this;
  70796. }
  70797. /**
  70798. * Defines the callback to call when left trigger is pressed
  70799. * @param callback defines the callback to use
  70800. */
  70801. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70802. this._onlefttriggerchanged = callback;
  70803. };
  70804. /**
  70805. * Defines the callback to call when right trigger is pressed
  70806. * @param callback defines the callback to use
  70807. */
  70808. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70809. this._onrighttriggerchanged = callback;
  70810. };
  70811. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70812. /**
  70813. * Gets or sets left trigger value
  70814. */
  70815. get: function () {
  70816. return this._leftTrigger;
  70817. },
  70818. set: function (newValue) {
  70819. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70820. this._onlefttriggerchanged(newValue);
  70821. }
  70822. this._leftTrigger = newValue;
  70823. },
  70824. enumerable: true,
  70825. configurable: true
  70826. });
  70827. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70828. /**
  70829. * Gets or sets right trigger value
  70830. */
  70831. get: function () {
  70832. return this._rightTrigger;
  70833. },
  70834. set: function (newValue) {
  70835. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70836. this._onrighttriggerchanged(newValue);
  70837. }
  70838. this._rightTrigger = newValue;
  70839. },
  70840. enumerable: true,
  70841. configurable: true
  70842. });
  70843. /**
  70844. * Defines the callback to call when a button is pressed
  70845. * @param callback defines the callback to use
  70846. */
  70847. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70848. this._onbuttondown = callback;
  70849. };
  70850. /**
  70851. * Defines the callback to call when a button is released
  70852. * @param callback defines the callback to use
  70853. */
  70854. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70855. this._onbuttonup = callback;
  70856. };
  70857. /**
  70858. * Defines the callback to call when a pad is pressed
  70859. * @param callback defines the callback to use
  70860. */
  70861. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70862. this._ondpaddown = callback;
  70863. };
  70864. /**
  70865. * Defines the callback to call when a pad is released
  70866. * @param callback defines the callback to use
  70867. */
  70868. Xbox360Pad.prototype.ondpadup = function (callback) {
  70869. this._ondpadup = callback;
  70870. };
  70871. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70872. if (newValue !== currentValue) {
  70873. if (newValue === 1) {
  70874. if (this._onbuttondown) {
  70875. this._onbuttondown(buttonType);
  70876. }
  70877. this.onButtonDownObservable.notifyObservers(buttonType);
  70878. }
  70879. if (newValue === 0) {
  70880. if (this._onbuttonup) {
  70881. this._onbuttonup(buttonType);
  70882. }
  70883. this.onButtonUpObservable.notifyObservers(buttonType);
  70884. }
  70885. }
  70886. return newValue;
  70887. };
  70888. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70889. if (newValue !== currentValue) {
  70890. if (newValue === 1) {
  70891. if (this._ondpaddown) {
  70892. this._ondpaddown(buttonType);
  70893. }
  70894. this.onPadDownObservable.notifyObservers(buttonType);
  70895. }
  70896. if (newValue === 0) {
  70897. if (this._ondpadup) {
  70898. this._ondpadup(buttonType);
  70899. }
  70900. this.onPadUpObservable.notifyObservers(buttonType);
  70901. }
  70902. }
  70903. return newValue;
  70904. };
  70905. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70906. /** Gets or sets value of A button */
  70907. get: function () {
  70908. return this._buttonA;
  70909. },
  70910. set: function (value) {
  70911. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70912. },
  70913. enumerable: true,
  70914. configurable: true
  70915. });
  70916. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70917. /** Gets or sets value of B button */
  70918. get: function () {
  70919. return this._buttonB;
  70920. },
  70921. set: function (value) {
  70922. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70923. },
  70924. enumerable: true,
  70925. configurable: true
  70926. });
  70927. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70928. /** Gets or sets value of X button */
  70929. get: function () {
  70930. return this._buttonX;
  70931. },
  70932. set: function (value) {
  70933. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70934. },
  70935. enumerable: true,
  70936. configurable: true
  70937. });
  70938. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70939. /** Gets or sets value of Y button */
  70940. get: function () {
  70941. return this._buttonY;
  70942. },
  70943. set: function (value) {
  70944. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70945. },
  70946. enumerable: true,
  70947. configurable: true
  70948. });
  70949. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70950. /** Gets or sets value of Start button */
  70951. get: function () {
  70952. return this._buttonStart;
  70953. },
  70954. set: function (value) {
  70955. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70956. },
  70957. enumerable: true,
  70958. configurable: true
  70959. });
  70960. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70961. /** Gets or sets value of Back button */
  70962. get: function () {
  70963. return this._buttonBack;
  70964. },
  70965. set: function (value) {
  70966. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70967. },
  70968. enumerable: true,
  70969. configurable: true
  70970. });
  70971. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70972. /** Gets or sets value of Left button */
  70973. get: function () {
  70974. return this._buttonLB;
  70975. },
  70976. set: function (value) {
  70977. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70978. },
  70979. enumerable: true,
  70980. configurable: true
  70981. });
  70982. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70983. /** Gets or sets value of Right button */
  70984. get: function () {
  70985. return this._buttonRB;
  70986. },
  70987. set: function (value) {
  70988. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70989. },
  70990. enumerable: true,
  70991. configurable: true
  70992. });
  70993. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70994. /** Gets or sets value of left stick */
  70995. get: function () {
  70996. return this._buttonLeftStick;
  70997. },
  70998. set: function (value) {
  70999. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71000. },
  71001. enumerable: true,
  71002. configurable: true
  71003. });
  71004. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71005. /** Gets or sets value of right stick */
  71006. get: function () {
  71007. return this._buttonRightStick;
  71008. },
  71009. set: function (value) {
  71010. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71011. },
  71012. enumerable: true,
  71013. configurable: true
  71014. });
  71015. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71016. /** Gets or sets value of DPad up */
  71017. get: function () {
  71018. return this._dPadUp;
  71019. },
  71020. set: function (value) {
  71021. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71022. },
  71023. enumerable: true,
  71024. configurable: true
  71025. });
  71026. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71027. /** Gets or sets value of DPad down */
  71028. get: function () {
  71029. return this._dPadDown;
  71030. },
  71031. set: function (value) {
  71032. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71033. },
  71034. enumerable: true,
  71035. configurable: true
  71036. });
  71037. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71038. /** Gets or sets value of DPad left */
  71039. get: function () {
  71040. return this._dPadLeft;
  71041. },
  71042. set: function (value) {
  71043. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71044. },
  71045. enumerable: true,
  71046. configurable: true
  71047. });
  71048. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71049. /** Gets or sets value of DPad right */
  71050. get: function () {
  71051. return this._dPadRight;
  71052. },
  71053. set: function (value) {
  71054. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71055. },
  71056. enumerable: true,
  71057. configurable: true
  71058. });
  71059. /**
  71060. * Force the gamepad to synchronize with device values
  71061. */
  71062. Xbox360Pad.prototype.update = function () {
  71063. _super.prototype.update.call(this);
  71064. if (this._isXboxOnePad) {
  71065. this.buttonA = this.browserGamepad.buttons[0].value;
  71066. this.buttonB = this.browserGamepad.buttons[1].value;
  71067. this.buttonX = this.browserGamepad.buttons[2].value;
  71068. this.buttonY = this.browserGamepad.buttons[3].value;
  71069. this.buttonLB = this.browserGamepad.buttons[4].value;
  71070. this.buttonRB = this.browserGamepad.buttons[5].value;
  71071. this.leftTrigger = this.browserGamepad.axes[2];
  71072. this.rightTrigger = this.browserGamepad.axes[5];
  71073. this.buttonBack = this.browserGamepad.buttons[9].value;
  71074. this.buttonStart = this.browserGamepad.buttons[8].value;
  71075. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71076. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71077. this.dPadUp = this.browserGamepad.buttons[11].value;
  71078. this.dPadDown = this.browserGamepad.buttons[12].value;
  71079. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71080. this.dPadRight = this.browserGamepad.buttons[14].value;
  71081. }
  71082. else {
  71083. this.buttonA = this.browserGamepad.buttons[0].value;
  71084. this.buttonB = this.browserGamepad.buttons[1].value;
  71085. this.buttonX = this.browserGamepad.buttons[2].value;
  71086. this.buttonY = this.browserGamepad.buttons[3].value;
  71087. this.buttonLB = this.browserGamepad.buttons[4].value;
  71088. this.buttonRB = this.browserGamepad.buttons[5].value;
  71089. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71090. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71091. this.buttonBack = this.browserGamepad.buttons[8].value;
  71092. this.buttonStart = this.browserGamepad.buttons[9].value;
  71093. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71094. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71095. this.dPadUp = this.browserGamepad.buttons[12].value;
  71096. this.dPadDown = this.browserGamepad.buttons[13].value;
  71097. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71098. this.dPadRight = this.browserGamepad.buttons[15].value;
  71099. }
  71100. };
  71101. Xbox360Pad.prototype.dispose = function () {
  71102. _super.prototype.dispose.call(this);
  71103. this.onButtonDownObservable.clear();
  71104. this.onButtonUpObservable.clear();
  71105. this.onPadDownObservable.clear();
  71106. this.onPadUpObservable.clear();
  71107. };
  71108. return Xbox360Pad;
  71109. }(BABYLON.Gamepad));
  71110. BABYLON.Xbox360Pad = Xbox360Pad;
  71111. })(BABYLON || (BABYLON = {}));
  71112. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71113. var BABYLON;
  71114. (function (BABYLON) {
  71115. /**
  71116. * Defines the types of pose enabled controllers that are supported
  71117. */
  71118. var PoseEnabledControllerType;
  71119. (function (PoseEnabledControllerType) {
  71120. /**
  71121. * HTC Vive
  71122. */
  71123. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71124. /**
  71125. * Oculus Rift
  71126. */
  71127. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71128. /**
  71129. * Windows mixed reality
  71130. */
  71131. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71132. /**
  71133. * Samsung gear VR
  71134. */
  71135. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71136. /**
  71137. * Google Daydream
  71138. */
  71139. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71140. /**
  71141. * Generic
  71142. */
  71143. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71144. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71145. /**
  71146. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71147. */
  71148. var PoseEnabledControllerHelper = /** @class */ (function () {
  71149. function PoseEnabledControllerHelper() {
  71150. }
  71151. /**
  71152. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71153. * @param vrGamepad the gamepad to initialized
  71154. * @returns a vr controller of the type the gamepad identified as
  71155. */
  71156. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71157. // Oculus Touch
  71158. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71159. return new BABYLON.OculusTouchController(vrGamepad);
  71160. }
  71161. // Windows Mixed Reality controllers
  71162. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71163. return new BABYLON.WindowsMotionController(vrGamepad);
  71164. }
  71165. // HTC Vive
  71166. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71167. return new BABYLON.ViveController(vrGamepad);
  71168. }
  71169. // Samsung/Oculus Gear VR
  71170. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  71171. return new BABYLON.GearVRController(vrGamepad);
  71172. }
  71173. // Google Daydream
  71174. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71175. return new BABYLON.DaydreamController(vrGamepad);
  71176. }
  71177. // Generic
  71178. else {
  71179. return new BABYLON.GenericController(vrGamepad);
  71180. }
  71181. };
  71182. return PoseEnabledControllerHelper;
  71183. }());
  71184. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71185. /**
  71186. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71187. */
  71188. var PoseEnabledController = /** @class */ (function (_super) {
  71189. __extends(PoseEnabledController, _super);
  71190. /**
  71191. * Creates a new PoseEnabledController from a gamepad
  71192. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71193. */
  71194. function PoseEnabledController(browserGamepad) {
  71195. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71196. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71197. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71198. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71199. /**
  71200. * The device position in babylon space
  71201. */
  71202. _this.devicePosition = BABYLON.Vector3.Zero();
  71203. /**
  71204. * The device rotation in babylon space
  71205. */
  71206. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71207. /**
  71208. * The scale factor of the device in babylon space
  71209. */
  71210. _this.deviceScaleFactor = 1;
  71211. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71212. /**
  71213. * Internal, matrix used to convert room space to babylon space
  71214. */
  71215. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71216. /**
  71217. * Node to be used when casting a ray from the controller
  71218. */
  71219. _this._pointingPoseNode = null;
  71220. _this._workingMatrix = BABYLON.Matrix.Identity();
  71221. /**
  71222. * @hidden
  71223. */
  71224. _this._meshAttachedObservable = new BABYLON.Observable();
  71225. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71226. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71227. _this.position = BABYLON.Vector3.Zero();
  71228. _this.rotationQuaternion = new BABYLON.Quaternion();
  71229. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71230. _this._calculatedRotation = new BABYLON.Quaternion();
  71231. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71232. return _this;
  71233. }
  71234. /**
  71235. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71236. */
  71237. PoseEnabledController.prototype.update = function () {
  71238. _super.prototype.update.call(this);
  71239. var pose = this.browserGamepad.pose;
  71240. this.updateFromDevice(pose);
  71241. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71242. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71243. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71244. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71245. if (this._mesh) {
  71246. this._mesh.position.copyFrom(this.devicePosition);
  71247. if (this._mesh.rotationQuaternion) {
  71248. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71249. }
  71250. }
  71251. };
  71252. /**
  71253. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71254. * @param poseData raw pose fromthe device
  71255. */
  71256. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71257. if (poseData) {
  71258. this.rawPose = poseData;
  71259. if (poseData.position) {
  71260. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71261. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71262. this._deviceRoomPosition.z *= -1;
  71263. }
  71264. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71265. this._calculatedPosition.addInPlace(this.position);
  71266. }
  71267. var pose = this.rawPose;
  71268. if (poseData.orientation && pose.orientation) {
  71269. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71270. if (this._mesh) {
  71271. if (this._mesh.getScene().useRightHandedSystem) {
  71272. this._deviceRoomRotationQuaternion.z *= -1;
  71273. this._deviceRoomRotationQuaternion.w *= -1;
  71274. }
  71275. else {
  71276. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71277. }
  71278. }
  71279. // if the camera is set, rotate to the camera's rotation
  71280. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71281. }
  71282. }
  71283. };
  71284. /**
  71285. * Attaches a mesh to the controller
  71286. * @param mesh the mesh to be attached
  71287. */
  71288. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71289. if (this._mesh) {
  71290. this._mesh.parent = null;
  71291. }
  71292. this._mesh = mesh;
  71293. if (this._poseControlledCamera) {
  71294. this._mesh.parent = this._poseControlledCamera;
  71295. }
  71296. if (!this._mesh.rotationQuaternion) {
  71297. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71298. }
  71299. this._meshAttachedObservable.notifyObservers(mesh);
  71300. };
  71301. /**
  71302. * Attaches the controllers mesh to a camera
  71303. * @param camera the camera the mesh should be attached to
  71304. */
  71305. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71306. this._poseControlledCamera = camera;
  71307. if (this._mesh) {
  71308. this._mesh.parent = this._poseControlledCamera;
  71309. }
  71310. };
  71311. /**
  71312. * Disposes of the controller
  71313. */
  71314. PoseEnabledController.prototype.dispose = function () {
  71315. if (this._mesh) {
  71316. this._mesh.dispose();
  71317. }
  71318. this._mesh = null;
  71319. _super.prototype.dispose.call(this);
  71320. };
  71321. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71322. /**
  71323. * The mesh that is attached to the controller
  71324. */
  71325. get: function () {
  71326. return this._mesh;
  71327. },
  71328. enumerable: true,
  71329. configurable: true
  71330. });
  71331. /**
  71332. * Gets the ray of the controller in the direction the controller is pointing
  71333. * @param length the length the resulting ray should be
  71334. * @returns a ray in the direction the controller is pointing
  71335. */
  71336. PoseEnabledController.prototype.getForwardRay = function (length) {
  71337. if (length === void 0) { length = 100; }
  71338. if (!this.mesh) {
  71339. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71340. }
  71341. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71342. var origin = m.getTranslation();
  71343. var forward = new BABYLON.Vector3(0, 0, -1);
  71344. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71345. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71346. return new BABYLON.Ray(origin, direction, length);
  71347. };
  71348. /**
  71349. * Name of the child mesh that can be used to cast a ray from the controller
  71350. */
  71351. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71352. return PoseEnabledController;
  71353. }(BABYLON.Gamepad));
  71354. BABYLON.PoseEnabledController = PoseEnabledController;
  71355. })(BABYLON || (BABYLON = {}));
  71356. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71357. var BABYLON;
  71358. (function (BABYLON) {
  71359. /**
  71360. * Defines the WebVRController object that represents controllers tracked in 3D space
  71361. */
  71362. var WebVRController = /** @class */ (function (_super) {
  71363. __extends(WebVRController, _super);
  71364. /**
  71365. * Creates a new WebVRController from a gamepad
  71366. * @param vrGamepad the gamepad that the WebVRController should be created from
  71367. */
  71368. function WebVRController(vrGamepad) {
  71369. var _this = _super.call(this, vrGamepad) || this;
  71370. // Observables
  71371. /**
  71372. * Fired when the trigger state has changed
  71373. */
  71374. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71375. /**
  71376. * Fired when the main button state has changed
  71377. */
  71378. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71379. /**
  71380. * Fired when the secondary button state has changed
  71381. */
  71382. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71383. /**
  71384. * Fired when the pad state has changed
  71385. */
  71386. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71387. /**
  71388. * Fired when controllers stick values have changed
  71389. */
  71390. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71391. /**
  71392. * X and Y axis corrisponding to the controllers joystick
  71393. */
  71394. _this.pad = { x: 0, y: 0 };
  71395. // avoid GC, store state in a tmp object
  71396. _this._changes = {
  71397. pressChanged: false,
  71398. touchChanged: false,
  71399. valueChanged: false,
  71400. changed: false
  71401. };
  71402. _this._buttons = new Array(vrGamepad.buttons.length);
  71403. _this.hand = vrGamepad.hand;
  71404. return _this;
  71405. }
  71406. /**
  71407. * Fired when a controller button's state has changed
  71408. * @param callback the callback containing the button that was modified
  71409. */
  71410. WebVRController.prototype.onButtonStateChange = function (callback) {
  71411. this._onButtonStateChange = callback;
  71412. };
  71413. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71414. /**
  71415. * The default controller model for the controller
  71416. */
  71417. get: function () {
  71418. return this._defaultModel;
  71419. },
  71420. enumerable: true,
  71421. configurable: true
  71422. });
  71423. /**
  71424. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71425. */
  71426. WebVRController.prototype.update = function () {
  71427. _super.prototype.update.call(this);
  71428. for (var index = 0; index < this._buttons.length; index++) {
  71429. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71430. }
  71431. ;
  71432. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71433. this.pad.x = this.leftStick.x;
  71434. this.pad.y = this.leftStick.y;
  71435. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71436. }
  71437. };
  71438. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71439. if (!newState) {
  71440. newState = {
  71441. pressed: false,
  71442. touched: false,
  71443. value: 0
  71444. };
  71445. }
  71446. if (!currentState) {
  71447. this._buttons[buttonIndex] = {
  71448. pressed: newState.pressed,
  71449. touched: newState.touched,
  71450. value: newState.value
  71451. };
  71452. return;
  71453. }
  71454. this._checkChanges(newState, currentState);
  71455. if (this._changes.changed) {
  71456. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71457. this._handleButtonChange(buttonIndex, newState, this._changes);
  71458. }
  71459. this._buttons[buttonIndex].pressed = newState.pressed;
  71460. this._buttons[buttonIndex].touched = newState.touched;
  71461. // oculus triggers are never 0, thou not touched.
  71462. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71463. };
  71464. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71465. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71466. this._changes.touchChanged = newState.touched !== currentState.touched;
  71467. this._changes.valueChanged = newState.value !== currentState.value;
  71468. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71469. return this._changes;
  71470. };
  71471. /**
  71472. * Disposes of th webVRCOntroller
  71473. */
  71474. WebVRController.prototype.dispose = function () {
  71475. _super.prototype.dispose.call(this);
  71476. this.onTriggerStateChangedObservable.clear();
  71477. this.onMainButtonStateChangedObservable.clear();
  71478. this.onSecondaryButtonStateChangedObservable.clear();
  71479. this.onPadStateChangedObservable.clear();
  71480. this.onPadValuesChangedObservable.clear();
  71481. };
  71482. return WebVRController;
  71483. }(BABYLON.PoseEnabledController));
  71484. BABYLON.WebVRController = WebVRController;
  71485. })(BABYLON || (BABYLON = {}));
  71486. //# sourceMappingURL=babylon.webVRController.js.map
  71487. var BABYLON;
  71488. (function (BABYLON) {
  71489. /**
  71490. * Oculus Touch Controller
  71491. */
  71492. var OculusTouchController = /** @class */ (function (_super) {
  71493. __extends(OculusTouchController, _super);
  71494. /**
  71495. * Creates a new OculusTouchController from a gamepad
  71496. * @param vrGamepad the gamepad that the controller should be created from
  71497. */
  71498. function OculusTouchController(vrGamepad) {
  71499. var _this = _super.call(this, vrGamepad) || this;
  71500. /**
  71501. * Fired when the secondary trigger on this controller is modified
  71502. */
  71503. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71504. /**
  71505. * Fired when the thumb rest on this controller is modified
  71506. */
  71507. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71508. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71509. return _this;
  71510. }
  71511. /**
  71512. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71513. * @param scene scene in which to add meshes
  71514. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71515. */
  71516. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71517. var _this = this;
  71518. var meshName;
  71519. // Hand
  71520. if (this.hand === 'left') {
  71521. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71522. }
  71523. else { // Right is the default if no hand is specified
  71524. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71525. }
  71526. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71527. /*
  71528. Parent Mesh name: oculus_touch_left
  71529. - body
  71530. - trigger
  71531. - thumbstick
  71532. - grip
  71533. - button_y
  71534. - button_x
  71535. - button_enter
  71536. */
  71537. _this._defaultModel = newMeshes[1];
  71538. _this.attachToMesh(_this._defaultModel);
  71539. if (meshLoaded) {
  71540. meshLoaded(_this._defaultModel);
  71541. }
  71542. });
  71543. };
  71544. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71545. /**
  71546. * Fired when the A button on this controller is modified
  71547. */
  71548. get: function () {
  71549. if (this.hand === 'right') {
  71550. return this.onMainButtonStateChangedObservable;
  71551. }
  71552. else {
  71553. throw new Error('No A button on left hand');
  71554. }
  71555. },
  71556. enumerable: true,
  71557. configurable: true
  71558. });
  71559. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71560. /**
  71561. * Fired when the B button on this controller is modified
  71562. */
  71563. get: function () {
  71564. if (this.hand === 'right') {
  71565. return this.onSecondaryButtonStateChangedObservable;
  71566. }
  71567. else {
  71568. throw new Error('No B button on left hand');
  71569. }
  71570. },
  71571. enumerable: true,
  71572. configurable: true
  71573. });
  71574. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71575. /**
  71576. * Fired when the X button on this controller is modified
  71577. */
  71578. get: function () {
  71579. if (this.hand === 'left') {
  71580. return this.onMainButtonStateChangedObservable;
  71581. }
  71582. else {
  71583. throw new Error('No X button on right hand');
  71584. }
  71585. },
  71586. enumerable: true,
  71587. configurable: true
  71588. });
  71589. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71590. /**
  71591. * Fired when the Y button on this controller is modified
  71592. */
  71593. get: function () {
  71594. if (this.hand === 'left') {
  71595. return this.onSecondaryButtonStateChangedObservable;
  71596. }
  71597. else {
  71598. throw new Error('No Y button on right hand');
  71599. }
  71600. },
  71601. enumerable: true,
  71602. configurable: true
  71603. });
  71604. /**
  71605. * Called once for each button that changed state since the last frame
  71606. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71607. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71608. * 2) secondary trigger (same)
  71609. * 3) A (right) X (left), touch, pressed = value
  71610. * 4) B / Y
  71611. * 5) thumb rest
  71612. * @param buttonIdx Which button index changed
  71613. * @param state New state of the button
  71614. * @param changes Which properties on the state changed since last frame
  71615. */
  71616. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71617. var notifyObject = state; //{ state: state, changes: changes };
  71618. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71619. switch (buttonIdx) {
  71620. case 0:
  71621. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71622. return;
  71623. case 1: // index trigger
  71624. if (this._defaultModel) {
  71625. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71626. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71627. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71628. }
  71629. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71630. return;
  71631. case 2: // secondary trigger
  71632. if (this._defaultModel) {
  71633. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71634. }
  71635. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71636. return;
  71637. case 3:
  71638. if (this._defaultModel) {
  71639. if (notifyObject.pressed) {
  71640. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71641. }
  71642. else {
  71643. (this._defaultModel.getChildren()[1]).position.y = 0;
  71644. }
  71645. }
  71646. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71647. return;
  71648. case 4:
  71649. if (this._defaultModel) {
  71650. if (notifyObject.pressed) {
  71651. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71652. }
  71653. else {
  71654. (this._defaultModel.getChildren()[2]).position.y = 0;
  71655. }
  71656. }
  71657. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71658. return;
  71659. case 5:
  71660. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71661. return;
  71662. }
  71663. };
  71664. /**
  71665. * Base Url for the controller model.
  71666. */
  71667. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71668. /**
  71669. * File name for the left controller model.
  71670. */
  71671. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71672. /**
  71673. * File name for the right controller model.
  71674. */
  71675. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71676. return OculusTouchController;
  71677. }(BABYLON.WebVRController));
  71678. BABYLON.OculusTouchController = OculusTouchController;
  71679. })(BABYLON || (BABYLON = {}));
  71680. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71681. var BABYLON;
  71682. (function (BABYLON) {
  71683. /**
  71684. * Vive Controller
  71685. */
  71686. var ViveController = /** @class */ (function (_super) {
  71687. __extends(ViveController, _super);
  71688. /**
  71689. * Creates a new ViveController from a gamepad
  71690. * @param vrGamepad the gamepad that the controller should be created from
  71691. */
  71692. function ViveController(vrGamepad) {
  71693. var _this = _super.call(this, vrGamepad) || this;
  71694. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71695. _this._invertLeftStickY = true;
  71696. return _this;
  71697. }
  71698. /**
  71699. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71700. * @param scene scene in which to add meshes
  71701. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71702. */
  71703. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71704. var _this = this;
  71705. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71706. /*
  71707. Parent Mesh name: ViveWand
  71708. - body
  71709. - r_gripper
  71710. - l_gripper
  71711. - menu_button
  71712. - system_button
  71713. - trackpad
  71714. - trigger
  71715. - LED
  71716. */
  71717. _this._defaultModel = newMeshes[1];
  71718. _this.attachToMesh(_this._defaultModel);
  71719. if (meshLoaded) {
  71720. meshLoaded(_this._defaultModel);
  71721. }
  71722. });
  71723. };
  71724. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71725. /**
  71726. * Fired when the left button on this controller is modified
  71727. */
  71728. get: function () {
  71729. return this.onMainButtonStateChangedObservable;
  71730. },
  71731. enumerable: true,
  71732. configurable: true
  71733. });
  71734. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71735. /**
  71736. * Fired when the right button on this controller is modified
  71737. */
  71738. get: function () {
  71739. return this.onMainButtonStateChangedObservable;
  71740. },
  71741. enumerable: true,
  71742. configurable: true
  71743. });
  71744. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71745. /**
  71746. * Fired when the menu button on this controller is modified
  71747. */
  71748. get: function () {
  71749. return this.onSecondaryButtonStateChangedObservable;
  71750. },
  71751. enumerable: true,
  71752. configurable: true
  71753. });
  71754. /**
  71755. * Called once for each button that changed state since the last frame
  71756. * Vive mapping:
  71757. * 0: touchpad
  71758. * 1: trigger
  71759. * 2: left AND right buttons
  71760. * 3: menu button
  71761. * @param buttonIdx Which button index changed
  71762. * @param state New state of the button
  71763. * @param changes Which properties on the state changed since last frame
  71764. */
  71765. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71766. var notifyObject = state; //{ state: state, changes: changes };
  71767. switch (buttonIdx) {
  71768. case 0:
  71769. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71770. return;
  71771. case 1: // index trigger
  71772. if (this._defaultModel) {
  71773. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71774. }
  71775. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71776. return;
  71777. case 2: // left AND right button
  71778. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71779. return;
  71780. case 3:
  71781. if (this._defaultModel) {
  71782. if (notifyObject.pressed) {
  71783. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71784. }
  71785. else {
  71786. (this._defaultModel.getChildren()[2]).position.y = 0;
  71787. }
  71788. }
  71789. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71790. return;
  71791. }
  71792. };
  71793. /**
  71794. * Base Url for the controller model.
  71795. */
  71796. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71797. /**
  71798. * File name for the controller model.
  71799. */
  71800. ViveController.MODEL_FILENAME = 'wand.babylon';
  71801. return ViveController;
  71802. }(BABYLON.WebVRController));
  71803. BABYLON.ViveController = ViveController;
  71804. })(BABYLON || (BABYLON = {}));
  71805. //# sourceMappingURL=babylon.viveController.js.map
  71806. var BABYLON;
  71807. (function (BABYLON) {
  71808. /**
  71809. * Generic Controller
  71810. */
  71811. var GenericController = /** @class */ (function (_super) {
  71812. __extends(GenericController, _super);
  71813. /**
  71814. * Creates a new GenericController from a gamepad
  71815. * @param vrGamepad the gamepad that the controller should be created from
  71816. */
  71817. function GenericController(vrGamepad) {
  71818. return _super.call(this, vrGamepad) || this;
  71819. }
  71820. /**
  71821. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71822. * @param scene scene in which to add meshes
  71823. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71824. */
  71825. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71826. var _this = this;
  71827. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71828. _this._defaultModel = newMeshes[1];
  71829. _this.attachToMesh(_this._defaultModel);
  71830. if (meshLoaded) {
  71831. meshLoaded(_this._defaultModel);
  71832. }
  71833. });
  71834. };
  71835. /**
  71836. * Called once for each button that changed state since the last frame
  71837. * @param buttonIdx Which button index changed
  71838. * @param state New state of the button
  71839. * @param changes Which properties on the state changed since last frame
  71840. */
  71841. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71842. console.log("Button id: " + buttonIdx + "state: ");
  71843. console.dir(state);
  71844. };
  71845. /**
  71846. * Base Url for the controller model.
  71847. */
  71848. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71849. /**
  71850. * File name for the controller model.
  71851. */
  71852. GenericController.MODEL_FILENAME = 'generic.babylon';
  71853. return GenericController;
  71854. }(BABYLON.WebVRController));
  71855. BABYLON.GenericController = GenericController;
  71856. })(BABYLON || (BABYLON = {}));
  71857. //# sourceMappingURL=babylon.genericController.js.map
  71858. var BABYLON;
  71859. (function (BABYLON) {
  71860. /**
  71861. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71862. */
  71863. var LoadedMeshInfo = /** @class */ (function () {
  71864. function LoadedMeshInfo() {
  71865. /**
  71866. * Map of the button meshes contained in the controller
  71867. */
  71868. this.buttonMeshes = {};
  71869. /**
  71870. * Map of the axis meshes contained in the controller
  71871. */
  71872. this.axisMeshes = {};
  71873. }
  71874. return LoadedMeshInfo;
  71875. }());
  71876. /**
  71877. * Defines the WindowsMotionController object that the state of the windows motion controller
  71878. */
  71879. var WindowsMotionController = /** @class */ (function (_super) {
  71880. __extends(WindowsMotionController, _super);
  71881. /**
  71882. * Creates a new WindowsMotionController from a gamepad
  71883. * @param vrGamepad the gamepad that the controller should be created from
  71884. */
  71885. function WindowsMotionController(vrGamepad) {
  71886. var _this = _super.call(this, vrGamepad) || this;
  71887. _this._mapping = {
  71888. // Semantic button names
  71889. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71890. // A mapping of the button name to glTF model node name
  71891. // that should be transformed by button value.
  71892. buttonMeshNames: {
  71893. 'trigger': 'SELECT',
  71894. 'menu': 'MENU',
  71895. 'grip': 'GRASP',
  71896. 'thumbstick': 'THUMBSTICK_PRESS',
  71897. 'trackpad': 'TOUCHPAD_PRESS'
  71898. },
  71899. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71900. buttonObservableNames: {
  71901. 'trigger': 'onTriggerStateChangedObservable',
  71902. 'menu': 'onSecondaryButtonStateChangedObservable',
  71903. 'grip': 'onMainButtonStateChangedObservable',
  71904. 'thumbstick': 'onPadStateChangedObservable',
  71905. 'trackpad': 'onTrackpadChangedObservable'
  71906. },
  71907. // A mapping of the axis name to glTF model node name
  71908. // that should be transformed by axis value.
  71909. // This array mirrors the browserGamepad.axes array, such that
  71910. // the mesh corresponding to axis 0 is in this array index 0.
  71911. axisMeshNames: [
  71912. 'THUMBSTICK_X',
  71913. 'THUMBSTICK_Y',
  71914. 'TOUCHPAD_TOUCH_X',
  71915. 'TOUCHPAD_TOUCH_Y'
  71916. ],
  71917. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71918. };
  71919. /**
  71920. * Fired when the trackpad on this controller is clicked
  71921. */
  71922. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71923. /**
  71924. * Fired when the trackpad on this controller is modified
  71925. */
  71926. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71927. /**
  71928. * The current x and y values of this controller's trackpad
  71929. */
  71930. _this.trackpad = { x: 0, y: 0 };
  71931. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71932. _this._loadedMeshInfo = null;
  71933. return _this;
  71934. }
  71935. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71936. /**
  71937. * Fired when the trigger on this controller is modified
  71938. */
  71939. get: function () {
  71940. return this.onTriggerStateChangedObservable;
  71941. },
  71942. enumerable: true,
  71943. configurable: true
  71944. });
  71945. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71946. /**
  71947. * Fired when the menu button on this controller is modified
  71948. */
  71949. get: function () {
  71950. return this.onSecondaryButtonStateChangedObservable;
  71951. },
  71952. enumerable: true,
  71953. configurable: true
  71954. });
  71955. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71956. /**
  71957. * Fired when the grip button on this controller is modified
  71958. */
  71959. get: function () {
  71960. return this.onMainButtonStateChangedObservable;
  71961. },
  71962. enumerable: true,
  71963. configurable: true
  71964. });
  71965. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71966. /**
  71967. * Fired when the thumbstick button on this controller is modified
  71968. */
  71969. get: function () {
  71970. return this.onPadStateChangedObservable;
  71971. },
  71972. enumerable: true,
  71973. configurable: true
  71974. });
  71975. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71976. /**
  71977. * Fired when the touchpad button on this controller is modified
  71978. */
  71979. get: function () {
  71980. return this.onTrackpadChangedObservable;
  71981. },
  71982. enumerable: true,
  71983. configurable: true
  71984. });
  71985. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71986. /**
  71987. * Fired when the touchpad values on this controller are modified
  71988. */
  71989. get: function () {
  71990. return this.onTrackpadValuesChangedObservable;
  71991. },
  71992. enumerable: true,
  71993. configurable: true
  71994. });
  71995. /**
  71996. * Called once per frame by the engine.
  71997. */
  71998. WindowsMotionController.prototype.update = function () {
  71999. _super.prototype.update.call(this);
  72000. if (this.browserGamepad.axes) {
  72001. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72002. this.trackpad.x = this.browserGamepad["axes"][2];
  72003. this.trackpad.y = this.browserGamepad["axes"][3];
  72004. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72005. }
  72006. // Only need to animate axes if there is a loaded mesh
  72007. if (this._loadedMeshInfo) {
  72008. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72009. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72010. }
  72011. }
  72012. }
  72013. };
  72014. /**
  72015. * Called once for each button that changed state since the last frame
  72016. * @param buttonIdx Which button index changed
  72017. * @param state New state of the button
  72018. * @param changes Which properties on the state changed since last frame
  72019. */
  72020. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72021. var buttonName = this._mapping.buttons[buttonIdx];
  72022. if (!buttonName) {
  72023. return;
  72024. }
  72025. // Only emit events for buttons that we know how to map from index to name
  72026. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72027. if (observable) {
  72028. observable.notifyObservers(state);
  72029. }
  72030. this._lerpButtonTransform(buttonName, state.value);
  72031. };
  72032. /**
  72033. * Moves the buttons on the controller mesh based on their current state
  72034. * @param buttonName the name of the button to move
  72035. * @param buttonValue the value of the button which determines the buttons new position
  72036. */
  72037. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72038. // If there is no loaded mesh, there is nothing to transform.
  72039. if (!this._loadedMeshInfo) {
  72040. return;
  72041. }
  72042. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72043. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72044. return;
  72045. }
  72046. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72047. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72048. };
  72049. /**
  72050. * Moves the axis on the controller mesh based on its current state
  72051. * @param axis the index of the axis
  72052. * @param axisValue the value of the axis which determines the meshes new position
  72053. * @hidden
  72054. */
  72055. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72056. if (!this._loadedMeshInfo) {
  72057. return;
  72058. }
  72059. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72060. if (!meshInfo) {
  72061. return;
  72062. }
  72063. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72064. return;
  72065. }
  72066. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72067. var lerpValue = axisValue * 0.5 + 0.5;
  72068. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72069. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72070. };
  72071. /**
  72072. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72073. * @param scene scene in which to add meshes
  72074. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72075. */
  72076. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72077. var _this = this;
  72078. if (forceDefault === void 0) { forceDefault = false; }
  72079. var path;
  72080. var filename;
  72081. // Checking if GLB loader is present
  72082. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72083. // Determine the device specific folder based on the ID suffix
  72084. var device = 'default';
  72085. if (this.id && !forceDefault) {
  72086. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72087. device = ((match && match[0]) || device);
  72088. }
  72089. // Hand
  72090. if (this.hand === 'left') {
  72091. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72092. }
  72093. else { // Right is the default if no hand is specified
  72094. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72095. }
  72096. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72097. }
  72098. else {
  72099. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72100. path = BABYLON.GenericController.MODEL_BASE_URL;
  72101. filename = BABYLON.GenericController.MODEL_FILENAME;
  72102. }
  72103. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72104. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72105. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72106. if (!_this._loadedMeshInfo) {
  72107. return;
  72108. }
  72109. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72110. _this.attachToMesh(_this._defaultModel);
  72111. if (meshLoaded) {
  72112. meshLoaded(_this._defaultModel);
  72113. }
  72114. }, null, function (scene, message) {
  72115. BABYLON.Tools.Log(message);
  72116. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72117. if (!forceDefault) {
  72118. _this.initControllerMesh(scene, meshLoaded, true);
  72119. }
  72120. });
  72121. };
  72122. /**
  72123. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72124. * can be transformed by button presses and axes values, based on this._mapping.
  72125. *
  72126. * @param scene scene in which the meshes exist
  72127. * @param meshes list of meshes that make up the controller model to process
  72128. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72129. */
  72130. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72131. var loadedMeshInfo = null;
  72132. // Create a new mesh to contain the glTF hierarchy
  72133. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72134. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72135. var childMesh = null;
  72136. for (var i = 0; i < meshes.length; i++) {
  72137. var mesh = meshes[i];
  72138. if (!mesh.parent) {
  72139. // Exclude controller meshes from picking results
  72140. mesh.isPickable = false;
  72141. // Handle root node, attach to the new parentMesh
  72142. childMesh = mesh;
  72143. break;
  72144. }
  72145. }
  72146. if (childMesh) {
  72147. childMesh.setParent(parentMesh);
  72148. // Create our mesh info. Note that this method will always return non-null.
  72149. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72150. }
  72151. else {
  72152. BABYLON.Tools.Warn('Could not find root node in model file.');
  72153. }
  72154. return loadedMeshInfo;
  72155. };
  72156. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72157. var loadedMeshInfo = new LoadedMeshInfo();
  72158. var i;
  72159. loadedMeshInfo.rootNode = rootNode;
  72160. // Reset the caches
  72161. loadedMeshInfo.buttonMeshes = {};
  72162. loadedMeshInfo.axisMeshes = {};
  72163. // Button Meshes
  72164. for (i = 0; i < this._mapping.buttons.length; i++) {
  72165. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72166. if (!buttonMeshName) {
  72167. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72168. continue;
  72169. }
  72170. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72171. if (!buttonMesh) {
  72172. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72173. continue;
  72174. }
  72175. var buttonMeshInfo = {
  72176. index: i,
  72177. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72178. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72179. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72180. };
  72181. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72182. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72183. }
  72184. else {
  72185. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72186. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72187. '(VALUE: ' + !!buttonMeshInfo.value +
  72188. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72189. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72190. ')');
  72191. }
  72192. }
  72193. // Axis Meshes
  72194. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72195. var axisMeshName = this._mapping.axisMeshNames[i];
  72196. if (!axisMeshName) {
  72197. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72198. continue;
  72199. }
  72200. var axisMesh = getChildByName(rootNode, axisMeshName);
  72201. if (!axisMesh) {
  72202. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72203. continue;
  72204. }
  72205. var axisMeshInfo = {
  72206. index: i,
  72207. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72208. min: getImmediateChildByName(axisMesh, 'MIN'),
  72209. max: getImmediateChildByName(axisMesh, 'MAX')
  72210. };
  72211. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72212. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72213. }
  72214. else {
  72215. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72216. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72217. '(VALUE: ' + !!axisMeshInfo.value +
  72218. ', MIN: ' + !!axisMeshInfo.min +
  72219. ', MAX:' + !!axisMeshInfo.max +
  72220. ')');
  72221. }
  72222. }
  72223. // Pointing Ray
  72224. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72225. if (!loadedMeshInfo.pointingPoseNode) {
  72226. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72227. }
  72228. return loadedMeshInfo;
  72229. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72230. function getChildByName(node, name) {
  72231. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72232. }
  72233. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72234. function getImmediateChildByName(node, name) {
  72235. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72236. }
  72237. };
  72238. /**
  72239. * Gets the ray of the controller in the direction the controller is pointing
  72240. * @param length the length the resulting ray should be
  72241. * @returns a ray in the direction the controller is pointing
  72242. */
  72243. WindowsMotionController.prototype.getForwardRay = function (length) {
  72244. if (length === void 0) { length = 100; }
  72245. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72246. return _super.prototype.getForwardRay.call(this, length);
  72247. }
  72248. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72249. var origin = m.getTranslation();
  72250. var forward = new BABYLON.Vector3(0, 0, -1);
  72251. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72252. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72253. return new BABYLON.Ray(origin, direction, length);
  72254. };
  72255. /**
  72256. * Disposes of the controller
  72257. */
  72258. WindowsMotionController.prototype.dispose = function () {
  72259. _super.prototype.dispose.call(this);
  72260. this.onTrackpadChangedObservable.clear();
  72261. };
  72262. /**
  72263. * The base url used to load the left and right controller models
  72264. */
  72265. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72266. /**
  72267. * The name of the left controller model file
  72268. */
  72269. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72270. /**
  72271. * The name of the right controller model file
  72272. */
  72273. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72274. /**
  72275. * The controller name prefix for this controller type
  72276. */
  72277. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72278. /**
  72279. * The controller id pattern for this controller type
  72280. */
  72281. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72282. return WindowsMotionController;
  72283. }(BABYLON.WebVRController));
  72284. BABYLON.WindowsMotionController = WindowsMotionController;
  72285. })(BABYLON || (BABYLON = {}));
  72286. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72287. var BABYLON;
  72288. (function (BABYLON) {
  72289. /**
  72290. * Gear VR Controller
  72291. */
  72292. var GearVRController = /** @class */ (function (_super) {
  72293. __extends(GearVRController, _super);
  72294. /**
  72295. * Creates a new GearVRController from a gamepad
  72296. * @param vrGamepad the gamepad that the controller should be created from
  72297. */
  72298. function GearVRController(vrGamepad) {
  72299. var _this = _super.call(this, vrGamepad) || this;
  72300. _this._buttonIndexToObservableNameMap = [
  72301. 'onTrackpadChangedObservable',
  72302. 'onTriggerStateChangedObservable' // Trigger
  72303. ];
  72304. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72305. return _this;
  72306. }
  72307. /**
  72308. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72309. * @param scene scene in which to add meshes
  72310. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72311. */
  72312. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72313. var _this = this;
  72314. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72315. _this._defaultModel = newMeshes[1];
  72316. _this.attachToMesh(_this._defaultModel);
  72317. if (meshLoaded) {
  72318. meshLoaded(_this._defaultModel);
  72319. }
  72320. });
  72321. };
  72322. /**
  72323. * Called once for each button that changed state since the last frame
  72324. * @param buttonIdx Which button index changed
  72325. * @param state New state of the button
  72326. * @param changes Which properties on the state changed since last frame
  72327. */
  72328. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72329. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72330. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72331. // Only emit events for buttons that we know how to map from index to observable
  72332. var observable = this[observableName];
  72333. if (observable) {
  72334. observable.notifyObservers(state);
  72335. }
  72336. }
  72337. };
  72338. /**
  72339. * Base Url for the controller model.
  72340. */
  72341. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72342. /**
  72343. * File name for the controller model.
  72344. */
  72345. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72346. /**
  72347. * Gamepad Id prefix used to identify this controller.
  72348. */
  72349. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72350. return GearVRController;
  72351. }(BABYLON.WebVRController));
  72352. BABYLON.GearVRController = GearVRController;
  72353. })(BABYLON || (BABYLON = {}));
  72354. //# sourceMappingURL=babylon.gearVRController.js.map
  72355. var BABYLON;
  72356. (function (BABYLON) {
  72357. /**
  72358. * Google Daydream controller
  72359. */
  72360. var DaydreamController = /** @class */ (function (_super) {
  72361. __extends(DaydreamController, _super);
  72362. /**
  72363. * Creates a new DaydreamController from a gamepad
  72364. * @param vrGamepad the gamepad that the controller should be created from
  72365. */
  72366. function DaydreamController(vrGamepad) {
  72367. var _this = _super.call(this, vrGamepad) || this;
  72368. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72369. return _this;
  72370. }
  72371. /**
  72372. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72373. * @param scene scene in which to add meshes
  72374. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72375. */
  72376. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72377. var _this = this;
  72378. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72379. _this._defaultModel = newMeshes[1];
  72380. _this.attachToMesh(_this._defaultModel);
  72381. if (meshLoaded) {
  72382. meshLoaded(_this._defaultModel);
  72383. }
  72384. });
  72385. };
  72386. /**
  72387. * Called once for each button that changed state since the last frame
  72388. * @param buttonIdx Which button index changed
  72389. * @param state New state of the button
  72390. * @param changes Which properties on the state changed since last frame
  72391. */
  72392. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72393. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72394. if (buttonIdx === 0) {
  72395. var observable = this.onTriggerStateChangedObservable;
  72396. if (observable) {
  72397. observable.notifyObservers(state);
  72398. }
  72399. }
  72400. else {
  72401. // If the app or home buttons are ever made available
  72402. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72403. }
  72404. };
  72405. /**
  72406. * Base Url for the controller model.
  72407. */
  72408. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72409. /**
  72410. * File name for the controller model.
  72411. */
  72412. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72413. /**
  72414. * Gamepad Id prefix used to identify Daydream Controller.
  72415. */
  72416. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72417. return DaydreamController;
  72418. }(BABYLON.WebVRController));
  72419. BABYLON.DaydreamController = DaydreamController;
  72420. })(BABYLON || (BABYLON = {}));
  72421. //# sourceMappingURL=babylon.daydreamController.js.map
  72422. var BABYLON;
  72423. (function (BABYLON) {
  72424. var FollowCamera = /** @class */ (function (_super) {
  72425. __extends(FollowCamera, _super);
  72426. function FollowCamera(name, position, scene, lockedTarget) {
  72427. if (lockedTarget === void 0) { lockedTarget = null; }
  72428. var _this = _super.call(this, name, position, scene) || this;
  72429. _this.radius = 12;
  72430. _this.rotationOffset = 0;
  72431. _this.heightOffset = 4;
  72432. _this.cameraAcceleration = 0.05;
  72433. _this.maxCameraSpeed = 20;
  72434. _this.lockedTarget = lockedTarget;
  72435. return _this;
  72436. }
  72437. FollowCamera.prototype.getRadians = function (degrees) {
  72438. return degrees * Math.PI / 180;
  72439. };
  72440. FollowCamera.prototype.follow = function (cameraTarget) {
  72441. if (!cameraTarget)
  72442. return;
  72443. var yRotation;
  72444. if (cameraTarget.rotationQuaternion) {
  72445. var rotMatrix = new BABYLON.Matrix();
  72446. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72447. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72448. }
  72449. else {
  72450. yRotation = cameraTarget.rotation.y;
  72451. }
  72452. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72453. var targetPosition = cameraTarget.getAbsolutePosition();
  72454. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72455. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72456. var dx = targetX - this.position.x;
  72457. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72458. var dz = (targetZ) - this.position.z;
  72459. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72460. var vy = dy * this.cameraAcceleration;
  72461. var vz = dz * this.cameraAcceleration * 2;
  72462. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72463. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72464. }
  72465. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72466. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72467. }
  72468. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72469. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72470. }
  72471. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72472. this.setTarget(targetPosition);
  72473. };
  72474. FollowCamera.prototype._checkInputs = function () {
  72475. _super.prototype._checkInputs.call(this);
  72476. if (this.lockedTarget) {
  72477. this.follow(this.lockedTarget);
  72478. }
  72479. };
  72480. FollowCamera.prototype.getClassName = function () {
  72481. return "FollowCamera";
  72482. };
  72483. __decorate([
  72484. BABYLON.serialize()
  72485. ], FollowCamera.prototype, "radius", void 0);
  72486. __decorate([
  72487. BABYLON.serialize()
  72488. ], FollowCamera.prototype, "rotationOffset", void 0);
  72489. __decorate([
  72490. BABYLON.serialize()
  72491. ], FollowCamera.prototype, "heightOffset", void 0);
  72492. __decorate([
  72493. BABYLON.serialize()
  72494. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72495. __decorate([
  72496. BABYLON.serialize()
  72497. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72498. __decorate([
  72499. BABYLON.serializeAsMeshReference("lockedTargetId")
  72500. ], FollowCamera.prototype, "lockedTarget", void 0);
  72501. return FollowCamera;
  72502. }(BABYLON.TargetCamera));
  72503. BABYLON.FollowCamera = FollowCamera;
  72504. var ArcFollowCamera = /** @class */ (function (_super) {
  72505. __extends(ArcFollowCamera, _super);
  72506. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72507. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72508. _this.alpha = alpha;
  72509. _this.beta = beta;
  72510. _this.radius = radius;
  72511. _this.target = target;
  72512. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72513. _this.follow();
  72514. return _this;
  72515. }
  72516. ArcFollowCamera.prototype.follow = function () {
  72517. if (!this.target) {
  72518. return;
  72519. }
  72520. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72521. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72522. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72523. var targetPosition = this.target.getAbsolutePosition();
  72524. this.position = targetPosition.add(this._cartesianCoordinates);
  72525. this.setTarget(targetPosition);
  72526. };
  72527. ArcFollowCamera.prototype._checkInputs = function () {
  72528. _super.prototype._checkInputs.call(this);
  72529. this.follow();
  72530. };
  72531. ArcFollowCamera.prototype.getClassName = function () {
  72532. return "ArcFollowCamera";
  72533. };
  72534. return ArcFollowCamera;
  72535. }(BABYLON.TargetCamera));
  72536. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72537. })(BABYLON || (BABYLON = {}));
  72538. //# sourceMappingURL=babylon.followCamera.js.map
  72539. var BABYLON;
  72540. (function (BABYLON) {
  72541. // We're mainly based on the logic defined into the FreeCamera code
  72542. var UniversalCamera = /** @class */ (function (_super) {
  72543. __extends(UniversalCamera, _super);
  72544. //-- end properties for backward compatibility for inputs
  72545. function UniversalCamera(name, position, scene) {
  72546. var _this = _super.call(this, name, position, scene) || this;
  72547. _this.inputs.addGamepad();
  72548. return _this;
  72549. }
  72550. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72551. //-- Begin properties for backward compatibility for inputs
  72552. get: function () {
  72553. var gamepad = this.inputs.attached["gamepad"];
  72554. if (gamepad)
  72555. return gamepad.gamepadAngularSensibility;
  72556. return 0;
  72557. },
  72558. set: function (value) {
  72559. var gamepad = this.inputs.attached["gamepad"];
  72560. if (gamepad)
  72561. gamepad.gamepadAngularSensibility = value;
  72562. },
  72563. enumerable: true,
  72564. configurable: true
  72565. });
  72566. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72567. get: function () {
  72568. var gamepad = this.inputs.attached["gamepad"];
  72569. if (gamepad)
  72570. return gamepad.gamepadMoveSensibility;
  72571. return 0;
  72572. },
  72573. set: function (value) {
  72574. var gamepad = this.inputs.attached["gamepad"];
  72575. if (gamepad)
  72576. gamepad.gamepadMoveSensibility = value;
  72577. },
  72578. enumerable: true,
  72579. configurable: true
  72580. });
  72581. UniversalCamera.prototype.getClassName = function () {
  72582. return "UniversalCamera";
  72583. };
  72584. return UniversalCamera;
  72585. }(BABYLON.TouchCamera));
  72586. BABYLON.UniversalCamera = UniversalCamera;
  72587. })(BABYLON || (BABYLON = {}));
  72588. //# sourceMappingURL=babylon.universalCamera.js.map
  72589. var BABYLON;
  72590. (function (BABYLON) {
  72591. // We're mainly based on the logic defined into the FreeCamera code
  72592. var GamepadCamera = /** @class */ (function (_super) {
  72593. __extends(GamepadCamera, _super);
  72594. //-- end properties for backward compatibility for inputs
  72595. function GamepadCamera(name, position, scene) {
  72596. return _super.call(this, name, position, scene) || this;
  72597. }
  72598. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72599. //-- Begin properties for backward compatibility for inputs
  72600. get: function () {
  72601. var gamepad = this.inputs.attached["gamepad"];
  72602. if (gamepad)
  72603. return gamepad.gamepadAngularSensibility;
  72604. return 0;
  72605. },
  72606. set: function (value) {
  72607. var gamepad = this.inputs.attached["gamepad"];
  72608. if (gamepad)
  72609. gamepad.gamepadAngularSensibility = value;
  72610. },
  72611. enumerable: true,
  72612. configurable: true
  72613. });
  72614. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72615. get: function () {
  72616. var gamepad = this.inputs.attached["gamepad"];
  72617. if (gamepad)
  72618. return gamepad.gamepadMoveSensibility;
  72619. return 0;
  72620. },
  72621. set: function (value) {
  72622. var gamepad = this.inputs.attached["gamepad"];
  72623. if (gamepad)
  72624. gamepad.gamepadMoveSensibility = value;
  72625. },
  72626. enumerable: true,
  72627. configurable: true
  72628. });
  72629. GamepadCamera.prototype.getClassName = function () {
  72630. return "GamepadCamera";
  72631. };
  72632. return GamepadCamera;
  72633. }(BABYLON.UniversalCamera));
  72634. BABYLON.GamepadCamera = GamepadCamera;
  72635. })(BABYLON || (BABYLON = {}));
  72636. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72637. var BABYLON;
  72638. (function (BABYLON) {
  72639. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72640. function PostProcessRenderPipelineManager() {
  72641. this._renderPipelines = {};
  72642. }
  72643. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72644. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72645. };
  72646. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72647. if (unique === void 0) { unique = false; }
  72648. var renderPipeline = this._renderPipelines[renderPipelineName];
  72649. if (!renderPipeline) {
  72650. return;
  72651. }
  72652. renderPipeline._attachCameras(cameras, unique);
  72653. };
  72654. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72655. var renderPipeline = this._renderPipelines[renderPipelineName];
  72656. if (!renderPipeline) {
  72657. return;
  72658. }
  72659. renderPipeline._detachCameras(cameras);
  72660. };
  72661. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72662. var renderPipeline = this._renderPipelines[renderPipelineName];
  72663. if (!renderPipeline) {
  72664. return;
  72665. }
  72666. renderPipeline._enableEffect(renderEffectName, cameras);
  72667. };
  72668. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72669. var renderPipeline = this._renderPipelines[renderPipelineName];
  72670. if (!renderPipeline) {
  72671. return;
  72672. }
  72673. renderPipeline._disableEffect(renderEffectName, cameras);
  72674. };
  72675. PostProcessRenderPipelineManager.prototype.update = function () {
  72676. for (var renderPipelineName in this._renderPipelines) {
  72677. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72678. var pipeline = this._renderPipelines[renderPipelineName];
  72679. if (!pipeline.isSupported) {
  72680. pipeline.dispose();
  72681. delete this._renderPipelines[renderPipelineName];
  72682. }
  72683. else {
  72684. pipeline._update();
  72685. }
  72686. }
  72687. }
  72688. };
  72689. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72690. for (var renderPipelineName in this._renderPipelines) {
  72691. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72692. var pipeline = this._renderPipelines[renderPipelineName];
  72693. pipeline._rebuild();
  72694. }
  72695. }
  72696. };
  72697. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72698. for (var renderPipelineName in this._renderPipelines) {
  72699. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72700. var pipeline = this._renderPipelines[renderPipelineName];
  72701. pipeline.dispose();
  72702. }
  72703. }
  72704. };
  72705. return PostProcessRenderPipelineManager;
  72706. }());
  72707. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72708. })(BABYLON || (BABYLON = {}));
  72709. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72710. var BABYLON;
  72711. (function (BABYLON) {
  72712. /**
  72713. * This represents a set of one or more post processes in Babylon.
  72714. * A post process can be used to apply a shader to a texture after it is rendered.
  72715. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72716. */
  72717. var PostProcessRenderEffect = /** @class */ (function () {
  72718. /**
  72719. * Instantiates a post process render effect.
  72720. * A post process can be used to apply a shader to a texture after it is rendered.
  72721. * @param engine The engine the effect is tied to
  72722. * @param name The name of the effect
  72723. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72724. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72725. */
  72726. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72727. this._name = name;
  72728. this._singleInstance = singleInstance || true;
  72729. this._getPostProcesses = getPostProcesses;
  72730. this._cameras = {};
  72731. this._indicesForCamera = {};
  72732. this._postProcesses = {};
  72733. }
  72734. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72735. /**
  72736. * Checks if all the post processes in the effect are supported.
  72737. */
  72738. get: function () {
  72739. for (var index in this._postProcesses) {
  72740. if (this._postProcesses.hasOwnProperty(index)) {
  72741. var pps = this._postProcesses[index];
  72742. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72743. if (!pps[ppIndex].isSupported) {
  72744. return false;
  72745. }
  72746. }
  72747. }
  72748. }
  72749. return true;
  72750. },
  72751. enumerable: true,
  72752. configurable: true
  72753. });
  72754. /**
  72755. * Updates the current state of the effect
  72756. */
  72757. PostProcessRenderEffect.prototype._update = function () {
  72758. };
  72759. /**
  72760. * Attaches the effect on cameras
  72761. * @param cameras The camera to attach to.
  72762. */
  72763. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72764. var _this = this;
  72765. var cameraKey;
  72766. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72767. if (!cams) {
  72768. return;
  72769. }
  72770. for (var i = 0; i < cams.length; i++) {
  72771. var camera = cams[i];
  72772. var cameraName = camera.name;
  72773. if (this._singleInstance) {
  72774. cameraKey = 0;
  72775. }
  72776. else {
  72777. cameraKey = cameraName;
  72778. }
  72779. if (!this._postProcesses[cameraKey]) {
  72780. var postProcess = this._getPostProcesses();
  72781. if (postProcess) {
  72782. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72783. }
  72784. }
  72785. if (!this._indicesForCamera[cameraName]) {
  72786. this._indicesForCamera[cameraName] = [];
  72787. }
  72788. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72789. var index = camera.attachPostProcess(postProcess);
  72790. _this._indicesForCamera[cameraName].push(index);
  72791. });
  72792. if (!this._cameras[cameraName]) {
  72793. this._cameras[cameraName] = camera;
  72794. }
  72795. }
  72796. };
  72797. /**
  72798. * Detatches the effect on cameras
  72799. * @param cameras The camera to detatch from.
  72800. */
  72801. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72802. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72803. if (!cams) {
  72804. return;
  72805. }
  72806. for (var i = 0; i < cams.length; i++) {
  72807. var camera = cams[i];
  72808. var cameraName = camera.name;
  72809. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72810. camera.detachPostProcess(postProcess);
  72811. });
  72812. if (this._cameras[cameraName]) {
  72813. //this._indicesForCamera.splice(index, 1);
  72814. this._cameras[cameraName] = null;
  72815. }
  72816. }
  72817. };
  72818. /**
  72819. * Enables the effect on given cameras
  72820. * @param cameras The camera to enable.
  72821. */
  72822. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72823. var _this = this;
  72824. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72825. if (!cams) {
  72826. return;
  72827. }
  72828. for (var i = 0; i < cams.length; i++) {
  72829. var camera = cams[i];
  72830. var cameraName = camera.name;
  72831. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72832. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72833. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72834. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72835. });
  72836. }
  72837. }
  72838. }
  72839. };
  72840. /**
  72841. * Disables the effect on the given cameras
  72842. * @param cameras The camera to disable.
  72843. */
  72844. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72845. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72846. if (!cams) {
  72847. return;
  72848. }
  72849. for (var i = 0; i < cams.length; i++) {
  72850. var camera = cams[i];
  72851. var cameraName = camera.name;
  72852. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72853. camera.detachPostProcess(postProcess);
  72854. });
  72855. }
  72856. };
  72857. /**
  72858. * Gets a list of the post processes contained in the effect.
  72859. * @param camera The camera to get the post processes on.
  72860. * @returns The list of the post processes in the effect.
  72861. */
  72862. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72863. if (this._singleInstance) {
  72864. return this._postProcesses[0];
  72865. }
  72866. else {
  72867. if (!camera) {
  72868. return null;
  72869. }
  72870. return this._postProcesses[camera.name];
  72871. }
  72872. };
  72873. return PostProcessRenderEffect;
  72874. }());
  72875. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72876. })(BABYLON || (BABYLON = {}));
  72877. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72878. var BABYLON;
  72879. (function (BABYLON) {
  72880. var PostProcessRenderPipeline = /** @class */ (function () {
  72881. function PostProcessRenderPipeline(engine, name) {
  72882. this.engine = engine;
  72883. this._name = name;
  72884. this._renderEffects = {};
  72885. this._renderEffectsForIsolatedPass = new Array();
  72886. this._cameras = [];
  72887. }
  72888. PostProcessRenderPipeline.prototype.getClassName = function () {
  72889. return "PostProcessRenderPipeline";
  72890. };
  72891. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72892. get: function () {
  72893. for (var renderEffectName in this._renderEffects) {
  72894. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72895. if (!this._renderEffects[renderEffectName].isSupported) {
  72896. return false;
  72897. }
  72898. }
  72899. }
  72900. return true;
  72901. },
  72902. enumerable: true,
  72903. configurable: true
  72904. });
  72905. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72906. this._renderEffects[renderEffect._name] = renderEffect;
  72907. };
  72908. // private
  72909. PostProcessRenderPipeline.prototype._rebuild = function () {
  72910. };
  72911. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72912. var renderEffects = this._renderEffects[renderEffectName];
  72913. if (!renderEffects) {
  72914. return;
  72915. }
  72916. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72917. };
  72918. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72919. var renderEffects = this._renderEffects[renderEffectName];
  72920. if (!renderEffects) {
  72921. return;
  72922. }
  72923. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72924. };
  72925. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72926. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72927. if (!cams) {
  72928. return;
  72929. }
  72930. var indicesToDelete = [];
  72931. var i;
  72932. for (i = 0; i < cams.length; i++) {
  72933. var camera = cams[i];
  72934. var cameraName = camera.name;
  72935. if (this._cameras.indexOf(camera) === -1) {
  72936. this._cameras[cameraName] = camera;
  72937. }
  72938. else if (unique) {
  72939. indicesToDelete.push(i);
  72940. }
  72941. }
  72942. for (i = 0; i < indicesToDelete.length; i++) {
  72943. cameras.splice(indicesToDelete[i], 1);
  72944. }
  72945. for (var renderEffectName in this._renderEffects) {
  72946. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72947. this._renderEffects[renderEffectName]._attachCameras(cams);
  72948. }
  72949. }
  72950. };
  72951. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72952. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72953. if (!cams) {
  72954. return;
  72955. }
  72956. for (var renderEffectName in this._renderEffects) {
  72957. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72958. this._renderEffects[renderEffectName]._detachCameras(cams);
  72959. }
  72960. }
  72961. for (var i = 0; i < cams.length; i++) {
  72962. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72963. }
  72964. };
  72965. PostProcessRenderPipeline.prototype._update = function () {
  72966. for (var renderEffectName in this._renderEffects) {
  72967. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72968. this._renderEffects[renderEffectName]._update();
  72969. }
  72970. }
  72971. for (var i = 0; i < this._cameras.length; i++) {
  72972. var cameraName = this._cameras[i].name;
  72973. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72974. this._renderEffectsForIsolatedPass[cameraName]._update();
  72975. }
  72976. }
  72977. };
  72978. PostProcessRenderPipeline.prototype._reset = function () {
  72979. this._renderEffects = {};
  72980. this._renderEffectsForIsolatedPass = new Array();
  72981. };
  72982. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72983. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  72984. var effectKeys = Object.keys(this._renderEffects);
  72985. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72986. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72987. if (postProcesses) {
  72988. postProcesses[0].samples = sampleCount;
  72989. return true;
  72990. }
  72991. }
  72992. return false;
  72993. };
  72994. PostProcessRenderPipeline.prototype.dispose = function () {
  72995. // Must be implemented by children
  72996. };
  72997. __decorate([
  72998. BABYLON.serialize()
  72999. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73000. return PostProcessRenderPipeline;
  73001. }());
  73002. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73003. })(BABYLON || (BABYLON = {}));
  73004. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73005. var BABYLON;
  73006. (function (BABYLON) {
  73007. /**
  73008. * This represents a depth renderer in Babylon.
  73009. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73010. */
  73011. var DepthRenderer = /** @class */ (function () {
  73012. /**
  73013. * Instantiates a depth renderer
  73014. * @param scene The scene the renderer belongs to
  73015. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73016. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73017. */
  73018. function DepthRenderer(scene, type, camera) {
  73019. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73020. if (camera === void 0) { camera = null; }
  73021. var _this = this;
  73022. this._scene = scene;
  73023. this._camera = camera;
  73024. var engine = scene.getEngine();
  73025. // Render target
  73026. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73027. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73028. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73029. this._depthMap.refreshRate = 1;
  73030. this._depthMap.renderParticles = false;
  73031. this._depthMap.renderList = null;
  73032. // Camera to get depth map from to support multiple concurrent cameras
  73033. this._depthMap.activeCamera = this._camera;
  73034. this._depthMap.ignoreCameraViewport = true;
  73035. this._depthMap.useCameraPostProcesses = false;
  73036. // set default depth value to 1.0 (far away)
  73037. this._depthMap.onClearObservable.add(function (engine) {
  73038. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73039. });
  73040. // Custom render function
  73041. var renderSubMesh = function (subMesh) {
  73042. var mesh = subMesh.getRenderingMesh();
  73043. var scene = _this._scene;
  73044. var engine = scene.getEngine();
  73045. var material = subMesh.getMaterial();
  73046. if (!material) {
  73047. return;
  73048. }
  73049. // Culling and reverse (right handed system)
  73050. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73051. // Managing instances
  73052. var batch = mesh._getInstancesRenderList(subMesh._id);
  73053. if (batch.mustReturn) {
  73054. return;
  73055. }
  73056. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73057. var camera = _this._camera || scene.activeCamera;
  73058. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73059. engine.enableEffect(_this._effect);
  73060. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73061. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73062. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73063. // Alpha test
  73064. if (material && material.needAlphaTesting()) {
  73065. var alphaTexture = material.getAlphaTestTexture();
  73066. if (alphaTexture) {
  73067. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73068. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73069. }
  73070. }
  73071. // Bones
  73072. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73073. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73074. }
  73075. // Draw
  73076. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73077. }
  73078. };
  73079. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73080. var index;
  73081. if (depthOnlySubMeshes.length) {
  73082. engine.setColorWrite(false);
  73083. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73084. renderSubMesh(depthOnlySubMeshes.data[index]);
  73085. }
  73086. engine.setColorWrite(true);
  73087. }
  73088. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73089. renderSubMesh(opaqueSubMeshes.data[index]);
  73090. }
  73091. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73092. renderSubMesh(alphaTestSubMeshes.data[index]);
  73093. }
  73094. };
  73095. }
  73096. /**
  73097. * Creates the depth rendering effect and checks if the effect is ready.
  73098. * @param subMesh The submesh to be used to render the depth map of
  73099. * @param useInstances If multiple world instances should be used
  73100. * @returns if the depth renderer is ready to render the depth map
  73101. */
  73102. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73103. var material = subMesh.getMaterial();
  73104. if (material.disableDepthWrite) {
  73105. return false;
  73106. }
  73107. var defines = [];
  73108. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73109. var mesh = subMesh.getMesh();
  73110. // Alpha test
  73111. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73112. defines.push("#define ALPHATEST");
  73113. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73114. attribs.push(BABYLON.VertexBuffer.UVKind);
  73115. defines.push("#define UV1");
  73116. }
  73117. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73118. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73119. defines.push("#define UV2");
  73120. }
  73121. }
  73122. // Bones
  73123. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73124. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73125. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73126. if (mesh.numBoneInfluencers > 4) {
  73127. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73128. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73129. }
  73130. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73131. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73132. }
  73133. else {
  73134. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73135. }
  73136. // Instances
  73137. if (useInstances) {
  73138. defines.push("#define INSTANCES");
  73139. attribs.push("world0");
  73140. attribs.push("world1");
  73141. attribs.push("world2");
  73142. attribs.push("world3");
  73143. }
  73144. // Get correct effect
  73145. var join = defines.join("\n");
  73146. if (this._cachedDefines !== join) {
  73147. this._cachedDefines = join;
  73148. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73149. }
  73150. return this._effect.isReady();
  73151. };
  73152. /**
  73153. * Gets the texture which the depth map will be written to.
  73154. * @returns The depth map texture
  73155. */
  73156. DepthRenderer.prototype.getDepthMap = function () {
  73157. return this._depthMap;
  73158. };
  73159. /**
  73160. * Disposes of the depth renderer.
  73161. */
  73162. DepthRenderer.prototype.dispose = function () {
  73163. this._depthMap.dispose();
  73164. };
  73165. return DepthRenderer;
  73166. }());
  73167. BABYLON.DepthRenderer = DepthRenderer;
  73168. })(BABYLON || (BABYLON = {}));
  73169. //# sourceMappingURL=babylon.depthRenderer.js.map
  73170. var BABYLON;
  73171. (function (BABYLON) {
  73172. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73173. __extends(SSAORenderingPipeline, _super);
  73174. /**
  73175. * @constructor
  73176. * @param {string} name - The rendering pipeline name
  73177. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73178. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  73179. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73180. */
  73181. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73182. var _this = _super.call(this, scene.getEngine(), name) || this;
  73183. // Members
  73184. /**
  73185. * The PassPostProcess id in the pipeline that contains the original scene color
  73186. */
  73187. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73188. /**
  73189. * The SSAO PostProcess id in the pipeline
  73190. */
  73191. _this.SSAORenderEffect = "SSAORenderEffect";
  73192. /**
  73193. * The horizontal blur PostProcess id in the pipeline
  73194. */
  73195. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73196. /**
  73197. * The vertical blur PostProcess id in the pipeline
  73198. */
  73199. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73200. /**
  73201. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73202. */
  73203. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73204. /**
  73205. * The output strength of the SSAO post-process. Default value is 1.0.
  73206. */
  73207. _this.totalStrength = 1.0;
  73208. /**
  73209. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73210. */
  73211. _this.radius = 0.0001;
  73212. /**
  73213. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73214. * Must not be equal to fallOff and superior to fallOff.
  73215. * Default value is 0.975
  73216. */
  73217. _this.area = 0.0075;
  73218. /**
  73219. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73220. * Must not be equal to area and inferior to area.
  73221. * Default value is 0.0
  73222. */
  73223. _this.fallOff = 0.000001;
  73224. /**
  73225. * The base color of the SSAO post-process
  73226. * The final result is "base + ssao" between [0, 1]
  73227. */
  73228. _this.base = 0.5;
  73229. _this._firstUpdate = true;
  73230. _this._scene = scene;
  73231. // Set up assets
  73232. _this._createRandomTexture();
  73233. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73234. var ssaoRatio = ratio.ssaoRatio || ratio;
  73235. var combineRatio = ratio.combineRatio || ratio;
  73236. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73237. _this._createSSAOPostProcess(ssaoRatio);
  73238. _this._createBlurPostProcess(ssaoRatio);
  73239. _this._createSSAOCombinePostProcess(combineRatio);
  73240. // Set up pipeline
  73241. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73242. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73243. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73244. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73245. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73246. // Finish
  73247. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73248. if (cameras)
  73249. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73250. return _this;
  73251. }
  73252. // Public Methods
  73253. /**
  73254. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73255. */
  73256. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73257. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73258. for (var i = 0; i < this._scene.cameras.length; i++) {
  73259. var camera = this._scene.cameras[i];
  73260. this._originalColorPostProcess.dispose(camera);
  73261. this._ssaoPostProcess.dispose(camera);
  73262. this._blurHPostProcess.dispose(camera);
  73263. this._blurVPostProcess.dispose(camera);
  73264. this._ssaoCombinePostProcess.dispose(camera);
  73265. }
  73266. this._randomTexture.dispose();
  73267. if (disableDepthRender)
  73268. this._scene.disableDepthRenderer();
  73269. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73270. _super.prototype.dispose.call(this);
  73271. };
  73272. // Private Methods
  73273. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73274. var _this = this;
  73275. var size = 16;
  73276. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73277. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73278. this._blurHPostProcess.onActivateObservable.add(function () {
  73279. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73280. _this._blurHPostProcess.kernel = size * dw;
  73281. });
  73282. this._blurVPostProcess.onActivateObservable.add(function () {
  73283. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73284. _this._blurVPostProcess.kernel = size * dw;
  73285. });
  73286. };
  73287. SSAORenderingPipeline.prototype._rebuild = function () {
  73288. this._firstUpdate = true;
  73289. _super.prototype._rebuild.call(this);
  73290. };
  73291. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73292. var _this = this;
  73293. var numSamples = 16;
  73294. var sampleSphere = [
  73295. 0.5381, 0.1856, -0.4319,
  73296. 0.1379, 0.2486, 0.4430,
  73297. 0.3371, 0.5679, -0.0057,
  73298. -0.6999, -0.0451, -0.0019,
  73299. 0.0689, -0.1598, -0.8547,
  73300. 0.0560, 0.0069, -0.1843,
  73301. -0.0146, 0.1402, 0.0762,
  73302. 0.0100, -0.1924, -0.0344,
  73303. -0.3577, -0.5301, -0.4358,
  73304. -0.3169, 0.1063, 0.0158,
  73305. 0.0103, -0.5869, 0.0046,
  73306. -0.0897, -0.4940, 0.3287,
  73307. 0.7119, -0.0154, -0.0918,
  73308. -0.0533, 0.0596, -0.5411,
  73309. 0.0352, -0.0631, 0.5460,
  73310. -0.4776, 0.2847, -0.0271
  73311. ];
  73312. var samplesFactor = 1.0 / numSamples;
  73313. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73314. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73315. "area", "fallOff", "base", "range", "viewport"
  73316. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73317. this._ssaoPostProcess.onApply = function (effect) {
  73318. if (_this._firstUpdate) {
  73319. effect.setArray3("sampleSphere", sampleSphere);
  73320. effect.setFloat("samplesFactor", samplesFactor);
  73321. effect.setFloat("randTextureTiles", 4.0);
  73322. }
  73323. effect.setFloat("totalStrength", _this.totalStrength);
  73324. effect.setFloat("radius", _this.radius);
  73325. effect.setFloat("area", _this.area);
  73326. effect.setFloat("fallOff", _this.fallOff);
  73327. effect.setFloat("base", _this.base);
  73328. effect.setTexture("textureSampler", _this._depthTexture);
  73329. effect.setTexture("randomSampler", _this._randomTexture);
  73330. };
  73331. };
  73332. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73333. var _this = this;
  73334. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73335. this._ssaoCombinePostProcess.onApply = function (effect) {
  73336. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73337. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73338. };
  73339. };
  73340. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73341. var size = 512;
  73342. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73343. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73344. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73345. var context = this._randomTexture.getContext();
  73346. var rand = function (min, max) {
  73347. return Math.random() * (max - min) + min;
  73348. };
  73349. var randVector = BABYLON.Vector3.Zero();
  73350. for (var x = 0; x < size; x++) {
  73351. for (var y = 0; y < size; y++) {
  73352. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73353. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73354. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73355. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73356. context.fillRect(x, y, 1, 1);
  73357. }
  73358. }
  73359. this._randomTexture.update(false);
  73360. };
  73361. __decorate([
  73362. BABYLON.serialize()
  73363. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73364. __decorate([
  73365. BABYLON.serialize()
  73366. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73367. __decorate([
  73368. BABYLON.serialize()
  73369. ], SSAORenderingPipeline.prototype, "area", void 0);
  73370. __decorate([
  73371. BABYLON.serialize()
  73372. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73373. __decorate([
  73374. BABYLON.serialize()
  73375. ], SSAORenderingPipeline.prototype, "base", void 0);
  73376. return SSAORenderingPipeline;
  73377. }(BABYLON.PostProcessRenderPipeline));
  73378. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73379. })(BABYLON || (BABYLON = {}));
  73380. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73381. var BABYLON;
  73382. (function (BABYLON) {
  73383. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73384. __extends(SSAO2RenderingPipeline, _super);
  73385. /**
  73386. * @constructor
  73387. * @param {string} name - The rendering pipeline name
  73388. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73389. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  73390. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73391. */
  73392. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73393. var _this = _super.call(this, scene.getEngine(), name) || this;
  73394. // Members
  73395. /**
  73396. * The PassPostProcess id in the pipeline that contains the original scene color
  73397. */
  73398. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73399. /**
  73400. * The SSAO PostProcess id in the pipeline
  73401. */
  73402. _this.SSAORenderEffect = "SSAORenderEffect";
  73403. /**
  73404. * The horizontal blur PostProcess id in the pipeline
  73405. */
  73406. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73407. /**
  73408. * The vertical blur PostProcess id in the pipeline
  73409. */
  73410. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73411. /**
  73412. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73413. */
  73414. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73415. /**
  73416. * The output strength of the SSAO post-process. Default value is 1.0.
  73417. */
  73418. _this.totalStrength = 1.0;
  73419. /**
  73420. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73421. */
  73422. _this.maxZ = 100.0;
  73423. /**
  73424. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73425. */
  73426. _this.minZAspect = 0.2;
  73427. /**
  73428. * Number of samples used for the SSAO calculations. Default value is 8
  73429. */
  73430. _this._samples = 8;
  73431. /**
  73432. * Are we using bilateral blur ?
  73433. */
  73434. _this._expensiveBlur = true;
  73435. /**
  73436. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73437. */
  73438. _this.radius = 2.0;
  73439. /**
  73440. * The base color of the SSAO post-process
  73441. * The final result is "base + ssao" between [0, 1]
  73442. */
  73443. _this.base = 0.1;
  73444. _this._firstUpdate = true;
  73445. _this._scene = scene;
  73446. _this._ratio = ratio;
  73447. if (!_this.isSupported) {
  73448. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73449. return _this;
  73450. }
  73451. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73452. var blurRatio = _this._ratio.blurRatio || ratio;
  73453. // Set up assets
  73454. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73455. _this._createRandomTexture();
  73456. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73457. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73458. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73459. _this._createSSAOPostProcess(1.0);
  73460. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73461. _this._createSSAOCombinePostProcess(blurRatio);
  73462. // Set up pipeline
  73463. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73464. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73465. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73466. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73467. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73468. // Finish
  73469. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73470. if (cameras)
  73471. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73472. return _this;
  73473. }
  73474. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73475. get: function () {
  73476. return this._samples;
  73477. },
  73478. set: function (n) {
  73479. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73480. this._samples = n;
  73481. this._sampleSphere = this._generateHemisphere();
  73482. this._firstUpdate = true;
  73483. },
  73484. enumerable: true,
  73485. configurable: true
  73486. });
  73487. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73488. get: function () {
  73489. return this._expensiveBlur;
  73490. },
  73491. set: function (b) {
  73492. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73493. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73494. this._expensiveBlur = b;
  73495. this._firstUpdate = true;
  73496. },
  73497. enumerable: true,
  73498. configurable: true
  73499. });
  73500. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73501. /**
  73502. * Support test.
  73503. */
  73504. get: function () {
  73505. var engine = BABYLON.Engine.LastCreatedEngine;
  73506. if (!engine) {
  73507. return false;
  73508. }
  73509. return engine.getCaps().drawBuffersExtension;
  73510. },
  73511. enumerable: true,
  73512. configurable: true
  73513. });
  73514. // Public Methods
  73515. /**
  73516. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73517. */
  73518. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73519. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73520. for (var i = 0; i < this._scene.cameras.length; i++) {
  73521. var camera = this._scene.cameras[i];
  73522. this._originalColorPostProcess.dispose(camera);
  73523. this._ssaoPostProcess.dispose(camera);
  73524. this._blurHPostProcess.dispose(camera);
  73525. this._blurVPostProcess.dispose(camera);
  73526. this._ssaoCombinePostProcess.dispose(camera);
  73527. }
  73528. this._randomTexture.dispose();
  73529. if (disableGeometryBufferRenderer)
  73530. this._scene.disableGeometryBufferRenderer();
  73531. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73532. _super.prototype.dispose.call(this);
  73533. };
  73534. // Private Methods
  73535. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73536. var _this = this;
  73537. this._samplerOffsets = [];
  73538. var expensive = this.expensiveBlur;
  73539. for (var i = -8; i < 8; i++) {
  73540. this._samplerOffsets.push(i * 2 + 0.5);
  73541. }
  73542. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  73543. this._blurHPostProcess.onApply = function (effect) {
  73544. if (!_this._scene.activeCamera) {
  73545. return;
  73546. }
  73547. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73548. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73549. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73550. effect.setFloat("radius", _this.radius);
  73551. effect.setTexture("depthSampler", _this._depthTexture);
  73552. if (_this._firstUpdate) {
  73553. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73554. }
  73555. };
  73556. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  73557. this._blurVPostProcess.onApply = function (effect) {
  73558. if (!_this._scene.activeCamera) {
  73559. return;
  73560. }
  73561. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73562. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73563. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73564. effect.setFloat("radius", _this.radius);
  73565. effect.setTexture("depthSampler", _this._depthTexture);
  73566. if (_this._firstUpdate) {
  73567. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73568. _this._firstUpdate = false;
  73569. }
  73570. };
  73571. };
  73572. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73573. this._firstUpdate = true;
  73574. _super.prototype._rebuild.call(this);
  73575. };
  73576. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73577. var numSamples = this.samples;
  73578. var result = [];
  73579. var vector, scale;
  73580. var rand = function (min, max) {
  73581. return Math.random() * (max - min) + min;
  73582. };
  73583. var i = 0;
  73584. while (i < numSamples) {
  73585. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73586. vector.normalize();
  73587. scale = i / numSamples;
  73588. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73589. vector.scaleInPlace(scale);
  73590. result.push(vector.x, vector.y, vector.z);
  73591. i++;
  73592. }
  73593. return result;
  73594. };
  73595. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73596. var _this = this;
  73597. var numSamples = this.samples;
  73598. this._sampleSphere = this._generateHemisphere();
  73599. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73600. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73601. "base", "range", "projection", "near", "far", "texelSize",
  73602. "xViewport", "yViewport", "maxZ", "minZAspect"
  73603. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73604. this._ssaoPostProcess.onApply = function (effect) {
  73605. if (_this._firstUpdate) {
  73606. effect.setArray3("sampleSphere", _this._sampleSphere);
  73607. effect.setFloat("randTextureTiles", 4.0);
  73608. }
  73609. if (!_this._scene.activeCamera) {
  73610. return;
  73611. }
  73612. effect.setFloat("samplesFactor", 1 / _this.samples);
  73613. effect.setFloat("totalStrength", _this.totalStrength);
  73614. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73615. effect.setFloat("radius", _this.radius);
  73616. effect.setFloat("maxZ", _this.maxZ);
  73617. effect.setFloat("minZAspect", _this.minZAspect);
  73618. effect.setFloat("base", _this.base);
  73619. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73620. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73621. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73622. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73623. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73624. effect.setTexture("textureSampler", _this._depthTexture);
  73625. effect.setTexture("normalSampler", _this._normalTexture);
  73626. effect.setTexture("randomSampler", _this._randomTexture);
  73627. };
  73628. };
  73629. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73630. var _this = this;
  73631. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73632. this._ssaoCombinePostProcess.onApply = function (effect) {
  73633. var viewport = _this._scene.activeCamera.viewport;
  73634. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73635. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73636. };
  73637. };
  73638. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73639. var size = 512;
  73640. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73641. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73642. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73643. var context = this._randomTexture.getContext();
  73644. var rand = function (min, max) {
  73645. return Math.random() * (max - min) + min;
  73646. };
  73647. var randVector = BABYLON.Vector3.Zero();
  73648. for (var x = 0; x < size; x++) {
  73649. for (var y = 0; y < size; y++) {
  73650. randVector.x = rand(0.0, 1.0);
  73651. randVector.y = rand(0.0, 1.0);
  73652. randVector.z = 0.0;
  73653. randVector.normalize();
  73654. randVector.scaleInPlace(255);
  73655. randVector.x = Math.floor(randVector.x);
  73656. randVector.y = Math.floor(randVector.y);
  73657. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73658. context.fillRect(x, y, 1, 1);
  73659. }
  73660. }
  73661. this._randomTexture.update(false);
  73662. };
  73663. /**
  73664. * Serialize the rendering pipeline (Used when exporting)
  73665. * @returns the serialized object
  73666. */
  73667. SSAO2RenderingPipeline.prototype.serialize = function () {
  73668. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73669. serializationObject.customType = "SSAO2RenderingPipeline";
  73670. return serializationObject;
  73671. };
  73672. /**
  73673. * Parse the serialized pipeline
  73674. * @param source Source pipeline.
  73675. * @param scene The scene to load the pipeline to.
  73676. * @param rootUrl The URL of the serialized pipeline.
  73677. * @returns An instantiated pipeline from the serialized object.
  73678. */
  73679. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73680. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73681. };
  73682. __decorate([
  73683. BABYLON.serialize()
  73684. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73685. __decorate([
  73686. BABYLON.serialize()
  73687. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73688. __decorate([
  73689. BABYLON.serialize()
  73690. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73691. __decorate([
  73692. BABYLON.serialize("samples")
  73693. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73694. __decorate([
  73695. BABYLON.serialize()
  73696. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73697. __decorate([
  73698. BABYLON.serialize("expensiveBlur")
  73699. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73700. __decorate([
  73701. BABYLON.serialize()
  73702. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73703. __decorate([
  73704. BABYLON.serialize()
  73705. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73706. return SSAO2RenderingPipeline;
  73707. }(BABYLON.PostProcessRenderPipeline));
  73708. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73709. })(BABYLON || (BABYLON = {}));
  73710. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73711. // BABYLON.JS Chromatic Aberration GLSL Shader
  73712. // Author: Olivier Guyot
  73713. // Separates very slightly R, G and B colors on the edges of the screen
  73714. // Inspired by Francois Tarlier & Martins Upitis
  73715. var BABYLON;
  73716. (function (BABYLON) {
  73717. var LensRenderingPipeline = /** @class */ (function (_super) {
  73718. __extends(LensRenderingPipeline, _super);
  73719. /**
  73720. * @constructor
  73721. *
  73722. * Effect parameters are as follow:
  73723. * {
  73724. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73725. * edge_blur: number; // from 0 to x (1 for realism)
  73726. * distortion: number; // from 0 to x (1 for realism)
  73727. * grain_amount: number; // from 0 to 1
  73728. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73729. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73730. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73731. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73732. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73733. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73734. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73735. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73736. * }
  73737. * Note: if an effect parameter is unset, effect is disabled
  73738. *
  73739. * @param {string} name - The rendering pipeline name
  73740. * @param {object} parameters - An object containing all parameters (see above)
  73741. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73742. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  73743. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73744. */
  73745. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73746. if (ratio === void 0) { ratio = 1.0; }
  73747. var _this = _super.call(this, scene.getEngine(), name) || this;
  73748. // Lens effects can be of the following:
  73749. // - chromatic aberration (slight shift of RGB colors)
  73750. // - blur on the edge of the lens
  73751. // - lens distortion
  73752. // - depth-of-field blur & highlights enhancing
  73753. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73754. // - grain effect (noise or custom texture)
  73755. // Two additional texture samplers are needed:
  73756. // - depth map (for depth-of-field)
  73757. // - grain texture
  73758. /**
  73759. * The chromatic aberration PostProcess id in the pipeline
  73760. */
  73761. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73762. /**
  73763. * The highlights enhancing PostProcess id in the pipeline
  73764. */
  73765. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73766. /**
  73767. * The depth-of-field PostProcess id in the pipeline
  73768. */
  73769. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73770. _this._scene = scene;
  73771. // Fetch texture samplers
  73772. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73773. if (parameters.grain_texture) {
  73774. _this._grainTexture = parameters.grain_texture;
  73775. }
  73776. else {
  73777. _this._createGrainTexture();
  73778. }
  73779. // save parameters
  73780. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73781. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73782. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73783. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73784. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73785. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73786. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73787. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73788. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73789. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73790. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73791. // Create effects
  73792. _this._createChromaticAberrationPostProcess(ratio);
  73793. _this._createHighlightsPostProcess(ratio);
  73794. _this._createDepthOfFieldPostProcess(ratio / 4);
  73795. // Set up pipeline
  73796. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73797. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73798. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73799. if (_this._highlightsGain === -1) {
  73800. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73801. }
  73802. // Finish
  73803. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73804. if (cameras) {
  73805. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73806. }
  73807. return _this;
  73808. }
  73809. // public methods (self explanatory)
  73810. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73811. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73812. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73813. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73814. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73815. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73816. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73817. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73818. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73819. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73820. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73821. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73822. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73823. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73824. };
  73825. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73826. this._highlightsPostProcess.updateEffect();
  73827. };
  73828. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73829. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73830. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73831. this._highlightsGain = amount;
  73832. };
  73833. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73834. if (this._highlightsGain === -1) {
  73835. this._highlightsGain = 1.0;
  73836. }
  73837. this._highlightsThreshold = amount;
  73838. };
  73839. LensRenderingPipeline.prototype.disableHighlights = function () {
  73840. this._highlightsGain = -1;
  73841. };
  73842. /**
  73843. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73844. */
  73845. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73846. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73847. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73848. this._chromaticAberrationPostProcess = null;
  73849. this._highlightsPostProcess = null;
  73850. this._depthOfFieldPostProcess = null;
  73851. this._grainTexture.dispose();
  73852. if (disableDepthRender)
  73853. this._scene.disableDepthRenderer();
  73854. };
  73855. // colors shifting and distortion
  73856. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73857. var _this = this;
  73858. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73859. [], // samplers
  73860. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73861. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73862. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73863. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73864. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73865. effect.setFloat('radialIntensity', 1);
  73866. effect.setFloat2('direction', 17, 17);
  73867. effect.setFloat2('centerPosition', 0.5, 0.5);
  73868. };
  73869. };
  73870. // highlights enhancing
  73871. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73872. var _this = this;
  73873. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73874. [], // samplers
  73875. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73876. this._highlightsPostProcess.onApply = function (effect) {
  73877. effect.setFloat('gain', _this._highlightsGain);
  73878. effect.setFloat('threshold', _this._highlightsThreshold);
  73879. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73880. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73881. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73882. };
  73883. };
  73884. // colors shifting and distortion
  73885. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73886. var _this = this;
  73887. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73888. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73889. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73890. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73891. this._depthOfFieldPostProcess.onApply = function (effect) {
  73892. effect.setTexture("depthSampler", _this._depthTexture);
  73893. effect.setTexture("grainSampler", _this._grainTexture);
  73894. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73895. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73896. effect.setFloat('grain_amount', _this._grainAmount);
  73897. effect.setBool('blur_noise', _this._blurNoise);
  73898. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73899. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73900. effect.setFloat('distortion', _this._distortion);
  73901. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73902. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73903. effect.setFloat('aperture', _this._dofAperture);
  73904. effect.setFloat('darken', _this._dofDarken);
  73905. effect.setFloat('edge_blur', _this._edgeBlur);
  73906. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73907. if (_this._scene.activeCamera) {
  73908. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73909. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73910. }
  73911. };
  73912. };
  73913. // creates a black and white random noise texture, 512x512
  73914. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73915. var size = 512;
  73916. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73917. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73918. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73919. var context = this._grainTexture.getContext();
  73920. var rand = function (min, max) {
  73921. return Math.random() * (max - min) + min;
  73922. };
  73923. var value;
  73924. for (var x = 0; x < size; x++) {
  73925. for (var y = 0; y < size; y++) {
  73926. value = Math.floor(rand(0.42, 0.58) * 255);
  73927. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73928. context.fillRect(x, y, 1, 1);
  73929. }
  73930. }
  73931. this._grainTexture.update(false);
  73932. };
  73933. return LensRenderingPipeline;
  73934. }(BABYLON.PostProcessRenderPipeline));
  73935. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73936. })(BABYLON || (BABYLON = {}));
  73937. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73938. var BABYLON;
  73939. (function (BABYLON) {
  73940. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73941. __extends(StandardRenderingPipeline, _super);
  73942. /**
  73943. * @constructor
  73944. * @param {string} name - The rendering pipeline name
  73945. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73946. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  73947. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73948. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73949. */
  73950. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73951. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73952. var _this = _super.call(this, scene.getEngine(), name) || this;
  73953. _this.downSampleX4PostProcess = null;
  73954. _this.brightPassPostProcess = null;
  73955. _this.blurHPostProcesses = [];
  73956. _this.blurVPostProcesses = [];
  73957. _this.textureAdderPostProcess = null;
  73958. _this.volumetricLightPostProcess = null;
  73959. _this.volumetricLightSmoothXPostProcess = null;
  73960. _this.volumetricLightSmoothYPostProcess = null;
  73961. _this.volumetricLightMergePostProces = null;
  73962. _this.volumetricLightFinalPostProcess = null;
  73963. _this.luminancePostProcess = null;
  73964. _this.luminanceDownSamplePostProcesses = [];
  73965. _this.hdrPostProcess = null;
  73966. _this.textureAdderFinalPostProcess = null;
  73967. _this.lensFlareFinalPostProcess = null;
  73968. _this.hdrFinalPostProcess = null;
  73969. _this.lensFlarePostProcess = null;
  73970. _this.lensFlareComposePostProcess = null;
  73971. _this.motionBlurPostProcess = null;
  73972. _this.depthOfFieldPostProcess = null;
  73973. // Values
  73974. _this.brightThreshold = 1.0;
  73975. _this.blurWidth = 512.0;
  73976. _this.horizontalBlur = false;
  73977. _this.exposure = 1.0;
  73978. _this.lensTexture = null;
  73979. _this.volumetricLightCoefficient = 0.2;
  73980. _this.volumetricLightPower = 4.0;
  73981. _this.volumetricLightBlurScale = 64.0;
  73982. _this.sourceLight = null;
  73983. _this.hdrMinimumLuminance = 1.0;
  73984. _this.hdrDecreaseRate = 0.5;
  73985. _this.hdrIncreaseRate = 0.5;
  73986. _this.lensColorTexture = null;
  73987. _this.lensFlareStrength = 20.0;
  73988. _this.lensFlareGhostDispersal = 1.4;
  73989. _this.lensFlareHaloWidth = 0.7;
  73990. _this.lensFlareDistortionStrength = 16.0;
  73991. _this.lensStarTexture = null;
  73992. _this.lensFlareDirtTexture = null;
  73993. _this.depthOfFieldDistance = 10.0;
  73994. _this.depthOfFieldBlurWidth = 64.0;
  73995. _this.motionStrength = 1.0;
  73996. // IAnimatable
  73997. _this.animations = [];
  73998. _this._currentDepthOfFieldSource = null;
  73999. _this._hdrCurrentLuminance = 1.0;
  74000. // Getters and setters
  74001. _this._bloomEnabled = true;
  74002. _this._depthOfFieldEnabled = false;
  74003. _this._vlsEnabled = false;
  74004. _this._lensFlareEnabled = false;
  74005. _this._hdrEnabled = false;
  74006. _this._motionBlurEnabled = false;
  74007. _this._motionBlurSamples = 64.0;
  74008. _this._volumetricLightStepsCount = 50.0;
  74009. _this._cameras = cameras || [];
  74010. // Initialize
  74011. _this._scene = scene;
  74012. _this._basePostProcess = originalPostProcess;
  74013. _this._ratio = ratio;
  74014. // Misc
  74015. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74016. // Finish
  74017. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74018. _this._buildPipeline();
  74019. return _this;
  74020. }
  74021. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74022. get: function () {
  74023. return this._bloomEnabled;
  74024. },
  74025. set: function (enabled) {
  74026. if (this._bloomEnabled === enabled) {
  74027. return;
  74028. }
  74029. this._bloomEnabled = enabled;
  74030. this._buildPipeline();
  74031. },
  74032. enumerable: true,
  74033. configurable: true
  74034. });
  74035. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74036. get: function () {
  74037. return this._depthOfFieldEnabled;
  74038. },
  74039. set: function (enabled) {
  74040. if (this._depthOfFieldEnabled === enabled) {
  74041. return;
  74042. }
  74043. this._depthOfFieldEnabled = enabled;
  74044. this._buildPipeline();
  74045. },
  74046. enumerable: true,
  74047. configurable: true
  74048. });
  74049. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74050. get: function () {
  74051. return this._lensFlareEnabled;
  74052. },
  74053. set: function (enabled) {
  74054. if (this._lensFlareEnabled === enabled) {
  74055. return;
  74056. }
  74057. this._lensFlareEnabled = enabled;
  74058. this._buildPipeline();
  74059. },
  74060. enumerable: true,
  74061. configurable: true
  74062. });
  74063. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74064. get: function () {
  74065. return this._hdrEnabled;
  74066. },
  74067. set: function (enabled) {
  74068. if (this._hdrEnabled === enabled) {
  74069. return;
  74070. }
  74071. this._hdrEnabled = enabled;
  74072. this._buildPipeline();
  74073. },
  74074. enumerable: true,
  74075. configurable: true
  74076. });
  74077. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74078. get: function () {
  74079. return this._vlsEnabled;
  74080. },
  74081. set: function (enabled) {
  74082. if (this._vlsEnabled === enabled) {
  74083. return;
  74084. }
  74085. if (enabled) {
  74086. var geometry = this._scene.enableGeometryBufferRenderer();
  74087. if (!geometry) {
  74088. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74089. return;
  74090. }
  74091. }
  74092. this._vlsEnabled = enabled;
  74093. this._buildPipeline();
  74094. },
  74095. enumerable: true,
  74096. configurable: true
  74097. });
  74098. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74099. get: function () {
  74100. return this._motionBlurEnabled;
  74101. },
  74102. set: function (enabled) {
  74103. if (this._motionBlurEnabled === enabled) {
  74104. return;
  74105. }
  74106. this._motionBlurEnabled = enabled;
  74107. this._buildPipeline();
  74108. },
  74109. enumerable: true,
  74110. configurable: true
  74111. });
  74112. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74113. get: function () {
  74114. return this._volumetricLightStepsCount;
  74115. },
  74116. set: function (count) {
  74117. if (this.volumetricLightPostProcess) {
  74118. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74119. }
  74120. this._volumetricLightStepsCount = count;
  74121. },
  74122. enumerable: true,
  74123. configurable: true
  74124. });
  74125. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74126. get: function () {
  74127. return this._motionBlurSamples;
  74128. },
  74129. set: function (samples) {
  74130. if (this.motionBlurPostProcess) {
  74131. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74132. }
  74133. this._motionBlurSamples = samples;
  74134. },
  74135. enumerable: true,
  74136. configurable: true
  74137. });
  74138. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74139. var _this = this;
  74140. var ratio = this._ratio;
  74141. var scene = this._scene;
  74142. this._disposePostProcesses();
  74143. this._reset();
  74144. // Create pass post-process
  74145. if (!this._basePostProcess) {
  74146. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74147. this.originalPostProcess.onApply = function (effect) {
  74148. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74149. };
  74150. }
  74151. else {
  74152. this.originalPostProcess = this._basePostProcess;
  74153. }
  74154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74155. this._currentDepthOfFieldSource = this.originalPostProcess;
  74156. if (this._bloomEnabled) {
  74157. // Create down sample X4 post-process
  74158. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74159. // Create bright pass post-process
  74160. this._createBrightPassPostProcess(scene, ratio / 2);
  74161. // Create gaussian blur post-processes (down sampling blurs)
  74162. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74163. // Create texture adder post-process
  74164. this._createTextureAdderPostProcess(scene, ratio);
  74165. // Create depth-of-field source post-process
  74166. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74167. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74168. }
  74169. if (this._vlsEnabled) {
  74170. // Create volumetric light
  74171. this._createVolumetricLightPostProcess(scene, ratio);
  74172. // Create volumetric light final post-process
  74173. this.volumetricLightFinalPostProcess = new BABYLON.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74175. }
  74176. if (this._lensFlareEnabled) {
  74177. // Create lens flare post-process
  74178. this._createLensFlarePostProcess(scene, ratio);
  74179. // Create depth-of-field source post-process post lens-flare and disable it now
  74180. this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74181. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74182. }
  74183. if (this._hdrEnabled) {
  74184. // Create luminance
  74185. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74186. // Create HDR
  74187. this._createHdrPostProcess(scene, ratio);
  74188. // Create depth-of-field source post-process post hdr and disable it now
  74189. this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74190. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74191. }
  74192. if (this._depthOfFieldEnabled) {
  74193. // Create gaussian blur used by depth-of-field
  74194. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74195. // Create depth-of-field post-process
  74196. this._createDepthOfFieldPostProcess(scene, ratio);
  74197. }
  74198. if (this._motionBlurEnabled) {
  74199. // Create motion blur post-process
  74200. this._createMotionBlurPostProcess(scene, ratio);
  74201. }
  74202. if (this._cameras !== null) {
  74203. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74204. }
  74205. };
  74206. // Down Sample X4 Post-Processs
  74207. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74208. var _this = this;
  74209. var downSampleX4Offsets = new Array(32);
  74210. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74211. this.downSampleX4PostProcess.onApply = function (effect) {
  74212. var id = 0;
  74213. var width = _this.downSampleX4PostProcess.width;
  74214. var height = _this.downSampleX4PostProcess.height;
  74215. for (var i = -2; i < 2; i++) {
  74216. for (var j = -2; j < 2; j++) {
  74217. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74218. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74219. id += 2;
  74220. }
  74221. }
  74222. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74223. };
  74224. // Add to pipeline
  74225. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74226. };
  74227. // Brightpass Post-Process
  74228. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74229. var _this = this;
  74230. var brightOffsets = new Array(8);
  74231. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74232. this.brightPassPostProcess.onApply = function (effect) {
  74233. var sU = (1.0 / _this.brightPassPostProcess.width);
  74234. var sV = (1.0 / _this.brightPassPostProcess.height);
  74235. brightOffsets[0] = -0.5 * sU;
  74236. brightOffsets[1] = 0.5 * sV;
  74237. brightOffsets[2] = 0.5 * sU;
  74238. brightOffsets[3] = 0.5 * sV;
  74239. brightOffsets[4] = -0.5 * sU;
  74240. brightOffsets[5] = -0.5 * sV;
  74241. brightOffsets[6] = 0.5 * sU;
  74242. brightOffsets[7] = -0.5 * sV;
  74243. effect.setArray2("dsOffsets", brightOffsets);
  74244. effect.setFloat("brightThreshold", _this.brightThreshold);
  74245. };
  74246. // Add to pipeline
  74247. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74248. };
  74249. // Create blur H&V post-processes
  74250. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74251. var _this = this;
  74252. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74253. var engine = scene.getEngine();
  74254. var blurX = new BABYLON.BlurPostProcess("HDRBlurH" + "_" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74255. var blurY = new BABYLON.BlurPostProcess("HDRBlurV" + "_" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74256. blurX.onActivateObservable.add(function () {
  74257. var dw = blurX.width / engine.getRenderWidth();
  74258. blurX.kernel = _this[blurWidthKey] * dw;
  74259. });
  74260. blurY.onActivateObservable.add(function () {
  74261. var dw = blurY.height / engine.getRenderHeight();
  74262. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74263. });
  74264. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74265. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74266. this.blurHPostProcesses.push(blurX);
  74267. this.blurVPostProcesses.push(blurY);
  74268. };
  74269. // Create texture adder post-process
  74270. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74271. var _this = this;
  74272. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74273. this.textureAdderPostProcess.onApply = function (effect) {
  74274. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74275. effect.setTexture("lensSampler", _this.lensTexture);
  74276. effect.setFloat("exposure", _this.exposure);
  74277. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74278. };
  74279. // Add to pipeline
  74280. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74281. };
  74282. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74283. var _this = this;
  74284. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74285. geometryRenderer.enablePosition = true;
  74286. var geometry = geometryRenderer.getGBuffer();
  74287. // Base post-process
  74288. this.volumetricLightPostProcess = new BABYLON.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
  74289. var depthValues = BABYLON.Vector2.Zero();
  74290. this.volumetricLightPostProcess.onApply = function (effect) {
  74291. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74292. var generator = _this.sourceLight.getShadowGenerator();
  74293. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74294. effect.setTexture("positionSampler", geometry.textures[2]);
  74295. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74296. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74297. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74298. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74299. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74300. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74301. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74302. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74303. effect.setVector2("depthValues", depthValues);
  74304. }
  74305. };
  74306. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74307. // Smooth
  74308. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74309. // Merge
  74310. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74311. this.volumetricLightMergePostProces.onApply = function (effect) {
  74312. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74313. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74314. };
  74315. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74316. };
  74317. // Create luminance
  74318. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74319. var _this = this;
  74320. // Create luminance
  74321. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74322. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74323. var offsets = [];
  74324. this.luminancePostProcess.onApply = function (effect) {
  74325. var sU = (1.0 / _this.luminancePostProcess.width);
  74326. var sV = (1.0 / _this.luminancePostProcess.height);
  74327. offsets[0] = -0.5 * sU;
  74328. offsets[1] = 0.5 * sV;
  74329. offsets[2] = 0.5 * sU;
  74330. offsets[3] = 0.5 * sV;
  74331. offsets[4] = -0.5 * sU;
  74332. offsets[5] = -0.5 * sV;
  74333. offsets[6] = 0.5 * sU;
  74334. offsets[7] = -0.5 * sV;
  74335. effect.setArray2("lumOffsets", offsets);
  74336. };
  74337. // Add to pipeline
  74338. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74339. // Create down sample luminance
  74340. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74341. var size = Math.pow(3, i);
  74342. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74343. if (i === 0) {
  74344. defines += "#define FINAL_DOWN_SAMPLER";
  74345. }
  74346. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74347. this.luminanceDownSamplePostProcesses.push(postProcess);
  74348. }
  74349. // Create callbacks and add effects
  74350. var lastLuminance = this.luminancePostProcess;
  74351. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74352. var downSampleOffsets = new Array(18);
  74353. pp.onApply = function (effect) {
  74354. if (!lastLuminance) {
  74355. return;
  74356. }
  74357. var id = 0;
  74358. for (var x = -1; x < 2; x++) {
  74359. for (var y = -1; y < 2; y++) {
  74360. downSampleOffsets[id] = x / lastLuminance.width;
  74361. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74362. id += 2;
  74363. }
  74364. }
  74365. effect.setArray2("dsOffsets", downSampleOffsets);
  74366. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74367. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74368. lastLuminance = _this.luminancePostProcess;
  74369. }
  74370. else {
  74371. lastLuminance = pp;
  74372. }
  74373. };
  74374. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74375. pp.onAfterRender = function (effect) {
  74376. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74377. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  74378. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74379. };
  74380. }
  74381. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74382. });
  74383. };
  74384. // Create HDR post-process
  74385. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74386. var _this = this;
  74387. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74388. var outputLiminance = 1;
  74389. var time = 0;
  74390. var lastTime = 0;
  74391. this.hdrPostProcess.onApply = function (effect) {
  74392. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74393. time += scene.getEngine().getDeltaTime();
  74394. if (outputLiminance < 0) {
  74395. outputLiminance = _this._hdrCurrentLuminance;
  74396. }
  74397. else {
  74398. var dt = (lastTime - time) / 1000.0;
  74399. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74400. outputLiminance += _this.hdrDecreaseRate * dt;
  74401. }
  74402. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74403. outputLiminance -= _this.hdrIncreaseRate * dt;
  74404. }
  74405. else {
  74406. outputLiminance = _this._hdrCurrentLuminance;
  74407. }
  74408. }
  74409. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74410. effect.setFloat("averageLuminance", outputLiminance);
  74411. lastTime = time;
  74412. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74413. };
  74414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74415. };
  74416. // Create lens flare post-process
  74417. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74418. var _this = this;
  74419. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74420. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74421. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74422. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74424. var resolution = new BABYLON.Vector2(0, 0);
  74425. // Lens flare
  74426. this.lensFlarePostProcess.onApply = function (effect) {
  74427. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74428. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74429. effect.setFloat("strength", _this.lensFlareStrength);
  74430. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74431. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74432. // Shift
  74433. resolution.x = _this.lensFlarePostProcess.width;
  74434. resolution.y = _this.lensFlarePostProcess.height;
  74435. effect.setVector2("resolution", resolution);
  74436. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74437. };
  74438. // Compose
  74439. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  74440. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  74441. this.lensFlareComposePostProcess.onApply = function (effect) {
  74442. if (!_this._scene.activeCamera) {
  74443. return;
  74444. }
  74445. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74446. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74447. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74448. // Lens start rotation matrix
  74449. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74450. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74451. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  74452. camRot *= 4.0;
  74453. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  74454. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74455. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74456. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74457. };
  74458. };
  74459. // Create depth-of-field post-process
  74460. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74461. var _this = this;
  74462. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74463. this.depthOfFieldPostProcess.onApply = function (effect) {
  74464. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74465. effect.setTexture("depthSampler", _this._getDepthTexture());
  74466. effect.setFloat("distance", _this.depthOfFieldDistance);
  74467. };
  74468. // Add to pipeline
  74469. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74470. };
  74471. // Create motion blur post-process
  74472. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74473. var _this = this;
  74474. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74475. var motionScale = 0;
  74476. var prevViewProjection = BABYLON.Matrix.Identity();
  74477. var invViewProjection = BABYLON.Matrix.Identity();
  74478. var viewProjection = BABYLON.Matrix.Identity();
  74479. var screenSize = BABYLON.Vector2.Zero();
  74480. this.motionBlurPostProcess.onApply = function (effect) {
  74481. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74482. viewProjection.invertToRef(invViewProjection);
  74483. effect.setMatrix("inverseViewProjection", invViewProjection);
  74484. effect.setMatrix("prevViewProjection", prevViewProjection);
  74485. prevViewProjection = viewProjection;
  74486. screenSize.x = _this.motionBlurPostProcess.width;
  74487. screenSize.y = _this.motionBlurPostProcess.height;
  74488. effect.setVector2("screenSize", screenSize);
  74489. motionScale = scene.getEngine().getFps() / 60.0;
  74490. effect.setFloat("motionScale", motionScale);
  74491. effect.setFloat("motionStrength", _this.motionStrength);
  74492. effect.setTexture("depthSampler", _this._getDepthTexture());
  74493. };
  74494. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74495. };
  74496. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74497. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74498. var renderer = this._scene.enableGeometryBufferRenderer();
  74499. return renderer.getGBuffer().textures[0];
  74500. }
  74501. return this._scene.enableDepthRenderer().getDepthMap();
  74502. };
  74503. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74504. for (var i = 0; i < this._cameras.length; i++) {
  74505. var camera = this._cameras[i];
  74506. if (this.originalPostProcess) {
  74507. this.originalPostProcess.dispose(camera);
  74508. }
  74509. if (this.downSampleX4PostProcess) {
  74510. this.downSampleX4PostProcess.dispose(camera);
  74511. }
  74512. if (this.brightPassPostProcess) {
  74513. this.brightPassPostProcess.dispose(camera);
  74514. }
  74515. if (this.textureAdderPostProcess) {
  74516. this.textureAdderPostProcess.dispose(camera);
  74517. }
  74518. if (this.textureAdderFinalPostProcess) {
  74519. this.textureAdderFinalPostProcess.dispose(camera);
  74520. }
  74521. if (this.volumetricLightPostProcess) {
  74522. this.volumetricLightPostProcess.dispose(camera);
  74523. }
  74524. if (this.volumetricLightSmoothXPostProcess) {
  74525. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74526. }
  74527. if (this.volumetricLightSmoothYPostProcess) {
  74528. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74529. }
  74530. if (this.volumetricLightMergePostProces) {
  74531. this.volumetricLightMergePostProces.dispose(camera);
  74532. }
  74533. if (this.volumetricLightFinalPostProcess) {
  74534. this.volumetricLightFinalPostProcess.dispose(camera);
  74535. }
  74536. if (this.lensFlarePostProcess) {
  74537. this.lensFlarePostProcess.dispose(camera);
  74538. }
  74539. if (this.lensFlareComposePostProcess) {
  74540. this.lensFlareComposePostProcess.dispose(camera);
  74541. }
  74542. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74543. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74544. }
  74545. if (this.luminancePostProcess) {
  74546. this.luminancePostProcess.dispose(camera);
  74547. }
  74548. if (this.hdrPostProcess) {
  74549. this.hdrPostProcess.dispose(camera);
  74550. }
  74551. if (this.hdrFinalPostProcess) {
  74552. this.hdrFinalPostProcess.dispose(camera);
  74553. }
  74554. if (this.depthOfFieldPostProcess) {
  74555. this.depthOfFieldPostProcess.dispose(camera);
  74556. }
  74557. if (this.motionBlurPostProcess) {
  74558. this.motionBlurPostProcess.dispose(camera);
  74559. }
  74560. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74561. this.blurHPostProcesses[j].dispose(camera);
  74562. }
  74563. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74564. this.blurVPostProcesses[j].dispose(camera);
  74565. }
  74566. }
  74567. this.originalPostProcess = null;
  74568. this.downSampleX4PostProcess = null;
  74569. this.brightPassPostProcess = null;
  74570. this.textureAdderPostProcess = null;
  74571. this.textureAdderFinalPostProcess = null;
  74572. this.volumetricLightPostProcess = null;
  74573. this.volumetricLightSmoothXPostProcess = null;
  74574. this.volumetricLightSmoothYPostProcess = null;
  74575. this.volumetricLightMergePostProces = null;
  74576. this.volumetricLightFinalPostProcess = null;
  74577. this.lensFlarePostProcess = null;
  74578. this.lensFlareComposePostProcess = null;
  74579. this.luminancePostProcess = null;
  74580. this.hdrPostProcess = null;
  74581. this.hdrFinalPostProcess = null;
  74582. this.depthOfFieldPostProcess = null;
  74583. this.motionBlurPostProcess = null;
  74584. this.luminanceDownSamplePostProcesses = [];
  74585. this.blurHPostProcesses = [];
  74586. this.blurVPostProcesses = [];
  74587. };
  74588. /**
  74589. * Dispose of the pipeline and stop all post processes
  74590. */
  74591. StandardRenderingPipeline.prototype.dispose = function () {
  74592. this._disposePostProcesses();
  74593. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74594. _super.prototype.dispose.call(this);
  74595. };
  74596. /**
  74597. * Serialize the rendering pipeline (Used when exporting)
  74598. * @returns the serialized object
  74599. */
  74600. StandardRenderingPipeline.prototype.serialize = function () {
  74601. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74602. if (this.sourceLight) {
  74603. serializationObject.sourceLightId = this.sourceLight.id;
  74604. }
  74605. serializationObject.customType = "StandardRenderingPipeline";
  74606. return serializationObject;
  74607. };
  74608. /**
  74609. * Parse the serialized pipeline
  74610. * @param source Source pipeline.
  74611. * @param scene The scene to load the pipeline to.
  74612. * @param rootUrl The URL of the serialized pipeline.
  74613. * @returns An instantiated pipeline from the serialized object.
  74614. */
  74615. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74616. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74617. if (source.sourceLightId) {
  74618. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74619. }
  74620. return p;
  74621. };
  74622. // Luminance steps
  74623. StandardRenderingPipeline.LuminanceSteps = 6;
  74624. __decorate([
  74625. BABYLON.serialize()
  74626. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74627. __decorate([
  74628. BABYLON.serialize()
  74629. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74630. __decorate([
  74631. BABYLON.serialize()
  74632. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74633. __decorate([
  74634. BABYLON.serialize()
  74635. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74636. __decorate([
  74637. BABYLON.serializeAsTexture("lensTexture")
  74638. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74639. __decorate([
  74640. BABYLON.serialize()
  74641. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74642. __decorate([
  74643. BABYLON.serialize()
  74644. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74645. __decorate([
  74646. BABYLON.serialize()
  74647. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74648. __decorate([
  74649. BABYLON.serialize()
  74650. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74651. __decorate([
  74652. BABYLON.serialize()
  74653. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74654. __decorate([
  74655. BABYLON.serialize()
  74656. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74657. __decorate([
  74658. BABYLON.serializeAsTexture("lensColorTexture")
  74659. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74660. __decorate([
  74661. BABYLON.serialize()
  74662. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74663. __decorate([
  74664. BABYLON.serialize()
  74665. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74666. __decorate([
  74667. BABYLON.serialize()
  74668. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74669. __decorate([
  74670. BABYLON.serialize()
  74671. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74672. __decorate([
  74673. BABYLON.serializeAsTexture("lensStarTexture")
  74674. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74675. __decorate([
  74676. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74677. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74678. __decorate([
  74679. BABYLON.serialize()
  74680. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74681. __decorate([
  74682. BABYLON.serialize()
  74683. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74684. __decorate([
  74685. BABYLON.serialize()
  74686. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74687. __decorate([
  74688. BABYLON.serialize()
  74689. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74690. __decorate([
  74691. BABYLON.serialize()
  74692. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74693. __decorate([
  74694. BABYLON.serialize()
  74695. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74696. __decorate([
  74697. BABYLON.serialize()
  74698. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74699. __decorate([
  74700. BABYLON.serialize()
  74701. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74702. __decorate([
  74703. BABYLON.serialize()
  74704. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74705. __decorate([
  74706. BABYLON.serialize()
  74707. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74708. __decorate([
  74709. BABYLON.serialize()
  74710. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74711. __decorate([
  74712. BABYLON.serialize()
  74713. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74714. return StandardRenderingPipeline;
  74715. }(BABYLON.PostProcessRenderPipeline));
  74716. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74717. })(BABYLON || (BABYLON = {}));
  74718. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74719. var BABYLON;
  74720. (function (BABYLON) {
  74721. var FxaaPostProcess = /** @class */ (function (_super) {
  74722. __extends(FxaaPostProcess, _super);
  74723. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74724. if (camera === void 0) { camera = null; }
  74725. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74726. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74727. var defines = _this._getDefines();
  74728. _this.updateEffect(defines);
  74729. _this.onApplyObservable.add(function (effect) {
  74730. var texelSize = _this.texelSize;
  74731. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74732. });
  74733. return _this;
  74734. }
  74735. FxaaPostProcess.prototype._getDefines = function () {
  74736. var engine = this.getEngine();
  74737. if (!engine) {
  74738. return null;
  74739. }
  74740. var glInfo = engine.getGlInfo();
  74741. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74742. return "#define MALI 1\n";
  74743. }
  74744. return null;
  74745. };
  74746. return FxaaPostProcess;
  74747. }(BABYLON.PostProcess));
  74748. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74749. })(BABYLON || (BABYLON = {}));
  74750. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74751. var BABYLON;
  74752. (function (BABYLON) {
  74753. /**
  74754. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74755. */
  74756. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74757. __extends(ChromaticAberrationPostProcess, _super);
  74758. /**
  74759. * Creates a new instance ChromaticAberrationPostProcess
  74760. * @param name The name of the effect.
  74761. * @param screenWidth The width of the screen to apply the effect on.
  74762. * @param screenHeight The height of the screen to apply the effect on.
  74763. * @param options The required width/height ratio to downsize to before computing the render pass.
  74764. * @param camera The camera to apply the render pass to.
  74765. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74766. * @param engine The engine which the post process will be applied. (default: current engine)
  74767. * @param reusable If the post process can be reused on the same frame. (default: false)
  74768. * @param textureType Type of textures used when performing the post process. (default: 0)
  74769. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74770. */
  74771. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74772. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74773. if (blockCompilation === void 0) { blockCompilation = false; }
  74774. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74775. /**
  74776. * The amount of seperation of rgb channels (default: 30)
  74777. */
  74778. _this.aberrationAmount = 30;
  74779. /**
  74780. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74781. */
  74782. _this.radialIntensity = 0;
  74783. /**
  74784. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  74785. */
  74786. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74787. /**
  74788. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  74789. */
  74790. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74791. _this.onApplyObservable.add(function (effect) {
  74792. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74793. effect.setFloat('screen_width', screenWidth);
  74794. effect.setFloat('screen_height', screenHeight);
  74795. effect.setFloat('radialIntensity', _this.radialIntensity);
  74796. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74797. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74798. });
  74799. return _this;
  74800. }
  74801. return ChromaticAberrationPostProcess;
  74802. }(BABYLON.PostProcess));
  74803. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74804. })(BABYLON || (BABYLON = {}));
  74805. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74806. var BABYLON;
  74807. (function (BABYLON) {
  74808. /**
  74809. * The GrainPostProcess adds noise to the image at mid luminance levels
  74810. */
  74811. var GrainPostProcess = /** @class */ (function (_super) {
  74812. __extends(GrainPostProcess, _super);
  74813. /**
  74814. * Creates a new instance of @see GrainPostProcess
  74815. * @param name The name of the effect.
  74816. * @param options The required width/height ratio to downsize to before computing the render pass.
  74817. * @param camera The camera to apply the render pass to.
  74818. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74819. * @param engine The engine which the post process will be applied. (default: current engine)
  74820. * @param reusable If the post process can be reused on the same frame. (default: false)
  74821. * @param textureType Type of textures used when performing the post process. (default: 0)
  74822. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74823. */
  74824. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74825. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74826. if (blockCompilation === void 0) { blockCompilation = false; }
  74827. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74828. /**
  74829. * The intensity of the grain added (default: 30)
  74830. */
  74831. _this.intensity = 30;
  74832. /**
  74833. * If the grain should be randomized on every frame
  74834. */
  74835. _this.animated = false;
  74836. _this.onApplyObservable.add(function (effect) {
  74837. effect.setFloat('intensity', _this.intensity);
  74838. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74839. });
  74840. return _this;
  74841. }
  74842. return GrainPostProcess;
  74843. }(BABYLON.PostProcess));
  74844. BABYLON.GrainPostProcess = GrainPostProcess;
  74845. })(BABYLON || (BABYLON = {}));
  74846. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74847. var BABYLON;
  74848. (function (BABYLON) {
  74849. /**
  74850. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74851. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74852. */
  74853. var SharpenPostProcess = /** @class */ (function (_super) {
  74854. __extends(SharpenPostProcess, _super);
  74855. /**
  74856. * Creates a new instance ConvolutionPostProcess
  74857. * @param name The name of the effect.
  74858. * @param options The required width/height ratio to downsize to before computing the render pass.
  74859. * @param camera The camera to apply the render pass to.
  74860. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74861. * @param engine The engine which the post process will be applied. (default: current engine)
  74862. * @param reusable If the post process can be reused on the same frame. (default: false)
  74863. * @param textureType Type of textures used when performing the post process. (default: 0)
  74864. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74865. */
  74866. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74867. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74868. if (blockCompilation === void 0) { blockCompilation = false; }
  74869. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74870. /**
  74871. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74872. */
  74873. _this.colorAmount = 1.0;
  74874. /**
  74875. * How much sharpness should be applied (default: 0.3)
  74876. */
  74877. _this.edgeAmount = 0.3;
  74878. _this.onApply = function (effect) {
  74879. effect.setFloat2("screenSize", _this.width, _this.height);
  74880. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74881. };
  74882. return _this;
  74883. }
  74884. return SharpenPostProcess;
  74885. }(BABYLON.PostProcess));
  74886. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74887. })(BABYLON || (BABYLON = {}));
  74888. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74889. var BABYLON;
  74890. (function (BABYLON) {
  74891. /**
  74892. * The Blur Post Process which blurs an image based on a kernel and direction.
  74893. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74894. */
  74895. var BlurPostProcess = /** @class */ (function (_super) {
  74896. __extends(BlurPostProcess, _super);
  74897. /**
  74898. * Creates a new instance BlurPostProcess
  74899. * @param name The name of the effect.
  74900. * @param direction The direction in which to blur the image.
  74901. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  74902. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74903. * @param camera The camera to apply the render pass to.
  74904. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74905. * @param engine The engine which the post process will be applied. (default: current engine)
  74906. * @param reusable If the post process can be reused on the same frame. (default: false)
  74907. * @param textureType Type of textures used when performing the post process. (default: 0)
  74908. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74909. */
  74910. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74912. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74913. if (defines === void 0) { defines = ""; }
  74914. if (blockCompilation === void 0) { blockCompilation = false; }
  74915. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  74916. _this.direction = direction;
  74917. _this.blockCompilation = blockCompilation;
  74918. _this._packedFloat = false;
  74919. _this._staticDefines = "";
  74920. _this._staticDefines = defines;
  74921. _this.onApplyObservable.add(function (effect) {
  74922. if (_this._outputTexture) {
  74923. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74924. }
  74925. else {
  74926. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74927. }
  74928. });
  74929. _this.kernel = kernel;
  74930. return _this;
  74931. }
  74932. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74933. /**
  74934. * Gets the length in pixels of the blur sample region
  74935. */
  74936. get: function () {
  74937. return this._idealKernel;
  74938. },
  74939. /**
  74940. * Sets the length in pixels of the blur sample region
  74941. */
  74942. set: function (v) {
  74943. if (this._idealKernel === v) {
  74944. return;
  74945. }
  74946. v = Math.max(v, 1);
  74947. this._idealKernel = v;
  74948. this._kernel = this._nearestBestKernel(v);
  74949. if (!this.blockCompilation) {
  74950. this._updateParameters();
  74951. }
  74952. },
  74953. enumerable: true,
  74954. configurable: true
  74955. });
  74956. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74957. /**
  74958. * Gets wether or not the blur is unpacking/repacking floats
  74959. */
  74960. get: function () {
  74961. return this._packedFloat;
  74962. },
  74963. /**
  74964. * Sets wether or not the blur needs to unpack/repack floats
  74965. */
  74966. set: function (v) {
  74967. if (this._packedFloat === v) {
  74968. return;
  74969. }
  74970. this._packedFloat = v;
  74971. if (!this.blockCompilation) {
  74972. this._updateParameters();
  74973. }
  74974. },
  74975. enumerable: true,
  74976. configurable: true
  74977. });
  74978. /**
  74979. * Updates the effect with the current post process compile time values and recompiles the shader.
  74980. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74981. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74982. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74983. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  74984. * @param onCompiled Called when the shader has been compiled.
  74985. * @param onError Called if there is an error when compiling a shader.
  74986. */
  74987. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74988. if (defines === void 0) { defines = null; }
  74989. if (uniforms === void 0) { uniforms = null; }
  74990. if (samplers === void 0) { samplers = null; }
  74991. this._updateParameters(onCompiled, onError);
  74992. };
  74993. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74994. // Generate sampling offsets and weights
  74995. var N = this._kernel;
  74996. var centerIndex = (N - 1) / 2;
  74997. // Generate Gaussian sampling weights over kernel
  74998. var offsets = [];
  74999. var weights = [];
  75000. var totalWeight = 0;
  75001. for (var i = 0; i < N; i++) {
  75002. var u = i / (N - 1);
  75003. var w = this._gaussianWeight(u * 2.0 - 1);
  75004. offsets[i] = (i - centerIndex);
  75005. weights[i] = w;
  75006. totalWeight += w;
  75007. }
  75008. // Normalize weights
  75009. for (var i = 0; i < weights.length; i++) {
  75010. weights[i] /= totalWeight;
  75011. }
  75012. // Optimize: combine samples to take advantage of hardware linear sampling
  75013. // Walk from left to center, combining pairs (symmetrically)
  75014. var linearSamplingWeights = [];
  75015. var linearSamplingOffsets = [];
  75016. var linearSamplingMap = [];
  75017. for (var i = 0; i <= centerIndex; i += 2) {
  75018. var j = Math.min(i + 1, Math.floor(centerIndex));
  75019. var singleCenterSample = i === j;
  75020. if (singleCenterSample) {
  75021. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75022. }
  75023. else {
  75024. var sharedCell = j === centerIndex;
  75025. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75026. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75027. if (offsetLinear === 0) {
  75028. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75029. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75030. }
  75031. else {
  75032. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75033. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75034. }
  75035. }
  75036. }
  75037. for (var i = 0; i < linearSamplingMap.length; i++) {
  75038. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75039. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75040. }
  75041. // Replace with optimized
  75042. offsets = linearSamplingOffsets;
  75043. weights = linearSamplingWeights;
  75044. // Generate shaders
  75045. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75046. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75047. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75048. var defines = "";
  75049. defines += this._staticDefines;
  75050. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75051. if (this._staticDefines.indexOf("DOF") != -1) {
  75052. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75053. varyingCount--;
  75054. }
  75055. for (var i = 0; i < varyingCount; i++) {
  75056. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75057. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75058. }
  75059. var depCount = 0;
  75060. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75061. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75062. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75063. depCount++;
  75064. }
  75065. if (this.packedFloat) {
  75066. defines += "#define PACKEDFLOAT 1";
  75067. }
  75068. this.blockCompilation = false;
  75069. _super.prototype.updateEffect.call(this, defines, null, null, {
  75070. varyingCount: varyingCount,
  75071. depCount: depCount
  75072. }, onCompiled, onError);
  75073. };
  75074. /**
  75075. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75076. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75077. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75078. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75079. * The gaps between physical kernels are compensated for in the weighting of the samples
  75080. * @param idealKernel Ideal blur kernel.
  75081. * @return Nearest best kernel.
  75082. */
  75083. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75084. var v = Math.round(idealKernel);
  75085. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75086. var k = _a[_i];
  75087. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75088. return Math.max(k, 3);
  75089. }
  75090. }
  75091. return Math.max(v, 3);
  75092. };
  75093. /**
  75094. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75095. * @param x The point on the Gaussian distribution to sample.
  75096. * @return the value of the Gaussian function at x.
  75097. */
  75098. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75099. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75100. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75101. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75102. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75103. // truncated at around 1.3% of peak strength.
  75104. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75105. var sigma = (1 / 3);
  75106. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75107. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75108. var weight = (1.0 / denominator) * Math.exp(exponent);
  75109. return weight;
  75110. };
  75111. /**
  75112. * Generates a string that can be used as a floating point number in GLSL.
  75113. * @param x Value to print.
  75114. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75115. * @return GLSL float string.
  75116. */
  75117. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75118. if (decimalFigures === void 0) { decimalFigures = 8; }
  75119. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75120. };
  75121. return BlurPostProcess;
  75122. }(BABYLON.PostProcess));
  75123. BABYLON.BlurPostProcess = BlurPostProcess;
  75124. })(BABYLON || (BABYLON = {}));
  75125. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75126. var BABYLON;
  75127. (function (BABYLON) {
  75128. /**
  75129. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75130. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75131. * based on samples that have a large difference in distance than the center pixel.
  75132. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75133. */
  75134. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75135. __extends(DepthOfFieldBlurPostProcess, _super);
  75136. /**
  75137. * Creates a new instance CircleOfConfusionPostProcess
  75138. * @param name The name of the effect.
  75139. * @param scene The scene the effect belongs to.
  75140. * @param direction The direction the blur should be applied.
  75141. * @param kernel The size of the kernel used to blur.
  75142. * @param options The required width/height ratio to downsize to before computing the render pass.
  75143. * @param camera The camera to apply the render pass to.
  75144. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75145. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75146. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75147. * @param engine The engine which the post process will be applied. (default: current engine)
  75148. * @param reusable If the post process can be reused on the same frame. (default: false)
  75149. * @param textureType Type of textures used when performing the post process. (default: 0)
  75150. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75151. */
  75152. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75153. if (imageToBlur === void 0) { imageToBlur = null; }
  75154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75155. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75156. if (blockCompilation === void 0) { blockCompilation = false; }
  75157. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  75158. _this.direction = direction;
  75159. _this.onApplyObservable.add(function (effect) {
  75160. if (imageToBlur != null) {
  75161. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75162. }
  75163. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75164. if (scene.activeCamera) {
  75165. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75166. }
  75167. });
  75168. return _this;
  75169. }
  75170. return DepthOfFieldBlurPostProcess;
  75171. }(BABYLON.BlurPostProcess));
  75172. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75173. })(BABYLON || (BABYLON = {}));
  75174. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75175. var BABYLON;
  75176. (function (BABYLON) {
  75177. /**
  75178. * Options to be set when merging outputs from the default pipeline.
  75179. */
  75180. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75181. function DepthOfFieldMergePostProcessOptions() {
  75182. }
  75183. return DepthOfFieldMergePostProcessOptions;
  75184. }());
  75185. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75186. /**
  75187. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75188. */
  75189. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75190. __extends(DepthOfFieldMergePostProcess, _super);
  75191. /**
  75192. * Creates a new instance of DepthOfFieldMergePostProcess
  75193. * @param name The name of the effect.
  75194. * @param originalFromInput Post process which's input will be used for the merge.
  75195. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75196. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75197. * @param options The required width/height ratio to downsize to before computing the render pass.
  75198. * @param camera The camera to apply the render pass to.
  75199. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75200. * @param engine The engine which the post process will be applied. (default: current engine)
  75201. * @param reusable If the post process can be reused on the same frame. (default: false)
  75202. * @param textureType Type of textures used when performing the post process. (default: 0)
  75203. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75204. */
  75205. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75206. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75207. if (blockCompilation === void 0) { blockCompilation = false; }
  75208. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75209. _this.blurSteps = blurSteps;
  75210. _this.onApplyObservable.add(function (effect) {
  75211. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75212. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75213. blurSteps.forEach(function (step, index) {
  75214. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75215. });
  75216. });
  75217. if (!blockCompilation) {
  75218. _this.updateEffect();
  75219. }
  75220. return _this;
  75221. }
  75222. /**
  75223. * Updates the effect with the current post process compile time values and recompiles the shader.
  75224. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75225. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75226. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75227. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  75228. * @param onCompiled Called when the shader has been compiled.
  75229. * @param onError Called if there is an error when compiling a shader.
  75230. */
  75231. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75232. if (defines === void 0) { defines = null; }
  75233. if (uniforms === void 0) { uniforms = null; }
  75234. if (samplers === void 0) { samplers = null; }
  75235. if (!defines) {
  75236. defines = "";
  75237. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75238. }
  75239. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75240. };
  75241. return DepthOfFieldMergePostProcess;
  75242. }(BABYLON.PostProcess));
  75243. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75244. })(BABYLON || (BABYLON = {}));
  75245. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75246. var BABYLON;
  75247. (function (BABYLON) {
  75248. /**
  75249. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75250. */
  75251. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75252. __extends(CircleOfConfusionPostProcess, _super);
  75253. /**
  75254. * Creates a new instance CircleOfConfusionPostProcess
  75255. * @param name The name of the effect.
  75256. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  75257. * @param options The required width/height ratio to downsize to before computing the render pass.
  75258. * @param camera The camera to apply the render pass to.
  75259. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75260. * @param engine The engine which the post process will be applied. (default: current engine)
  75261. * @param reusable If the post process can be reused on the same frame. (default: false)
  75262. * @param textureType Type of textures used when performing the post process. (default: 0)
  75263. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75264. */
  75265. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75266. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75267. if (blockCompilation === void 0) { blockCompilation = false; }
  75268. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75269. /**
  75270. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  75271. */
  75272. _this.lensSize = 50;
  75273. /**
  75274. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75275. */
  75276. _this.fStop = 1.4;
  75277. /**
  75278. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75279. */
  75280. _this.focusDistance = 2000;
  75281. /**
  75282. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75283. */
  75284. _this.focalLength = 50;
  75285. _this._depthTexture = null;
  75286. _this._depthTexture = depthTexture;
  75287. _this.onApplyObservable.add(function (effect) {
  75288. if (!_this._depthTexture) {
  75289. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75290. return;
  75291. }
  75292. effect.setTexture("depthSampler", _this._depthTexture);
  75293. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75294. var aperture = _this.lensSize / _this.fStop;
  75295. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75296. effect.setFloat('focusDistance', _this.focusDistance);
  75297. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75298. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75299. });
  75300. return _this;
  75301. }
  75302. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75303. /**
  75304. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  75305. */
  75306. set: function (value) {
  75307. this._depthTexture = value;
  75308. },
  75309. enumerable: true,
  75310. configurable: true
  75311. });
  75312. return CircleOfConfusionPostProcess;
  75313. }(BABYLON.PostProcess));
  75314. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75315. })(BABYLON || (BABYLON = {}));
  75316. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75317. var BABYLON;
  75318. (function (BABYLON) {
  75319. /**
  75320. * Specifies the level of max blur that should be applied when using the depth of field effect
  75321. */
  75322. var DepthOfFieldEffectBlurLevel;
  75323. (function (DepthOfFieldEffectBlurLevel) {
  75324. /**
  75325. * Subtle blur
  75326. */
  75327. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75328. /**
  75329. * Medium blur
  75330. */
  75331. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75332. /**
  75333. * Large blur
  75334. */
  75335. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75336. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75337. ;
  75338. /**
  75339. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75340. */
  75341. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75342. __extends(DepthOfFieldEffect, _super);
  75343. /**
  75344. * Creates a new instance DepthOfFieldEffect
  75345. * @param scene The scene the effect belongs to.
  75346. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  75347. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75348. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75349. */
  75350. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75351. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75352. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75353. if (blockCompilation === void 0) { blockCompilation = false; }
  75354. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75355. return _this._effects;
  75356. }, true) || this;
  75357. /**
  75358. * Internal post processes in depth of field effect
  75359. */
  75360. _this._effects = [];
  75361. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75362. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75363. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  75364. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75365. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75366. _this._depthOfFieldBlurY = [];
  75367. _this._depthOfFieldBlurX = [];
  75368. var blurCount = 1;
  75369. var kernelSize = 15;
  75370. switch (blurLevel) {
  75371. case DepthOfFieldEffectBlurLevel.High: {
  75372. blurCount = 3;
  75373. kernelSize = 51;
  75374. break;
  75375. }
  75376. case DepthOfFieldEffectBlurLevel.Medium: {
  75377. blurCount = 2;
  75378. kernelSize = 31;
  75379. break;
  75380. }
  75381. default: {
  75382. kernelSize = 15;
  75383. blurCount = 1;
  75384. break;
  75385. }
  75386. }
  75387. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75388. var ratio = 1.0;
  75389. for (var i = 0; i < blurCount; i++) {
  75390. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75391. blurY.autoClear = false;
  75392. ratio = 0.75 / Math.pow(2, i);
  75393. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75394. blurX.autoClear = false;
  75395. _this._depthOfFieldBlurY.push(blurY);
  75396. _this._depthOfFieldBlurX.push(blurX);
  75397. }
  75398. // Set all post processes on the effect.
  75399. _this._effects = [_this._circleOfConfusion];
  75400. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75401. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75402. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75403. }
  75404. // Merge blurred images with original image based on circleOfConfusion
  75405. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75406. _this._dofMerge.autoClear = false;
  75407. _this._effects.push(_this._dofMerge);
  75408. return _this;
  75409. }
  75410. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75411. get: function () {
  75412. return this._circleOfConfusion.focalLength;
  75413. },
  75414. /**
  75415. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75416. */
  75417. set: function (value) {
  75418. this._circleOfConfusion.focalLength = value;
  75419. },
  75420. enumerable: true,
  75421. configurable: true
  75422. });
  75423. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75424. get: function () {
  75425. return this._circleOfConfusion.fStop;
  75426. },
  75427. /**
  75428. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75429. */
  75430. set: function (value) {
  75431. this._circleOfConfusion.fStop = value;
  75432. },
  75433. enumerable: true,
  75434. configurable: true
  75435. });
  75436. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75437. get: function () {
  75438. return this._circleOfConfusion.focusDistance;
  75439. },
  75440. /**
  75441. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75442. */
  75443. set: function (value) {
  75444. this._circleOfConfusion.focusDistance = value;
  75445. },
  75446. enumerable: true,
  75447. configurable: true
  75448. });
  75449. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75450. get: function () {
  75451. return this._circleOfConfusion.lensSize;
  75452. },
  75453. /**
  75454. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  75455. */
  75456. set: function (value) {
  75457. this._circleOfConfusion.lensSize = value;
  75458. },
  75459. enumerable: true,
  75460. configurable: true
  75461. });
  75462. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75463. /**
  75464. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  75465. */
  75466. set: function (value) {
  75467. this._circleOfConfusion.depthTexture = value;
  75468. },
  75469. enumerable: true,
  75470. configurable: true
  75471. });
  75472. /**
  75473. * Disposes each of the internal effects for a given camera.
  75474. * @param camera The camera to dispose the effect on.
  75475. */
  75476. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75477. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75478. this._effects[effectIndex].dispose(camera);
  75479. }
  75480. };
  75481. /**
  75482. * Internal
  75483. */
  75484. DepthOfFieldEffect.prototype._updateEffects = function () {
  75485. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75486. this._effects[effectIndex].updateEffect();
  75487. }
  75488. };
  75489. /**
  75490. * Internal
  75491. * @returns if all the contained post processes are ready.
  75492. */
  75493. DepthOfFieldEffect.prototype._isReady = function () {
  75494. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75495. if (!this._effects[effectIndex].isReady()) {
  75496. return false;
  75497. }
  75498. }
  75499. return true;
  75500. };
  75501. return DepthOfFieldEffect;
  75502. }(BABYLON.PostProcessRenderEffect));
  75503. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75504. })(BABYLON || (BABYLON = {}));
  75505. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75506. var BABYLON;
  75507. (function (BABYLON) {
  75508. /**
  75509. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75510. */
  75511. var BloomMergePostProcess = /** @class */ (function (_super) {
  75512. __extends(BloomMergePostProcess, _super);
  75513. /**
  75514. * Creates a new instance of @see BloomMergePostProcess
  75515. * @param name The name of the effect.
  75516. * @param originalFromInput Post process which's input will be used for the merge.
  75517. * @param blurred Blurred highlights post process which's output will be used.
  75518. * @param weight Weight of the bloom to be added to the original input.
  75519. * @param options The required width/height ratio to downsize to before computing the render pass.
  75520. * @param camera The camera to apply the render pass to.
  75521. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75522. * @param engine The engine which the post process will be applied. (default: current engine)
  75523. * @param reusable If the post process can be reused on the same frame. (default: false)
  75524. * @param textureType Type of textures used when performing the post process. (default: 0)
  75525. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75526. */
  75527. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75528. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75529. if (blockCompilation === void 0) { blockCompilation = false; }
  75530. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75531. _this.weight = weight;
  75532. _this.onApplyObservable.add(function (effect) {
  75533. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75534. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75535. effect.setFloat("bloomWeight", _this.weight);
  75536. });
  75537. if (!blockCompilation) {
  75538. _this.updateEffect();
  75539. }
  75540. return _this;
  75541. }
  75542. return BloomMergePostProcess;
  75543. }(BABYLON.PostProcess));
  75544. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75545. })(BABYLON || (BABYLON = {}));
  75546. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75547. var BABYLON;
  75548. (function (BABYLON) {
  75549. /**
  75550. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  75551. */
  75552. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75553. __extends(ExtractHighlightsPostProcess, _super);
  75554. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75555. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75556. if (blockCompilation === void 0) { blockCompilation = false; }
  75557. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75558. /**
  75559. * The luminance threshold, pixels below this value will be set to black.
  75560. */
  75561. _this.threshold = 0.9;
  75562. /**
  75563. * Internal
  75564. */
  75565. _this._exposure = 1;
  75566. /**
  75567. * Post process which has the input texture to be used when performing highlight extraction
  75568. */
  75569. _this._inputPostProcess = null;
  75570. _this.onApplyObservable.add(function (effect) {
  75571. if (_this._inputPostProcess) {
  75572. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75573. }
  75574. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75575. effect.setFloat('exposure', _this._exposure);
  75576. });
  75577. return _this;
  75578. }
  75579. return ExtractHighlightsPostProcess;
  75580. }(BABYLON.PostProcess));
  75581. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75582. })(BABYLON || (BABYLON = {}));
  75583. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75584. var BABYLON;
  75585. (function (BABYLON) {
  75586. /**
  75587. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75588. */
  75589. var BloomEffect = /** @class */ (function (_super) {
  75590. __extends(BloomEffect, _super);
  75591. /**
  75592. * Creates a new instance of @see BloomEffect
  75593. * @param scene The scene the effect belongs to.
  75594. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75595. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75596. * @param bloomWeight The the strength of bloom.
  75597. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75598. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75599. */
  75600. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75601. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75602. if (blockCompilation === void 0) { blockCompilation = false; }
  75603. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75604. return _this._effects;
  75605. }, true) || this;
  75606. _this.bloomScale = bloomScale;
  75607. /**
  75608. * Internal
  75609. */
  75610. _this._effects = [];
  75611. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75612. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75613. _this._blurX.alwaysForcePOT = true;
  75614. _this._blurX.autoClear = false;
  75615. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75616. _this._blurY.alwaysForcePOT = true;
  75617. _this._blurY.autoClear = false;
  75618. _this.kernel = bloomKernel;
  75619. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75620. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75621. _this._merge.autoClear = false;
  75622. _this._effects.push(_this._merge);
  75623. return _this;
  75624. }
  75625. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75626. /**
  75627. * The luminance threshold to find bright areas of the image to bloom.
  75628. */
  75629. get: function () {
  75630. return this._downscale.threshold;
  75631. },
  75632. set: function (value) {
  75633. this._downscale.threshold = value;
  75634. },
  75635. enumerable: true,
  75636. configurable: true
  75637. });
  75638. Object.defineProperty(BloomEffect.prototype, "weight", {
  75639. /**
  75640. * The strength of the bloom.
  75641. */
  75642. get: function () {
  75643. return this._merge.weight;
  75644. },
  75645. set: function (value) {
  75646. this._merge.weight = value;
  75647. },
  75648. enumerable: true,
  75649. configurable: true
  75650. });
  75651. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75652. /**
  75653. * Specifies the size of the bloom blur kernel, relative to the final output size
  75654. */
  75655. get: function () {
  75656. return this._blurX.kernel / this.bloomScale;
  75657. },
  75658. set: function (value) {
  75659. this._blurX.kernel = value * this.bloomScale;
  75660. this._blurY.kernel = value * this.bloomScale;
  75661. },
  75662. enumerable: true,
  75663. configurable: true
  75664. });
  75665. /**
  75666. * Disposes each of the internal effects for a given camera.
  75667. * @param camera The camera to dispose the effect on.
  75668. */
  75669. BloomEffect.prototype.disposeEffects = function (camera) {
  75670. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75671. this._effects[effectIndex].dispose(camera);
  75672. }
  75673. };
  75674. /**
  75675. * Internal
  75676. */
  75677. BloomEffect.prototype._updateEffects = function () {
  75678. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75679. this._effects[effectIndex].updateEffect();
  75680. }
  75681. };
  75682. /**
  75683. * Internal
  75684. * @returns if all the contained post processes are ready.
  75685. */
  75686. BloomEffect.prototype._isReady = function () {
  75687. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75688. if (!this._effects[effectIndex].isReady()) {
  75689. return false;
  75690. }
  75691. }
  75692. return true;
  75693. };
  75694. return BloomEffect;
  75695. }(BABYLON.PostProcessRenderEffect));
  75696. BABYLON.BloomEffect = BloomEffect;
  75697. })(BABYLON || (BABYLON = {}));
  75698. //# sourceMappingURL=babylon.bloomEffect.js.map
  75699. var BABYLON;
  75700. (function (BABYLON) {
  75701. /**
  75702. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75703. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75704. */
  75705. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75706. __extends(DefaultRenderingPipeline, _super);
  75707. /**
  75708. * @constructor
  75709. * @param {string} name - The rendering pipeline name (default: "")
  75710. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75711. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75712. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75713. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75714. */
  75715. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75716. if (name === void 0) { name = ""; }
  75717. if (hdr === void 0) { hdr = true; }
  75718. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75719. if (automaticBuild === void 0) { automaticBuild = true; }
  75720. var _this = _super.call(this, scene.getEngine(), name) || this;
  75721. _this._originalCameras = [];
  75722. /**
  75723. * ID of the sharpen post process,
  75724. */
  75725. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75726. /**
  75727. * ID of the image processing post process;
  75728. */
  75729. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75730. /**
  75731. * ID of the Fast Approximate Anti-Aliasing post process;
  75732. */
  75733. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75734. /**
  75735. * ID of the chromatic aberration post process,
  75736. */
  75737. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75738. /**
  75739. * ID of the grain post process
  75740. */
  75741. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75742. /**
  75743. * Glow post process which adds a glow to emmisive areas of the image
  75744. */
  75745. _this._glowLayer = null;
  75746. /**
  75747. * Animations which can be used to tweak settings over a period of time
  75748. */
  75749. _this.animations = [];
  75750. _this._imageProcessingConfigurationObserver = null;
  75751. // Values
  75752. _this._sharpenEnabled = false;
  75753. _this._bloomEnabled = false;
  75754. _this._depthOfFieldEnabled = false;
  75755. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75756. _this._fxaaEnabled = false;
  75757. _this._imageProcessingEnabled = true;
  75758. _this._bloomScale = 0.5;
  75759. _this._chromaticAberrationEnabled = false;
  75760. _this._grainEnabled = false;
  75761. _this._buildAllowed = true;
  75762. _this._resizeObserver = null;
  75763. _this._hardwareScaleLevel = 1.0;
  75764. _this._bloomKernel = 64;
  75765. /**
  75766. * Specifies the weight of the bloom in the final rendering
  75767. */
  75768. _this._bloomWeight = 0.15;
  75769. /**
  75770. * Specifies the luma threshold for the area that will be blurred by the bloom
  75771. */
  75772. _this._bloomThreshold = 0.9;
  75773. _this._samples = 1;
  75774. _this._hasCleared = false;
  75775. _this._prevPostProcess = null;
  75776. _this._prevPrevPostProcess = null;
  75777. _this._cameras = cameras || scene.cameras;
  75778. _this._originalCameras = _this._cameras.slice();
  75779. _this._buildAllowed = automaticBuild;
  75780. // Initialize
  75781. _this._scene = scene;
  75782. var caps = _this._scene.getEngine().getCaps();
  75783. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75784. // Misc
  75785. if (_this._hdr) {
  75786. if (caps.textureHalfFloatRender) {
  75787. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75788. }
  75789. else if (caps.textureFloatRender) {
  75790. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75791. }
  75792. }
  75793. else {
  75794. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75795. }
  75796. // Attach
  75797. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75798. var engine = _this._scene.getEngine();
  75799. // Create post processes before hand so they can be modified before enabled.
  75800. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75801. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75802. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75803. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75804. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75805. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75806. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75807. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75808. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75809. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75810. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75811. _this.bloomKernel = _this.bloomKernel;
  75812. });
  75813. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75814. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75815. });
  75816. _this._buildPipeline();
  75817. return _this;
  75818. }
  75819. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75820. get: function () {
  75821. return this._sharpenEnabled;
  75822. },
  75823. /**
  75824. * Enable or disable the sharpen process from the pipeline
  75825. */
  75826. set: function (enabled) {
  75827. if (this._sharpenEnabled === enabled) {
  75828. return;
  75829. }
  75830. this._sharpenEnabled = enabled;
  75831. this._buildPipeline();
  75832. },
  75833. enumerable: true,
  75834. configurable: true
  75835. });
  75836. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75837. /**
  75838. * Specifies the size of the bloom blur kernel, relative to the final output size
  75839. */
  75840. get: function () {
  75841. return this._bloomKernel;
  75842. },
  75843. set: function (value) {
  75844. this._bloomKernel = value;
  75845. this.bloom.kernel = value / this._hardwareScaleLevel;
  75846. },
  75847. enumerable: true,
  75848. configurable: true
  75849. });
  75850. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75851. get: function () {
  75852. return this._bloomWeight;
  75853. },
  75854. /**
  75855. * The strength of the bloom.
  75856. */
  75857. set: function (value) {
  75858. if (this._bloomWeight === value) {
  75859. return;
  75860. }
  75861. this.bloom.weight = value;
  75862. this._bloomWeight = value;
  75863. },
  75864. enumerable: true,
  75865. configurable: true
  75866. });
  75867. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75868. get: function () {
  75869. return this._bloomThreshold;
  75870. },
  75871. /**
  75872. * The strength of the bloom.
  75873. */
  75874. set: function (value) {
  75875. if (this._bloomThreshold === value) {
  75876. return;
  75877. }
  75878. this.bloom.threshold = value;
  75879. this._bloomThreshold = value;
  75880. },
  75881. enumerable: true,
  75882. configurable: true
  75883. });
  75884. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75885. get: function () {
  75886. return this._bloomScale;
  75887. },
  75888. /**
  75889. * The scale of the bloom, lower value will provide better performance.
  75890. */
  75891. set: function (value) {
  75892. if (this._bloomScale === value) {
  75893. return;
  75894. }
  75895. this._bloomScale = value;
  75896. // recreate bloom and dispose old as this setting is not dynamic
  75897. this._rebuildBloom();
  75898. this._buildPipeline();
  75899. },
  75900. enumerable: true,
  75901. configurable: true
  75902. });
  75903. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75904. get: function () {
  75905. return this._bloomEnabled;
  75906. },
  75907. /**
  75908. * Enable or disable the bloom from the pipeline
  75909. */
  75910. set: function (enabled) {
  75911. if (this._bloomEnabled === enabled) {
  75912. return;
  75913. }
  75914. this._bloomEnabled = enabled;
  75915. this._buildPipeline();
  75916. },
  75917. enumerable: true,
  75918. configurable: true
  75919. });
  75920. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75921. // recreate bloom and dispose old as this setting is not dynamic
  75922. var oldBloom = this.bloom;
  75923. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75924. this.bloom.threshold = oldBloom.threshold;
  75925. for (var i = 0; i < this._cameras.length; i++) {
  75926. oldBloom.disposeEffects(this._cameras[i]);
  75927. }
  75928. };
  75929. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75930. /**
  75931. * If the depth of field is enabled.
  75932. */
  75933. get: function () {
  75934. return this._depthOfFieldEnabled;
  75935. },
  75936. set: function (enabled) {
  75937. if (this._depthOfFieldEnabled === enabled) {
  75938. return;
  75939. }
  75940. this._depthOfFieldEnabled = enabled;
  75941. this._buildPipeline();
  75942. },
  75943. enumerable: true,
  75944. configurable: true
  75945. });
  75946. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75947. /**
  75948. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75949. */
  75950. get: function () {
  75951. return this._depthOfFieldBlurLevel;
  75952. },
  75953. set: function (value) {
  75954. if (this._depthOfFieldBlurLevel === value) {
  75955. return;
  75956. }
  75957. this._depthOfFieldBlurLevel = value;
  75958. // recreate dof and dispose old as this setting is not dynamic
  75959. var oldDof = this.depthOfField;
  75960. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75961. this.depthOfField.focalLength = oldDof.focalLength;
  75962. this.depthOfField.focusDistance = oldDof.focusDistance;
  75963. this.depthOfField.fStop = oldDof.fStop;
  75964. this.depthOfField.lensSize = oldDof.lensSize;
  75965. for (var i = 0; i < this._cameras.length; i++) {
  75966. oldDof.disposeEffects(this._cameras[i]);
  75967. }
  75968. this._buildPipeline();
  75969. },
  75970. enumerable: true,
  75971. configurable: true
  75972. });
  75973. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75974. get: function () {
  75975. return this._fxaaEnabled;
  75976. },
  75977. /**
  75978. * If the anti aliasing is enabled.
  75979. */
  75980. set: function (enabled) {
  75981. if (this._fxaaEnabled === enabled) {
  75982. return;
  75983. }
  75984. this._fxaaEnabled = enabled;
  75985. this._buildPipeline();
  75986. },
  75987. enumerable: true,
  75988. configurable: true
  75989. });
  75990. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75991. get: function () {
  75992. return this._samples;
  75993. },
  75994. /**
  75995. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75996. */
  75997. set: function (sampleCount) {
  75998. if (this._samples === sampleCount) {
  75999. return;
  76000. }
  76001. this._samples = sampleCount;
  76002. this._buildPipeline();
  76003. },
  76004. enumerable: true,
  76005. configurable: true
  76006. });
  76007. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76008. get: function () {
  76009. return this._imageProcessingEnabled;
  76010. },
  76011. /**
  76012. * If image processing is enabled.
  76013. */
  76014. set: function (enabled) {
  76015. if (this._imageProcessingEnabled === enabled) {
  76016. return;
  76017. }
  76018. this._imageProcessingEnabled = enabled;
  76019. this._buildPipeline();
  76020. },
  76021. enumerable: true,
  76022. configurable: true
  76023. });
  76024. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76025. get: function () {
  76026. return this._glowLayer == null;
  76027. },
  76028. /**
  76029. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76030. */
  76031. set: function (enabled) {
  76032. if (enabled && !this._glowLayer) {
  76033. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76034. }
  76035. else if (!enabled && this._glowLayer) {
  76036. this._glowLayer.dispose();
  76037. this._glowLayer = null;
  76038. }
  76039. },
  76040. enumerable: true,
  76041. configurable: true
  76042. });
  76043. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76044. get: function () {
  76045. return this._chromaticAberrationEnabled;
  76046. },
  76047. /**
  76048. * Enable or disable the chromaticAberration process from the pipeline
  76049. */
  76050. set: function (enabled) {
  76051. if (this._chromaticAberrationEnabled === enabled) {
  76052. return;
  76053. }
  76054. this._chromaticAberrationEnabled = enabled;
  76055. this._buildPipeline();
  76056. },
  76057. enumerable: true,
  76058. configurable: true
  76059. });
  76060. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76061. get: function () {
  76062. return this._grainEnabled;
  76063. },
  76064. /**
  76065. * Enable or disable the grain process from the pipeline
  76066. */
  76067. set: function (enabled) {
  76068. if (this._grainEnabled === enabled) {
  76069. return;
  76070. }
  76071. this._grainEnabled = enabled;
  76072. this._buildPipeline();
  76073. },
  76074. enumerable: true,
  76075. configurable: true
  76076. });
  76077. /**
  76078. * Force the compilation of the entire pipeline.
  76079. */
  76080. DefaultRenderingPipeline.prototype.prepare = function () {
  76081. var previousState = this._buildAllowed;
  76082. this._buildAllowed = true;
  76083. this._buildPipeline();
  76084. this._buildAllowed = previousState;
  76085. };
  76086. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76087. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76088. if (this._hasCleared) {
  76089. postProcess.autoClear = false;
  76090. }
  76091. else {
  76092. postProcess.autoClear = true;
  76093. this._scene.autoClear = false;
  76094. this._hasCleared = true;
  76095. }
  76096. if (!skipTextureSharing) {
  76097. if (this._prevPrevPostProcess) {
  76098. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76099. }
  76100. else {
  76101. postProcess.useOwnOutput();
  76102. }
  76103. if (this._prevPostProcess) {
  76104. this._prevPrevPostProcess = this._prevPostProcess;
  76105. }
  76106. this._prevPostProcess = postProcess;
  76107. }
  76108. };
  76109. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76110. var _this = this;
  76111. if (!this._buildAllowed) {
  76112. return;
  76113. }
  76114. this._scene.autoClear = true;
  76115. var engine = this._scene.getEngine();
  76116. this._disposePostProcesses();
  76117. if (this._cameras !== null) {
  76118. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76119. // get back cameras to be used to reattach pipeline
  76120. this._cameras = this._originalCameras.slice();
  76121. }
  76122. this._reset();
  76123. this._prevPostProcess = null;
  76124. this._prevPrevPostProcess = null;
  76125. this._hasCleared = false;
  76126. if (this.depthOfFieldEnabled) {
  76127. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76128. this.depthOfField.depthTexture = depthTexture;
  76129. if (!this.depthOfField._isReady()) {
  76130. this.depthOfField._updateEffects();
  76131. }
  76132. this.addEffect(this.depthOfField);
  76133. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76134. }
  76135. if (this.bloomEnabled) {
  76136. if (!this.bloom._isReady()) {
  76137. this.bloom._updateEffects();
  76138. }
  76139. this.addEffect(this.bloom);
  76140. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76141. }
  76142. if (this._imageProcessingEnabled) {
  76143. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76144. if (this._hdr) {
  76145. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76146. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76147. }
  76148. else {
  76149. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76150. }
  76151. }
  76152. if (this.sharpenEnabled) {
  76153. if (!this.sharpen.isReady()) {
  76154. this.sharpen.updateEffect();
  76155. }
  76156. this.addEffect(this._sharpenEffect);
  76157. this._setAutoClearAndTextureSharing(this.sharpen);
  76158. }
  76159. if (this.grainEnabled) {
  76160. if (!this.grain.isReady()) {
  76161. this.grain.updateEffect();
  76162. }
  76163. this.addEffect(this._grainEffect);
  76164. this._setAutoClearAndTextureSharing(this.grain);
  76165. }
  76166. if (this.chromaticAberrationEnabled) {
  76167. if (!this.chromaticAberration.isReady()) {
  76168. this.chromaticAberration.updateEffect();
  76169. }
  76170. this.addEffect(this._chromaticAberrationEffect);
  76171. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76172. }
  76173. if (this.fxaaEnabled) {
  76174. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76175. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76176. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76177. }
  76178. if (this._cameras !== null) {
  76179. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76180. }
  76181. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76182. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76183. }
  76184. };
  76185. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76186. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76187. for (var i = 0; i < this._cameras.length; i++) {
  76188. var camera = this._cameras[i];
  76189. if (this.imageProcessing) {
  76190. this.imageProcessing.dispose(camera);
  76191. }
  76192. if (this.fxaa) {
  76193. this.fxaa.dispose(camera);
  76194. }
  76195. // These are created in the constructor and should not be disposed on every pipeline change
  76196. if (disposeNonRecreated) {
  76197. if (this.sharpen) {
  76198. this.sharpen.dispose(camera);
  76199. }
  76200. if (this.depthOfField) {
  76201. this.depthOfField.disposeEffects(camera);
  76202. }
  76203. if (this.bloom) {
  76204. this.bloom.disposeEffects(camera);
  76205. }
  76206. if (this.chromaticAberration) {
  76207. this.chromaticAberration.dispose(camera);
  76208. }
  76209. if (this.grain) {
  76210. this.grain.dispose(camera);
  76211. }
  76212. if (this._glowLayer) {
  76213. this._glowLayer.dispose();
  76214. }
  76215. }
  76216. }
  76217. this.imageProcessing = null;
  76218. this.fxaa = null;
  76219. if (disposeNonRecreated) {
  76220. this.sharpen = null;
  76221. this._sharpenEffect = null;
  76222. this.depthOfField = null;
  76223. this.bloom = null;
  76224. this.chromaticAberration = null;
  76225. this._chromaticAberrationEffect = null;
  76226. this.grain = null;
  76227. this._grainEffect = null;
  76228. this._glowLayer = null;
  76229. }
  76230. };
  76231. /**
  76232. * Dispose of the pipeline and stop all post processes
  76233. */
  76234. DefaultRenderingPipeline.prototype.dispose = function () {
  76235. this._disposePostProcesses(true);
  76236. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76237. this._scene.autoClear = true;
  76238. if (this._resizeObserver) {
  76239. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76240. this._resizeObserver = null;
  76241. }
  76242. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76243. _super.prototype.dispose.call(this);
  76244. };
  76245. /**
  76246. * Serialize the rendering pipeline (Used when exporting)
  76247. * @returns the serialized object
  76248. */
  76249. DefaultRenderingPipeline.prototype.serialize = function () {
  76250. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76251. serializationObject.customType = "DefaultRenderingPipeline";
  76252. return serializationObject;
  76253. };
  76254. /**
  76255. * Parse the serialized pipeline
  76256. * @param source Source pipeline.
  76257. * @param scene The scene to load the pipeline to.
  76258. * @param rootUrl The URL of the serialized pipeline.
  76259. * @returns An instantiated pipeline from the serialized object.
  76260. */
  76261. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76262. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76263. };
  76264. __decorate([
  76265. BABYLON.serialize()
  76266. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76267. __decorate([
  76268. BABYLON.serialize()
  76269. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76270. __decorate([
  76271. BABYLON.serialize()
  76272. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76273. __decorate([
  76274. BABYLON.serialize()
  76275. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76276. __decorate([
  76277. BABYLON.serialize()
  76278. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76279. __decorate([
  76280. BABYLON.serialize()
  76281. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76282. __decorate([
  76283. BABYLON.serialize()
  76284. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76285. __decorate([
  76286. BABYLON.serialize()
  76287. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76288. __decorate([
  76289. BABYLON.serialize()
  76290. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76291. __decorate([
  76292. BABYLON.serialize()
  76293. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76294. __decorate([
  76295. BABYLON.serialize()
  76296. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76297. __decorate([
  76298. BABYLON.serialize()
  76299. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76300. __decorate([
  76301. BABYLON.serialize()
  76302. ], DefaultRenderingPipeline.prototype, "samples", null);
  76303. __decorate([
  76304. BABYLON.serialize()
  76305. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76306. __decorate([
  76307. BABYLON.serialize()
  76308. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76309. __decorate([
  76310. BABYLON.serialize()
  76311. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76312. __decorate([
  76313. BABYLON.serialize()
  76314. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76315. return DefaultRenderingPipeline;
  76316. }(BABYLON.PostProcessRenderPipeline));
  76317. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76318. })(BABYLON || (BABYLON = {}));
  76319. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76320. var BABYLON;
  76321. (function (BABYLON) {
  76322. /**
  76323. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76324. */
  76325. var GeometryBufferRenderer = /** @class */ (function () {
  76326. /**
  76327. * Creates a new G Buffer for the scene
  76328. * @param scene The scene the buffer belongs to
  76329. * @param ratio How big is the buffer related to the main canvas.
  76330. */
  76331. function GeometryBufferRenderer(scene, ratio) {
  76332. if (ratio === void 0) { ratio = 1; }
  76333. this._enablePosition = false;
  76334. this._scene = scene;
  76335. this._ratio = ratio;
  76336. // Render target
  76337. this._createRenderTargets();
  76338. }
  76339. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76340. /**
  76341. * Set the render list (meshes to be rendered) used in the G buffer.
  76342. */
  76343. set: function (meshes) {
  76344. this._multiRenderTarget.renderList = meshes;
  76345. },
  76346. enumerable: true,
  76347. configurable: true
  76348. });
  76349. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76350. /**
  76351. * Gets wether or not G buffer are supported by the running hardware.
  76352. * This requires draw buffer supports
  76353. */
  76354. get: function () {
  76355. return this._multiRenderTarget.isSupported;
  76356. },
  76357. enumerable: true,
  76358. configurable: true
  76359. });
  76360. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76361. /**
  76362. * Gets wether or not position are enabled for the G buffer.
  76363. */
  76364. get: function () {
  76365. return this._enablePosition;
  76366. },
  76367. /**
  76368. * Sets wether or not position are enabled for the G buffer.
  76369. */
  76370. set: function (enable) {
  76371. this._enablePosition = enable;
  76372. this.dispose();
  76373. this._createRenderTargets();
  76374. },
  76375. enumerable: true,
  76376. configurable: true
  76377. });
  76378. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76379. /**
  76380. * Gets the scene associated with the buffer.
  76381. */
  76382. get: function () {
  76383. return this._scene;
  76384. },
  76385. enumerable: true,
  76386. configurable: true
  76387. });
  76388. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76389. /**
  76390. * Gets the ratio used by the buffer during its creation.
  76391. * How big is the buffer related to the main canvas.
  76392. */
  76393. get: function () {
  76394. return this._ratio;
  76395. },
  76396. enumerable: true,
  76397. configurable: true
  76398. });
  76399. /**
  76400. * Checks wether everything is ready to render a submesh to the G buffer.
  76401. * @param subMesh the submesh to check readiness for
  76402. * @param useInstances is the mesh drawn using instance or not
  76403. * @returns true if ready otherwise false
  76404. */
  76405. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76406. var material = subMesh.getMaterial();
  76407. if (material && material.disableDepthWrite) {
  76408. return false;
  76409. }
  76410. var defines = [];
  76411. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76412. var mesh = subMesh.getMesh();
  76413. // Alpha test
  76414. if (material && material.needAlphaTesting()) {
  76415. defines.push("#define ALPHATEST");
  76416. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76417. attribs.push(BABYLON.VertexBuffer.UVKind);
  76418. defines.push("#define UV1");
  76419. }
  76420. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76421. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76422. defines.push("#define UV2");
  76423. }
  76424. }
  76425. // Buffers
  76426. if (this._enablePosition) {
  76427. defines.push("#define POSITION");
  76428. }
  76429. // Bones
  76430. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76431. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76432. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76433. if (mesh.numBoneInfluencers > 4) {
  76434. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76435. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76436. }
  76437. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76438. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76439. }
  76440. else {
  76441. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76442. }
  76443. // Instances
  76444. if (useInstances) {
  76445. defines.push("#define INSTANCES");
  76446. attribs.push("world0");
  76447. attribs.push("world1");
  76448. attribs.push("world2");
  76449. attribs.push("world3");
  76450. }
  76451. // Get correct effect
  76452. var join = defines.join("\n");
  76453. if (this._cachedDefines !== join) {
  76454. this._cachedDefines = join;
  76455. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76456. }
  76457. return this._effect.isReady();
  76458. };
  76459. /**
  76460. * Gets the current underlying G Buffer.
  76461. * @returns the buffer
  76462. */
  76463. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76464. return this._multiRenderTarget;
  76465. };
  76466. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76467. /**
  76468. * Gets the number of samples used to render the buffer (anti aliasing).
  76469. */
  76470. get: function () {
  76471. return this._multiRenderTarget.samples;
  76472. },
  76473. /**
  76474. * Sets the number of samples used to render the buffer (anti aliasing).
  76475. */
  76476. set: function (value) {
  76477. this._multiRenderTarget.samples = value;
  76478. },
  76479. enumerable: true,
  76480. configurable: true
  76481. });
  76482. /**
  76483. * Disposes the renderer and frees up associated resources.
  76484. */
  76485. GeometryBufferRenderer.prototype.dispose = function () {
  76486. this.getGBuffer().dispose();
  76487. };
  76488. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76489. var _this = this;
  76490. var engine = this._scene.getEngine();
  76491. var count = this._enablePosition ? 3 : 2;
  76492. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  76493. if (!this.isSupported) {
  76494. return;
  76495. }
  76496. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76497. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76498. this._multiRenderTarget.refreshRate = 1;
  76499. this._multiRenderTarget.renderParticles = false;
  76500. this._multiRenderTarget.renderList = null;
  76501. // set default depth value to 1.0 (far away)
  76502. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76503. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76504. });
  76505. // Custom render function
  76506. var renderSubMesh = function (subMesh) {
  76507. var mesh = subMesh.getRenderingMesh();
  76508. var scene = _this._scene;
  76509. var engine = scene.getEngine();
  76510. var material = subMesh.getMaterial();
  76511. if (!material) {
  76512. return;
  76513. }
  76514. // Culling
  76515. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76516. // Managing instances
  76517. var batch = mesh._getInstancesRenderList(subMesh._id);
  76518. if (batch.mustReturn) {
  76519. return;
  76520. }
  76521. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76522. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76523. engine.enableEffect(_this._effect);
  76524. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76525. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76526. _this._effect.setMatrix("view", scene.getViewMatrix());
  76527. // Alpha test
  76528. if (material && material.needAlphaTesting()) {
  76529. var alphaTexture = material.getAlphaTestTexture();
  76530. if (alphaTexture) {
  76531. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76532. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76533. }
  76534. }
  76535. // Bones
  76536. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76537. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76538. }
  76539. // Draw
  76540. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76541. }
  76542. };
  76543. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76544. var index;
  76545. if (depthOnlySubMeshes.length) {
  76546. engine.setColorWrite(false);
  76547. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76548. renderSubMesh(depthOnlySubMeshes.data[index]);
  76549. }
  76550. engine.setColorWrite(true);
  76551. }
  76552. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76553. renderSubMesh(opaqueSubMeshes.data[index]);
  76554. }
  76555. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76556. renderSubMesh(alphaTestSubMeshes.data[index]);
  76557. }
  76558. };
  76559. };
  76560. return GeometryBufferRenderer;
  76561. }());
  76562. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76563. })(BABYLON || (BABYLON = {}));
  76564. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76565. var BABYLON;
  76566. (function (BABYLON) {
  76567. var RefractionPostProcess = /** @class */ (function (_super) {
  76568. __extends(RefractionPostProcess, _super);
  76569. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76570. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76571. _this.color = color;
  76572. _this.depth = depth;
  76573. _this.colorLevel = colorLevel;
  76574. _this._ownRefractionTexture = true;
  76575. _this.onActivateObservable.add(function (cam) {
  76576. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76577. });
  76578. _this.onApplyObservable.add(function (effect) {
  76579. effect.setColor3("baseColor", _this.color);
  76580. effect.setFloat("depth", _this.depth);
  76581. effect.setFloat("colorLevel", _this.colorLevel);
  76582. effect.setTexture("refractionSampler", _this._refTexture);
  76583. });
  76584. return _this;
  76585. }
  76586. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76587. /**
  76588. * Gets or sets the refraction texture
  76589. * Please note that you are responsible for disposing the texture if you set it manually
  76590. */
  76591. get: function () {
  76592. return this._refTexture;
  76593. },
  76594. set: function (value) {
  76595. if (this._refTexture && this._ownRefractionTexture) {
  76596. this._refTexture.dispose();
  76597. }
  76598. this._refTexture = value;
  76599. this._ownRefractionTexture = false;
  76600. },
  76601. enumerable: true,
  76602. configurable: true
  76603. });
  76604. // Methods
  76605. RefractionPostProcess.prototype.dispose = function (camera) {
  76606. if (this._refTexture && this._ownRefractionTexture) {
  76607. this._refTexture.dispose();
  76608. this._refTexture = null;
  76609. }
  76610. _super.prototype.dispose.call(this, camera);
  76611. };
  76612. return RefractionPostProcess;
  76613. }(BABYLON.PostProcess));
  76614. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76615. })(BABYLON || (BABYLON = {}));
  76616. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76617. var BABYLON;
  76618. (function (BABYLON) {
  76619. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76620. __extends(BlackAndWhitePostProcess, _super);
  76621. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76622. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76623. _this.degree = 1;
  76624. _this.onApplyObservable.add(function (effect) {
  76625. effect.setFloat("degree", _this.degree);
  76626. });
  76627. return _this;
  76628. }
  76629. return BlackAndWhitePostProcess;
  76630. }(BABYLON.PostProcess));
  76631. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76632. })(BABYLON || (BABYLON = {}));
  76633. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76634. var BABYLON;
  76635. (function (BABYLON) {
  76636. /**
  76637. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76638. * input texture to perform effects such as edge detection or sharpening
  76639. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76640. */
  76641. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76642. __extends(ConvolutionPostProcess, _super);
  76643. /**
  76644. * Creates a new instance ConvolutionPostProcess
  76645. * @param name The name of the effect.
  76646. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76647. * @param options The required width/height ratio to downsize to before computing the render pass.
  76648. * @param camera The camera to apply the render pass to.
  76649. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76650. * @param engine The engine which the post process will be applied. (default: current engine)
  76651. * @param reusable If the post process can be reused on the same frame. (default: false)
  76652. * @param textureType Type of textures used when performing the post process. (default: 0)
  76653. */
  76654. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76655. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76656. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76657. _this.kernel = kernel;
  76658. _this.onApply = function (effect) {
  76659. effect.setFloat2("screenSize", _this.width, _this.height);
  76660. effect.setArray("kernel", _this.kernel);
  76661. };
  76662. return _this;
  76663. }
  76664. // Statics
  76665. /**
  76666. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76667. */
  76668. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76669. /**
  76670. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76671. */
  76672. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76673. /**
  76674. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76675. */
  76676. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76677. /**
  76678. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76679. */
  76680. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76681. /**
  76682. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76683. */
  76684. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76685. /**
  76686. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76687. */
  76688. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76689. return ConvolutionPostProcess;
  76690. }(BABYLON.PostProcess));
  76691. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76692. })(BABYLON || (BABYLON = {}));
  76693. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76694. var BABYLON;
  76695. (function (BABYLON) {
  76696. var FilterPostProcess = /** @class */ (function (_super) {
  76697. __extends(FilterPostProcess, _super);
  76698. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76699. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76700. _this.kernelMatrix = kernelMatrix;
  76701. _this.onApply = function (effect) {
  76702. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76703. };
  76704. return _this;
  76705. }
  76706. return FilterPostProcess;
  76707. }(BABYLON.PostProcess));
  76708. BABYLON.FilterPostProcess = FilterPostProcess;
  76709. })(BABYLON || (BABYLON = {}));
  76710. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76711. var BABYLON;
  76712. (function (BABYLON) {
  76713. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76714. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76715. __extends(VolumetricLightScatteringPostProcess, _super);
  76716. /**
  76717. * @constructor
  76718. * @param {string} name - The post-process name
  76719. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  76720. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76721. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76722. * @param {number} samples - The post-process quality, default 100
  76723. * @param {number} samplingMode - The post-process filtering mode
  76724. * @param {BABYLON.Engine} engine - The babylon engine
  76725. * @param {boolean} reusable - If the post-process is reusable
  76726. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76727. */
  76728. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76729. if (samples === void 0) { samples = 100; }
  76730. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76731. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  76732. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76733. /**
  76734. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76735. */
  76736. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76737. /**
  76738. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76739. */
  76740. _this.useCustomMeshPosition = false;
  76741. /**
  76742. * If the post-process should inverse the light scattering direction
  76743. */
  76744. _this.invert = true;
  76745. /**
  76746. * Array containing the excluded meshes not rendered in the internal pass
  76747. */
  76748. _this.excludedMeshes = new Array();
  76749. /**
  76750. * Controls the overall intensity of the post-process
  76751. */
  76752. _this.exposure = 0.3;
  76753. /**
  76754. * Dissipates each sample's contribution in range [0, 1]
  76755. */
  76756. _this.decay = 0.96815;
  76757. /**
  76758. * Controls the overall intensity of each sample
  76759. */
  76760. _this.weight = 0.58767;
  76761. /**
  76762. * Controls the density of each sample
  76763. */
  76764. _this.density = 0.926;
  76765. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76766. engine = scene.getEngine();
  76767. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76768. // Configure mesh
  76769. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76770. // Configure
  76771. _this._createPass(scene, ratio.passRatio || ratio);
  76772. _this.onActivate = function (camera) {
  76773. if (!_this.isSupported) {
  76774. _this.dispose(camera);
  76775. }
  76776. _this.onActivate = null;
  76777. };
  76778. _this.onApplyObservable.add(function (effect) {
  76779. _this._updateMeshScreenCoordinates(scene);
  76780. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76781. effect.setFloat("exposure", _this.exposure);
  76782. effect.setFloat("decay", _this.decay);
  76783. effect.setFloat("weight", _this.weight);
  76784. effect.setFloat("density", _this.density);
  76785. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76786. });
  76787. return _this;
  76788. }
  76789. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76790. get: function () {
  76791. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76792. return false;
  76793. },
  76794. set: function (useDiffuseColor) {
  76795. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76796. },
  76797. enumerable: true,
  76798. configurable: true
  76799. });
  76800. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76801. return "VolumetricLightScatteringPostProcess";
  76802. };
  76803. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76804. var mesh = subMesh.getMesh();
  76805. // Render this.mesh as default
  76806. if (mesh === this.mesh && mesh.material) {
  76807. return mesh.material.isReady(mesh);
  76808. }
  76809. var defines = [];
  76810. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76811. var material = subMesh.getMaterial();
  76812. // Alpha test
  76813. if (material) {
  76814. if (material.needAlphaTesting()) {
  76815. defines.push("#define ALPHATEST");
  76816. }
  76817. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76818. attribs.push(BABYLON.VertexBuffer.UVKind);
  76819. defines.push("#define UV1");
  76820. }
  76821. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76822. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76823. defines.push("#define UV2");
  76824. }
  76825. }
  76826. // Bones
  76827. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76828. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76829. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76830. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76831. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76832. }
  76833. else {
  76834. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76835. }
  76836. // Instances
  76837. if (useInstances) {
  76838. defines.push("#define INSTANCES");
  76839. attribs.push("world0");
  76840. attribs.push("world1");
  76841. attribs.push("world2");
  76842. attribs.push("world3");
  76843. }
  76844. // Get correct effect
  76845. var join = defines.join("\n");
  76846. if (this._cachedDefines !== join) {
  76847. this._cachedDefines = join;
  76848. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76849. }
  76850. return this._volumetricLightScatteringPass.isReady();
  76851. };
  76852. /**
  76853. * Sets the new light position for light scattering effect
  76854. * @param {BABYLON.Vector3} The new custom light position
  76855. */
  76856. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76857. this.customMeshPosition = position;
  76858. };
  76859. /**
  76860. * Returns the light position for light scattering effect
  76861. * @return {BABYLON.Vector3} The custom light position
  76862. */
  76863. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76864. return this.customMeshPosition;
  76865. };
  76866. /**
  76867. * Disposes the internal assets and detaches the post-process from the camera
  76868. */
  76869. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76870. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76871. if (rttIndex !== -1) {
  76872. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76873. }
  76874. this._volumetricLightScatteringRTT.dispose();
  76875. _super.prototype.dispose.call(this, camera);
  76876. };
  76877. /**
  76878. * Returns the render target texture used by the post-process
  76879. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76880. */
  76881. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76882. return this._volumetricLightScatteringRTT;
  76883. };
  76884. // Private methods
  76885. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76886. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76887. return true;
  76888. }
  76889. return false;
  76890. };
  76891. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76892. var _this = this;
  76893. var engine = scene.getEngine();
  76894. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76895. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76896. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76897. this._volumetricLightScatteringRTT.renderList = null;
  76898. this._volumetricLightScatteringRTT.renderParticles = false;
  76899. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76900. var camera = this.getCamera();
  76901. if (camera) {
  76902. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76903. }
  76904. else {
  76905. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76906. }
  76907. // Custom render function for submeshes
  76908. var renderSubMesh = function (subMesh) {
  76909. var mesh = subMesh.getRenderingMesh();
  76910. if (_this._meshExcluded(mesh)) {
  76911. return;
  76912. }
  76913. var material = subMesh.getMaterial();
  76914. if (!material) {
  76915. return;
  76916. }
  76917. var scene = mesh.getScene();
  76918. var engine = scene.getEngine();
  76919. // Culling
  76920. engine.setState(material.backFaceCulling);
  76921. // Managing instances
  76922. var batch = mesh._getInstancesRenderList(subMesh._id);
  76923. if (batch.mustReturn) {
  76924. return;
  76925. }
  76926. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76927. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76928. var effect = _this._volumetricLightScatteringPass;
  76929. if (mesh === _this.mesh) {
  76930. if (subMesh.effect) {
  76931. effect = subMesh.effect;
  76932. }
  76933. else {
  76934. effect = material.getEffect();
  76935. }
  76936. }
  76937. engine.enableEffect(effect);
  76938. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76939. if (mesh === _this.mesh) {
  76940. material.bind(mesh.getWorldMatrix(), mesh);
  76941. }
  76942. else {
  76943. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76944. // Alpha test
  76945. if (material && material.needAlphaTesting()) {
  76946. var alphaTexture = material.getAlphaTestTexture();
  76947. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76948. if (alphaTexture) {
  76949. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76950. }
  76951. }
  76952. // Bones
  76953. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76954. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76955. }
  76956. }
  76957. // Draw
  76958. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76959. }
  76960. };
  76961. // Render target texture callbacks
  76962. var savedSceneClearColor;
  76963. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76964. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76965. savedSceneClearColor = scene.clearColor;
  76966. scene.clearColor = sceneClearColor;
  76967. });
  76968. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76969. scene.clearColor = savedSceneClearColor;
  76970. });
  76971. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76972. var engine = scene.getEngine();
  76973. var index;
  76974. if (depthOnlySubMeshes.length) {
  76975. engine.setColorWrite(false);
  76976. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76977. renderSubMesh(depthOnlySubMeshes.data[index]);
  76978. }
  76979. engine.setColorWrite(true);
  76980. }
  76981. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76982. renderSubMesh(opaqueSubMeshes.data[index]);
  76983. }
  76984. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76985. renderSubMesh(alphaTestSubMeshes.data[index]);
  76986. }
  76987. if (transparentSubMeshes.length) {
  76988. // Sort sub meshes
  76989. for (index = 0; index < transparentSubMeshes.length; index++) {
  76990. var submesh = transparentSubMeshes.data[index];
  76991. var boundingInfo = submesh.getBoundingInfo();
  76992. if (boundingInfo && scene.activeCamera) {
  76993. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76994. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76995. }
  76996. }
  76997. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76998. sortedArray.sort(function (a, b) {
  76999. // Alpha index first
  77000. if (a._alphaIndex > b._alphaIndex) {
  77001. return 1;
  77002. }
  77003. if (a._alphaIndex < b._alphaIndex) {
  77004. return -1;
  77005. }
  77006. // Then distance to camera
  77007. if (a._distanceToCamera < b._distanceToCamera) {
  77008. return 1;
  77009. }
  77010. if (a._distanceToCamera > b._distanceToCamera) {
  77011. return -1;
  77012. }
  77013. return 0;
  77014. });
  77015. // Render sub meshes
  77016. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77017. for (index = 0; index < sortedArray.length; index++) {
  77018. renderSubMesh(sortedArray[index]);
  77019. }
  77020. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77021. }
  77022. };
  77023. };
  77024. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77025. var transform = scene.getTransformMatrix();
  77026. var meshPosition;
  77027. if (this.useCustomMeshPosition) {
  77028. meshPosition = this.customMeshPosition;
  77029. }
  77030. else if (this.attachedNode) {
  77031. meshPosition = this.attachedNode.position;
  77032. }
  77033. else {
  77034. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77035. }
  77036. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77037. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77038. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77039. if (this.invert)
  77040. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77041. };
  77042. // Static methods
  77043. /**
  77044. * Creates a default mesh for the Volumeric Light Scattering post-process
  77045. * @param {string} The mesh name
  77046. * @param {BABYLON.Scene} The scene where to create the mesh
  77047. * @return {BABYLON.Mesh} the default mesh
  77048. */
  77049. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77050. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77051. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77052. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77053. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77054. mesh.material = material;
  77055. return mesh;
  77056. };
  77057. __decorate([
  77058. BABYLON.serializeAsVector3()
  77059. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77060. __decorate([
  77061. BABYLON.serialize()
  77062. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77063. __decorate([
  77064. BABYLON.serialize()
  77065. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77066. __decorate([
  77067. BABYLON.serializeAsMeshReference()
  77068. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77069. __decorate([
  77070. BABYLON.serialize()
  77071. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77072. __decorate([
  77073. BABYLON.serialize()
  77074. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77075. __decorate([
  77076. BABYLON.serialize()
  77077. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77078. __decorate([
  77079. BABYLON.serialize()
  77080. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77081. __decorate([
  77082. BABYLON.serialize()
  77083. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77084. return VolumetricLightScatteringPostProcess;
  77085. }(BABYLON.PostProcess));
  77086. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77087. })(BABYLON || (BABYLON = {}));
  77088. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77089. //
  77090. // This post-process allows the modification of rendered colors by using
  77091. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77092. //
  77093. // The object needs to be provided an url to a texture containing the color
  77094. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77095. // Use an image editing software to tweak the LUT to match your needs.
  77096. //
  77097. // For an example of a color LUT, see here:
  77098. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77099. // For explanations on color grading, see here:
  77100. // http://udn.epicgames.com/Three/ColorGrading.html
  77101. //
  77102. var BABYLON;
  77103. (function (BABYLON) {
  77104. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77105. __extends(ColorCorrectionPostProcess, _super);
  77106. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77107. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77108. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77109. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77110. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77111. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77112. _this.onApply = function (effect) {
  77113. effect.setTexture("colorTable", _this._colorTableTexture);
  77114. };
  77115. return _this;
  77116. }
  77117. return ColorCorrectionPostProcess;
  77118. }(BABYLON.PostProcess));
  77119. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77120. })(BABYLON || (BABYLON = {}));
  77121. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77122. var BABYLON;
  77123. (function (BABYLON) {
  77124. /** Defines operator used for tonemapping */
  77125. var TonemappingOperator;
  77126. (function (TonemappingOperator) {
  77127. /** Hable */
  77128. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77129. /** Reinhard */
  77130. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77131. /** HejiDawson */
  77132. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77133. /** Photographic */
  77134. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77135. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77136. ;
  77137. /**
  77138. * Defines a post process to apply tone mapping
  77139. */
  77140. var TonemapPostProcess = /** @class */ (function (_super) {
  77141. __extends(TonemapPostProcess, _super);
  77142. /**
  77143. * Creates a new TonemapPostProcess
  77144. * @param name defines the name of the postprocess
  77145. * @param _operator defines the operator to use
  77146. * @param exposureAdjustment defines the required exposure adjustement
  77147. * @param camera defines the camera to use (can be null)
  77148. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77149. * @param engine defines the hosting engine (can be ignore if camera is set)
  77150. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77151. */
  77152. function TonemapPostProcess(name, _operator,
  77153. /** Defines the required exposure adjustement */
  77154. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77155. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77156. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77157. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77158. _this._operator = _operator;
  77159. _this.exposureAdjustment = exposureAdjustment;
  77160. var defines = "#define ";
  77161. if (_this._operator === TonemappingOperator.Hable)
  77162. defines += "HABLE_TONEMAPPING";
  77163. else if (_this._operator === TonemappingOperator.Reinhard)
  77164. defines += "REINHARD_TONEMAPPING";
  77165. else if (_this._operator === TonemappingOperator.HejiDawson)
  77166. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77167. else if (_this._operator === TonemappingOperator.Photographic)
  77168. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77169. //sadly a second call to create the effect.
  77170. _this.updateEffect(defines);
  77171. _this.onApply = function (effect) {
  77172. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77173. };
  77174. return _this;
  77175. }
  77176. return TonemapPostProcess;
  77177. }(BABYLON.PostProcess));
  77178. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77179. })(BABYLON || (BABYLON = {}));
  77180. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77181. var BABYLON;
  77182. (function (BABYLON) {
  77183. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77184. __extends(DisplayPassPostProcess, _super);
  77185. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77186. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77187. }
  77188. return DisplayPassPostProcess;
  77189. }(BABYLON.PostProcess));
  77190. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77191. })(BABYLON || (BABYLON = {}));
  77192. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77193. var BABYLON;
  77194. (function (BABYLON) {
  77195. var HighlightsPostProcess = /** @class */ (function (_super) {
  77196. __extends(HighlightsPostProcess, _super);
  77197. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77198. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77199. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77200. }
  77201. return HighlightsPostProcess;
  77202. }(BABYLON.PostProcess));
  77203. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77204. })(BABYLON || (BABYLON = {}));
  77205. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77206. var BABYLON;
  77207. (function (BABYLON) {
  77208. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77209. __extends(ImageProcessingPostProcess, _super);
  77210. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77211. if (camera === void 0) { camera = null; }
  77212. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77213. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77214. _this._fromLinearSpace = true;
  77215. /**
  77216. * Defines cache preventing GC.
  77217. */
  77218. _this._defines = {
  77219. IMAGEPROCESSING: false,
  77220. VIGNETTE: false,
  77221. VIGNETTEBLENDMODEMULTIPLY: false,
  77222. VIGNETTEBLENDMODEOPAQUE: false,
  77223. TONEMAPPING: false,
  77224. CONTRAST: false,
  77225. COLORCURVES: false,
  77226. COLORGRADING: false,
  77227. COLORGRADING3D: false,
  77228. FROMLINEARSPACE: false,
  77229. SAMPLER3DGREENDEPTH: false,
  77230. SAMPLER3DBGRMAP: false,
  77231. IMAGEPROCESSINGPOSTPROCESS: false,
  77232. EXPOSURE: false,
  77233. };
  77234. // Setup the configuration as forced by the constructor. This would then not force the
  77235. // scene materials output in linear space and let untouched the default forward pass.
  77236. if (imageProcessingConfiguration) {
  77237. imageProcessingConfiguration.applyByPostProcess = true;
  77238. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77239. // This will cause the shader to be compiled
  77240. _this.fromLinearSpace = false;
  77241. }
  77242. // Setup the default processing configuration to the scene.
  77243. else {
  77244. _this._attachImageProcessingConfiguration(null, true);
  77245. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77246. }
  77247. _this.onApply = function (effect) {
  77248. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77249. };
  77250. return _this;
  77251. }
  77252. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77253. /**
  77254. * Gets the image processing configuration used either in this material.
  77255. */
  77256. get: function () {
  77257. return this._imageProcessingConfiguration;
  77258. },
  77259. /**
  77260. * Sets the Default image processing configuration used either in the this material.
  77261. *
  77262. * If sets to null, the scene one is in use.
  77263. */
  77264. set: function (value) {
  77265. this._attachImageProcessingConfiguration(value);
  77266. },
  77267. enumerable: true,
  77268. configurable: true
  77269. });
  77270. /**
  77271. * Attaches a new image processing configuration to the PBR Material.
  77272. * @param configuration
  77273. */
  77274. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77275. var _this = this;
  77276. if (doNotBuild === void 0) { doNotBuild = false; }
  77277. if (configuration === this._imageProcessingConfiguration) {
  77278. return;
  77279. }
  77280. // Detaches observer.
  77281. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77282. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77283. }
  77284. // Pick the scene configuration if needed.
  77285. if (!configuration) {
  77286. var scene = null;
  77287. var engine = this.getEngine();
  77288. var camera = this.getCamera();
  77289. if (camera) {
  77290. scene = camera.getScene();
  77291. }
  77292. else if (engine && engine.scenes) {
  77293. var scenes = engine.scenes;
  77294. scene = scenes[scenes.length - 1];
  77295. }
  77296. else {
  77297. scene = BABYLON.Engine.LastCreatedScene;
  77298. }
  77299. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77300. }
  77301. else {
  77302. this._imageProcessingConfiguration = configuration;
  77303. }
  77304. // Attaches observer.
  77305. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77306. _this._updateParameters();
  77307. });
  77308. // Ensure the effect will be rebuilt.
  77309. if (!doNotBuild) {
  77310. this._updateParameters();
  77311. }
  77312. };
  77313. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77314. /**
  77315. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77316. */
  77317. get: function () {
  77318. return this.imageProcessingConfiguration.colorCurves;
  77319. },
  77320. /**
  77321. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77322. */
  77323. set: function (value) {
  77324. this.imageProcessingConfiguration.colorCurves = value;
  77325. },
  77326. enumerable: true,
  77327. configurable: true
  77328. });
  77329. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77330. /**
  77331. * Gets wether the color curves effect is enabled.
  77332. */
  77333. get: function () {
  77334. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77335. },
  77336. /**
  77337. * Sets wether the color curves effect is enabled.
  77338. */
  77339. set: function (value) {
  77340. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77341. },
  77342. enumerable: true,
  77343. configurable: true
  77344. });
  77345. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77346. /**
  77347. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77348. */
  77349. get: function () {
  77350. return this.imageProcessingConfiguration.colorGradingTexture;
  77351. },
  77352. /**
  77353. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77354. */
  77355. set: function (value) {
  77356. this.imageProcessingConfiguration.colorGradingTexture = value;
  77357. },
  77358. enumerable: true,
  77359. configurable: true
  77360. });
  77361. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77362. /**
  77363. * Gets wether the color grading effect is enabled.
  77364. */
  77365. get: function () {
  77366. return this.imageProcessingConfiguration.colorGradingEnabled;
  77367. },
  77368. /**
  77369. * Gets wether the color grading effect is enabled.
  77370. */
  77371. set: function (value) {
  77372. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77373. },
  77374. enumerable: true,
  77375. configurable: true
  77376. });
  77377. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77378. /**
  77379. * Gets exposure used in the effect.
  77380. */
  77381. get: function () {
  77382. return this.imageProcessingConfiguration.exposure;
  77383. },
  77384. /**
  77385. * Sets exposure used in the effect.
  77386. */
  77387. set: function (value) {
  77388. this.imageProcessingConfiguration.exposure = value;
  77389. },
  77390. enumerable: true,
  77391. configurable: true
  77392. });
  77393. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77394. /**
  77395. * Gets wether tonemapping is enabled or not.
  77396. */
  77397. get: function () {
  77398. return this._imageProcessingConfiguration.toneMappingEnabled;
  77399. },
  77400. /**
  77401. * Sets wether tonemapping is enabled or not
  77402. */
  77403. set: function (value) {
  77404. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77405. },
  77406. enumerable: true,
  77407. configurable: true
  77408. });
  77409. ;
  77410. ;
  77411. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77412. /**
  77413. * Gets contrast used in the effect.
  77414. */
  77415. get: function () {
  77416. return this.imageProcessingConfiguration.contrast;
  77417. },
  77418. /**
  77419. * Sets contrast used in the effect.
  77420. */
  77421. set: function (value) {
  77422. this.imageProcessingConfiguration.contrast = value;
  77423. },
  77424. enumerable: true,
  77425. configurable: true
  77426. });
  77427. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77428. /**
  77429. * Gets Vignette stretch size.
  77430. */
  77431. get: function () {
  77432. return this.imageProcessingConfiguration.vignetteStretch;
  77433. },
  77434. /**
  77435. * Sets Vignette stretch size.
  77436. */
  77437. set: function (value) {
  77438. this.imageProcessingConfiguration.vignetteStretch = value;
  77439. },
  77440. enumerable: true,
  77441. configurable: true
  77442. });
  77443. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77444. /**
  77445. * Gets Vignette centre X Offset.
  77446. */
  77447. get: function () {
  77448. return this.imageProcessingConfiguration.vignetteCentreX;
  77449. },
  77450. /**
  77451. * Sets Vignette centre X Offset.
  77452. */
  77453. set: function (value) {
  77454. this.imageProcessingConfiguration.vignetteCentreX = value;
  77455. },
  77456. enumerable: true,
  77457. configurable: true
  77458. });
  77459. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77460. /**
  77461. * Gets Vignette centre Y Offset.
  77462. */
  77463. get: function () {
  77464. return this.imageProcessingConfiguration.vignetteCentreY;
  77465. },
  77466. /**
  77467. * Sets Vignette centre Y Offset.
  77468. */
  77469. set: function (value) {
  77470. this.imageProcessingConfiguration.vignetteCentreY = value;
  77471. },
  77472. enumerable: true,
  77473. configurable: true
  77474. });
  77475. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77476. /**
  77477. * Gets Vignette weight or intensity of the vignette effect.
  77478. */
  77479. get: function () {
  77480. return this.imageProcessingConfiguration.vignetteWeight;
  77481. },
  77482. /**
  77483. * Sets Vignette weight or intensity of the vignette effect.
  77484. */
  77485. set: function (value) {
  77486. this.imageProcessingConfiguration.vignetteWeight = value;
  77487. },
  77488. enumerable: true,
  77489. configurable: true
  77490. });
  77491. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77492. /**
  77493. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77494. * if vignetteEnabled is set to true.
  77495. */
  77496. get: function () {
  77497. return this.imageProcessingConfiguration.vignetteColor;
  77498. },
  77499. /**
  77500. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77501. * if vignetteEnabled is set to true.
  77502. */
  77503. set: function (value) {
  77504. this.imageProcessingConfiguration.vignetteColor = value;
  77505. },
  77506. enumerable: true,
  77507. configurable: true
  77508. });
  77509. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77510. /**
  77511. * Gets Camera field of view used by the Vignette effect.
  77512. */
  77513. get: function () {
  77514. return this.imageProcessingConfiguration.vignetteCameraFov;
  77515. },
  77516. /**
  77517. * Sets Camera field of view used by the Vignette effect.
  77518. */
  77519. set: function (value) {
  77520. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77521. },
  77522. enumerable: true,
  77523. configurable: true
  77524. });
  77525. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77526. /**
  77527. * Gets the vignette blend mode allowing different kind of effect.
  77528. */
  77529. get: function () {
  77530. return this.imageProcessingConfiguration.vignetteBlendMode;
  77531. },
  77532. /**
  77533. * Sets the vignette blend mode allowing different kind of effect.
  77534. */
  77535. set: function (value) {
  77536. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77537. },
  77538. enumerable: true,
  77539. configurable: true
  77540. });
  77541. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77542. /**
  77543. * Gets wether the vignette effect is enabled.
  77544. */
  77545. get: function () {
  77546. return this.imageProcessingConfiguration.vignetteEnabled;
  77547. },
  77548. /**
  77549. * Sets wether the vignette effect is enabled.
  77550. */
  77551. set: function (value) {
  77552. this.imageProcessingConfiguration.vignetteEnabled = value;
  77553. },
  77554. enumerable: true,
  77555. configurable: true
  77556. });
  77557. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77558. /**
  77559. * Gets wether the input of the processing is in Gamma or Linear Space.
  77560. */
  77561. get: function () {
  77562. return this._fromLinearSpace;
  77563. },
  77564. /**
  77565. * Sets wether the input of the processing is in Gamma or Linear Space.
  77566. */
  77567. set: function (value) {
  77568. if (this._fromLinearSpace === value) {
  77569. return;
  77570. }
  77571. this._fromLinearSpace = value;
  77572. this._updateParameters();
  77573. },
  77574. enumerable: true,
  77575. configurable: true
  77576. });
  77577. ImageProcessingPostProcess.prototype.getClassName = function () {
  77578. return "ImageProcessingPostProcess";
  77579. };
  77580. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77581. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77582. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77583. var defines = "";
  77584. for (var define in this._defines) {
  77585. if (this._defines[define]) {
  77586. defines += "#define " + define + ";\r\n";
  77587. }
  77588. }
  77589. var samplers = ["textureSampler"];
  77590. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77591. var uniforms = ["scale"];
  77592. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77593. this.updateEffect(defines, uniforms, samplers);
  77594. };
  77595. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77596. _super.prototype.dispose.call(this, camera);
  77597. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77598. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77599. }
  77600. this.imageProcessingConfiguration.applyByPostProcess = false;
  77601. };
  77602. __decorate([
  77603. BABYLON.serialize()
  77604. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77605. return ImageProcessingPostProcess;
  77606. }(BABYLON.PostProcess));
  77607. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77608. })(BABYLON || (BABYLON = {}));
  77609. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77610. var BABYLON;
  77611. (function (BABYLON) {
  77612. /**
  77613. * Class used to store bone information
  77614. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77615. */
  77616. var Bone = /** @class */ (function (_super) {
  77617. __extends(Bone, _super);
  77618. /**
  77619. * Create a new bone
  77620. * @param name defines the bone name
  77621. * @param skeleton defines the parent skeleton
  77622. * @param parentBone defines the parent (can be null if the bone is the root)
  77623. * @param localMatrix defines the local matrix
  77624. * @param restPose defines the rest pose matrix
  77625. * @param baseMatrix defines the base matrix
  77626. * @param index defines index of the bone in the hiearchy
  77627. */
  77628. function Bone(
  77629. /**
  77630. * defines the bone name
  77631. */
  77632. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77633. if (parentBone === void 0) { parentBone = null; }
  77634. if (localMatrix === void 0) { localMatrix = null; }
  77635. if (restPose === void 0) { restPose = null; }
  77636. if (baseMatrix === void 0) { baseMatrix = null; }
  77637. if (index === void 0) { index = null; }
  77638. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77639. _this.name = name;
  77640. /**
  77641. * Gets the list of child bones
  77642. */
  77643. _this.children = new Array();
  77644. /** Gets the animations associated with this bone */
  77645. _this.animations = new Array();
  77646. /**
  77647. * @hidden Internal only
  77648. * Set this value to map this bone to a different index in the transform matrices
  77649. * Set this value to -1 to exclude the bone from the transform matrices
  77650. */
  77651. _this._index = null;
  77652. _this._absoluteTransform = new BABYLON.Matrix();
  77653. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77654. _this._scalingDeterminant = 1;
  77655. _this._worldTransform = new BABYLON.Matrix();
  77656. _this._needToDecompose = true;
  77657. _this._needToCompose = false;
  77658. _this._skeleton = skeleton;
  77659. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77660. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77661. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77662. _this._index = index;
  77663. skeleton.bones.push(_this);
  77664. _this.setParent(parentBone, false);
  77665. if (baseMatrix || localMatrix) {
  77666. _this._updateDifferenceMatrix();
  77667. }
  77668. return _this;
  77669. }
  77670. Object.defineProperty(Bone.prototype, "_matrix", {
  77671. /** @hidden */
  77672. get: function () {
  77673. this._compose();
  77674. return this._localMatrix;
  77675. },
  77676. /** @hidden */
  77677. set: function (value) {
  77678. this._localMatrix.copyFrom(value);
  77679. this._needToDecompose = true;
  77680. },
  77681. enumerable: true,
  77682. configurable: true
  77683. });
  77684. // Members
  77685. /**
  77686. * Gets the parent skeleton
  77687. * @returns a skeleton
  77688. */
  77689. Bone.prototype.getSkeleton = function () {
  77690. return this._skeleton;
  77691. };
  77692. /**
  77693. * Gets parent bone
  77694. * @returns a bone or null if the bone is the root of the bone hierarchy
  77695. */
  77696. Bone.prototype.getParent = function () {
  77697. return this._parent;
  77698. };
  77699. /**
  77700. * Sets the parent bone
  77701. * @param parent defines the parent (can be null if the bone is the root)
  77702. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77703. */
  77704. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77705. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77706. if (this._parent === parent) {
  77707. return;
  77708. }
  77709. if (this._parent) {
  77710. var index = this._parent.children.indexOf(this);
  77711. if (index !== -1) {
  77712. this._parent.children.splice(index, 1);
  77713. }
  77714. }
  77715. this._parent = parent;
  77716. if (this._parent) {
  77717. this._parent.children.push(this);
  77718. }
  77719. if (updateDifferenceMatrix) {
  77720. this._updateDifferenceMatrix();
  77721. }
  77722. this.markAsDirty();
  77723. };
  77724. /**
  77725. * Gets the local matrix
  77726. * @returns a matrix
  77727. */
  77728. Bone.prototype.getLocalMatrix = function () {
  77729. this._compose();
  77730. return this._localMatrix;
  77731. };
  77732. /**
  77733. * Gets the base matrix (initial matrix which remains unchanged)
  77734. * @returns a matrix
  77735. */
  77736. Bone.prototype.getBaseMatrix = function () {
  77737. return this._baseMatrix;
  77738. };
  77739. /**
  77740. * Gets the rest pose matrix
  77741. * @returns a matrix
  77742. */
  77743. Bone.prototype.getRestPose = function () {
  77744. return this._restPose;
  77745. };
  77746. /**
  77747. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77748. */
  77749. Bone.prototype.getWorldMatrix = function () {
  77750. return this._worldTransform;
  77751. };
  77752. /**
  77753. * Sets the local matrix to rest pose matrix
  77754. */
  77755. Bone.prototype.returnToRest = function () {
  77756. this.updateMatrix(this._restPose.clone());
  77757. };
  77758. /**
  77759. * Gets the inverse of the absolute transform matrix.
  77760. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77761. * @returns a matrix
  77762. */
  77763. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77764. return this._invertedAbsoluteTransform;
  77765. };
  77766. /**
  77767. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77768. * @returns a matrix
  77769. */
  77770. Bone.prototype.getAbsoluteTransform = function () {
  77771. return this._absoluteTransform;
  77772. };
  77773. Object.defineProperty(Bone.prototype, "position", {
  77774. // Properties (matches AbstractMesh properties)
  77775. /** Gets or sets current position (in local space) */
  77776. get: function () {
  77777. this._decompose();
  77778. return this._localPosition;
  77779. },
  77780. set: function (newPosition) {
  77781. this._decompose();
  77782. this._localPosition.copyFrom(newPosition);
  77783. this._markAsDirtyAndCompose();
  77784. },
  77785. enumerable: true,
  77786. configurable: true
  77787. });
  77788. Object.defineProperty(Bone.prototype, "rotation", {
  77789. /** Gets or sets current rotation (in local space) */
  77790. get: function () {
  77791. return this.getRotation();
  77792. },
  77793. set: function (newRotation) {
  77794. this.setRotation(newRotation);
  77795. },
  77796. enumerable: true,
  77797. configurable: true
  77798. });
  77799. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77800. /** Gets or sets current rotation quaternion (in local space) */
  77801. get: function () {
  77802. this._decompose();
  77803. return this._localRotation;
  77804. },
  77805. set: function (newRotation) {
  77806. this.setRotationQuaternion(newRotation);
  77807. },
  77808. enumerable: true,
  77809. configurable: true
  77810. });
  77811. Object.defineProperty(Bone.prototype, "scaling", {
  77812. /** Gets or sets current scaling (in local space) */
  77813. get: function () {
  77814. return this.getScale();
  77815. },
  77816. set: function (newScaling) {
  77817. this.setScale(newScaling);
  77818. },
  77819. enumerable: true,
  77820. configurable: true
  77821. });
  77822. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77823. /**
  77824. * Gets the animation properties override
  77825. */
  77826. get: function () {
  77827. return this._skeleton.animationPropertiesOverride;
  77828. },
  77829. enumerable: true,
  77830. configurable: true
  77831. });
  77832. // Methods
  77833. Bone.prototype._decompose = function () {
  77834. if (!this._needToDecompose) {
  77835. return;
  77836. }
  77837. this._needToDecompose = false;
  77838. if (!this._localScaling) {
  77839. this._localScaling = BABYLON.Vector3.Zero();
  77840. this._localRotation = BABYLON.Quaternion.Zero();
  77841. this._localPosition = BABYLON.Vector3.Zero();
  77842. }
  77843. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77844. };
  77845. Bone.prototype._compose = function () {
  77846. if (!this._needToCompose) {
  77847. return;
  77848. }
  77849. this._needToCompose = false;
  77850. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77851. };
  77852. /**
  77853. * Update the base and local matrices
  77854. * @param matrix defines the new base or local matrix
  77855. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77856. * @param updateLocalMatrix defines if the local matrix should be updated
  77857. */
  77858. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77859. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77860. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77861. this._baseMatrix.copyFrom(matrix);
  77862. if (updateDifferenceMatrix) {
  77863. this._updateDifferenceMatrix();
  77864. }
  77865. if (updateLocalMatrix) {
  77866. this._localMatrix.copyFrom(matrix);
  77867. this._markAsDirtyAndDecompose();
  77868. }
  77869. else {
  77870. this.markAsDirty();
  77871. }
  77872. };
  77873. /** @hidden */
  77874. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77875. if (updateChildren === void 0) { updateChildren = true; }
  77876. if (!rootMatrix) {
  77877. rootMatrix = this._baseMatrix;
  77878. }
  77879. if (this._parent) {
  77880. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77881. }
  77882. else {
  77883. this._absoluteTransform.copyFrom(rootMatrix);
  77884. }
  77885. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77886. if (updateChildren) {
  77887. for (var index = 0; index < this.children.length; index++) {
  77888. this.children[index]._updateDifferenceMatrix();
  77889. }
  77890. }
  77891. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77892. };
  77893. /**
  77894. * Flag the bone as dirty (Forcing it to update everything)
  77895. */
  77896. Bone.prototype.markAsDirty = function () {
  77897. this._currentRenderId++;
  77898. this._childRenderId++;
  77899. this._skeleton._markAsDirty();
  77900. };
  77901. Bone.prototype._markAsDirtyAndCompose = function () {
  77902. this.markAsDirty();
  77903. this._needToCompose = true;
  77904. };
  77905. Bone.prototype._markAsDirtyAndDecompose = function () {
  77906. this.markAsDirty();
  77907. this._needToDecompose = true;
  77908. };
  77909. /**
  77910. * Copy an animation range from another bone
  77911. * @param source defines the source bone
  77912. * @param rangeName defines the range name to copy
  77913. * @param frameOffset defines the frame offset
  77914. * @param rescaleAsRequired defines if rescaling must be applied if required
  77915. * @param skelDimensionsRatio defines the scaling ratio
  77916. * @returns true if operation was successful
  77917. */
  77918. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77919. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77920. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77921. // all animation may be coming from a library skeleton, so may need to create animation
  77922. if (this.animations.length === 0) {
  77923. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77924. this.animations[0].setKeys([]);
  77925. }
  77926. // get animation info / verify there is such a range from the source bone
  77927. var sourceRange = source.animations[0].getRange(rangeName);
  77928. if (!sourceRange) {
  77929. return false;
  77930. }
  77931. var from = sourceRange.from;
  77932. var to = sourceRange.to;
  77933. var sourceKeys = source.animations[0].getKeys();
  77934. // rescaling prep
  77935. var sourceBoneLength = source.length;
  77936. var sourceParent = source.getParent();
  77937. var parent = this.getParent();
  77938. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77939. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77940. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77941. var destKeys = this.animations[0].getKeys();
  77942. // loop vars declaration
  77943. var orig;
  77944. var origTranslation;
  77945. var mat;
  77946. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77947. orig = sourceKeys[key];
  77948. if (orig.frame >= from && orig.frame <= to) {
  77949. if (rescaleAsRequired) {
  77950. mat = orig.value.clone();
  77951. // scale based on parent ratio, when bone has parent
  77952. if (parentScalingReqd) {
  77953. origTranslation = mat.getTranslation();
  77954. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77955. // scale based on skeleton dimension ratio when root bone, and value is passed
  77956. }
  77957. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77958. origTranslation = mat.getTranslation();
  77959. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77960. // use original when root bone, and no data for skelDimensionsRatio
  77961. }
  77962. else {
  77963. mat = orig.value;
  77964. }
  77965. }
  77966. else {
  77967. mat = orig.value;
  77968. }
  77969. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77970. }
  77971. }
  77972. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77973. return true;
  77974. };
  77975. /**
  77976. * Translate the bone in local or world space
  77977. * @param vec The amount to translate the bone
  77978. * @param space The space that the translation is in
  77979. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77980. */
  77981. Bone.prototype.translate = function (vec, space, mesh) {
  77982. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77983. var lm = this.getLocalMatrix();
  77984. if (space == BABYLON.Space.LOCAL) {
  77985. lm.m[12] += vec.x;
  77986. lm.m[13] += vec.y;
  77987. lm.m[14] += vec.z;
  77988. }
  77989. else {
  77990. var wm = null;
  77991. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77992. if (mesh) {
  77993. wm = mesh.getWorldMatrix();
  77994. }
  77995. this._skeleton.computeAbsoluteTransforms();
  77996. var tmat = Bone._tmpMats[0];
  77997. var tvec = Bone._tmpVecs[0];
  77998. if (this._parent) {
  77999. if (mesh && wm) {
  78000. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78001. tmat.multiplyToRef(wm, tmat);
  78002. }
  78003. else {
  78004. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78005. }
  78006. }
  78007. tmat.m[12] = 0;
  78008. tmat.m[13] = 0;
  78009. tmat.m[14] = 0;
  78010. tmat.invert();
  78011. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78012. lm.m[12] += tvec.x;
  78013. lm.m[13] += tvec.y;
  78014. lm.m[14] += tvec.z;
  78015. }
  78016. this._markAsDirtyAndDecompose();
  78017. };
  78018. /**
  78019. * Set the postion of the bone in local or world space
  78020. * @param position The position to set the bone
  78021. * @param space The space that the position is in
  78022. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78023. */
  78024. Bone.prototype.setPosition = function (position, space, mesh) {
  78025. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78026. var lm = this.getLocalMatrix();
  78027. if (space == BABYLON.Space.LOCAL) {
  78028. lm.m[12] = position.x;
  78029. lm.m[13] = position.y;
  78030. lm.m[14] = position.z;
  78031. }
  78032. else {
  78033. var wm = null;
  78034. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78035. if (mesh) {
  78036. wm = mesh.getWorldMatrix();
  78037. }
  78038. this._skeleton.computeAbsoluteTransforms();
  78039. var tmat = Bone._tmpMats[0];
  78040. var vec = Bone._tmpVecs[0];
  78041. if (this._parent) {
  78042. if (mesh && wm) {
  78043. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78044. tmat.multiplyToRef(wm, tmat);
  78045. }
  78046. else {
  78047. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78048. }
  78049. }
  78050. tmat.invert();
  78051. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78052. lm.m[12] = vec.x;
  78053. lm.m[13] = vec.y;
  78054. lm.m[14] = vec.z;
  78055. }
  78056. this._markAsDirtyAndDecompose();
  78057. };
  78058. /**
  78059. * Set the absolute position of the bone (world space)
  78060. * @param position The position to set the bone
  78061. * @param mesh The mesh that this bone is attached to
  78062. */
  78063. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78064. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78065. };
  78066. /**
  78067. * Scale the bone on the x, y and z axes (in local space)
  78068. * @param x The amount to scale the bone on the x axis
  78069. * @param y The amount to scale the bone on the y axis
  78070. * @param z The amount to scale the bone on the z axis
  78071. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78072. */
  78073. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78074. if (scaleChildren === void 0) { scaleChildren = false; }
  78075. var locMat = this.getLocalMatrix();
  78076. // Apply new scaling on top of current local matrix
  78077. var scaleMat = Bone._tmpMats[0];
  78078. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78079. scaleMat.multiplyToRef(locMat, locMat);
  78080. // Invert scaling matrix and apply the inverse to all children
  78081. scaleMat.invert();
  78082. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78083. var child = _a[_i];
  78084. var cm = child.getLocalMatrix();
  78085. cm.multiplyToRef(scaleMat, cm);
  78086. cm.m[12] *= x;
  78087. cm.m[13] *= y;
  78088. cm.m[14] *= z;
  78089. child._markAsDirtyAndDecompose();
  78090. }
  78091. this._markAsDirtyAndDecompose();
  78092. if (scaleChildren) {
  78093. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78094. var child = _c[_b];
  78095. child.scale(x, y, z, scaleChildren);
  78096. }
  78097. }
  78098. };
  78099. /**
  78100. * Set the bone scaling in local space
  78101. * @param scale defines the scaling vector
  78102. */
  78103. Bone.prototype.setScale = function (scale) {
  78104. this._decompose();
  78105. this._localScaling.copyFrom(scale);
  78106. this._markAsDirtyAndCompose();
  78107. };
  78108. /**
  78109. * Gets the current scaling in local space
  78110. * @returns the current scaling vector
  78111. */
  78112. Bone.prototype.getScale = function () {
  78113. this._decompose();
  78114. return this._localScaling;
  78115. };
  78116. /**
  78117. * Gets the current scaling in local space and stores it in a target vector
  78118. * @param result defines the target vector
  78119. */
  78120. Bone.prototype.getScaleToRef = function (result) {
  78121. this._decompose();
  78122. result.copyFrom(this._localScaling);
  78123. };
  78124. /**
  78125. * Set the yaw, pitch, and roll of the bone in local or world space
  78126. * @param yaw The rotation of the bone on the y axis
  78127. * @param pitch The rotation of the bone on the x axis
  78128. * @param roll The rotation of the bone on the z axis
  78129. * @param space The space that the axes of rotation are in
  78130. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78131. */
  78132. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78133. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78134. if (space === BABYLON.Space.LOCAL) {
  78135. var quat = Bone._tmpQuat;
  78136. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78137. this.setRotationQuaternion(quat, space, mesh);
  78138. return;
  78139. }
  78140. var rotMatInv = Bone._tmpMats[0];
  78141. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78142. return;
  78143. }
  78144. var rotMat = Bone._tmpMats[1];
  78145. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78146. rotMatInv.multiplyToRef(rotMat, rotMat);
  78147. this._rotateWithMatrix(rotMat, space, mesh);
  78148. };
  78149. /**
  78150. * Add a rotation to the bone on an axis in local or world space
  78151. * @param axis The axis to rotate the bone on
  78152. * @param amount The amount to rotate the bone
  78153. * @param space The space that the axis is in
  78154. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78155. */
  78156. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78157. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78158. var rmat = Bone._tmpMats[0];
  78159. rmat.m[12] = 0;
  78160. rmat.m[13] = 0;
  78161. rmat.m[14] = 0;
  78162. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78163. this._rotateWithMatrix(rmat, space, mesh);
  78164. };
  78165. /**
  78166. * Set the rotation of the bone to a particular axis angle in local or world space
  78167. * @param axis The axis to rotate the bone on
  78168. * @param angle The angle that the bone should be rotated to
  78169. * @param space The space that the axis is in
  78170. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78171. */
  78172. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78174. if (space === BABYLON.Space.LOCAL) {
  78175. var quat = Bone._tmpQuat;
  78176. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78177. this.setRotationQuaternion(quat, space, mesh);
  78178. return;
  78179. }
  78180. var rotMatInv = Bone._tmpMats[0];
  78181. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78182. return;
  78183. }
  78184. var rotMat = Bone._tmpMats[1];
  78185. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78186. rotMatInv.multiplyToRef(rotMat, rotMat);
  78187. this._rotateWithMatrix(rotMat, space, mesh);
  78188. };
  78189. /**
  78190. * Set the euler rotation of the bone in local of world space
  78191. * @param rotation The euler rotation that the bone should be set to
  78192. * @param space The space that the rotation is in
  78193. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78194. */
  78195. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78196. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78197. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78198. };
  78199. /**
  78200. * Set the quaternion rotation of the bone in local of world space
  78201. * @param quat The quaternion rotation that the bone should be set to
  78202. * @param space The space that the rotation is in
  78203. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78204. */
  78205. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78207. if (space === BABYLON.Space.LOCAL) {
  78208. this._decompose();
  78209. this._localRotation.copyFrom(quat);
  78210. this._markAsDirtyAndCompose();
  78211. return;
  78212. }
  78213. var rotMatInv = Bone._tmpMats[0];
  78214. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78215. return;
  78216. }
  78217. var rotMat = Bone._tmpMats[1];
  78218. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78219. rotMatInv.multiplyToRef(rotMat, rotMat);
  78220. this._rotateWithMatrix(rotMat, space, mesh);
  78221. };
  78222. /**
  78223. * Set the rotation matrix of the bone in local of world space
  78224. * @param rotMat The rotation matrix that the bone should be set to
  78225. * @param space The space that the rotation is in
  78226. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78227. */
  78228. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78229. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78230. if (space === BABYLON.Space.LOCAL) {
  78231. var quat = Bone._tmpQuat;
  78232. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78233. this.setRotationQuaternion(quat, space, mesh);
  78234. return;
  78235. }
  78236. var rotMatInv = Bone._tmpMats[0];
  78237. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78238. return;
  78239. }
  78240. var rotMat2 = Bone._tmpMats[1];
  78241. rotMat2.copyFrom(rotMat);
  78242. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78243. this._rotateWithMatrix(rotMat2, space, mesh);
  78244. };
  78245. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78247. var lmat = this.getLocalMatrix();
  78248. var lx = lmat.m[12];
  78249. var ly = lmat.m[13];
  78250. var lz = lmat.m[14];
  78251. var parent = this.getParent();
  78252. var parentScale = Bone._tmpMats[3];
  78253. var parentScaleInv = Bone._tmpMats[4];
  78254. if (parent && space == BABYLON.Space.WORLD) {
  78255. if (mesh) {
  78256. parentScale.copyFrom(mesh.getWorldMatrix());
  78257. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78258. }
  78259. else {
  78260. parentScale.copyFrom(parent.getAbsoluteTransform());
  78261. }
  78262. parentScaleInv.copyFrom(parentScale);
  78263. parentScaleInv.invert();
  78264. lmat.multiplyToRef(parentScale, lmat);
  78265. lmat.multiplyToRef(rmat, lmat);
  78266. lmat.multiplyToRef(parentScaleInv, lmat);
  78267. }
  78268. else {
  78269. if (space == BABYLON.Space.WORLD && mesh) {
  78270. parentScale.copyFrom(mesh.getWorldMatrix());
  78271. parentScaleInv.copyFrom(parentScale);
  78272. parentScaleInv.invert();
  78273. lmat.multiplyToRef(parentScale, lmat);
  78274. lmat.multiplyToRef(rmat, lmat);
  78275. lmat.multiplyToRef(parentScaleInv, lmat);
  78276. }
  78277. else {
  78278. lmat.multiplyToRef(rmat, lmat);
  78279. }
  78280. }
  78281. lmat.m[12] = lx;
  78282. lmat.m[13] = ly;
  78283. lmat.m[14] = lz;
  78284. this.computeAbsoluteTransforms();
  78285. this._markAsDirtyAndDecompose();
  78286. };
  78287. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78288. var scaleMatrix = Bone._tmpMats[2];
  78289. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78290. if (mesh) {
  78291. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78292. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78293. }
  78294. rotMatInv.invert();
  78295. if (isNaN(rotMatInv.m[0])) {
  78296. // Matrix failed to invert.
  78297. // This can happen if scale is zero for example.
  78298. return false;
  78299. }
  78300. scaleMatrix.m[0] *= this._scalingDeterminant;
  78301. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78302. return true;
  78303. };
  78304. /**
  78305. * Get the position of the bone in local or world space
  78306. * @param space The space that the returned position is in
  78307. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78308. * @returns The position of the bone
  78309. */
  78310. Bone.prototype.getPosition = function (space, mesh) {
  78311. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78312. if (mesh === void 0) { mesh = null; }
  78313. var pos = BABYLON.Vector3.Zero();
  78314. this.getPositionToRef(space, mesh, pos);
  78315. return pos;
  78316. };
  78317. /**
  78318. * Copy the position of the bone to a vector3 in local or world space
  78319. * @param space The space that the returned position is in
  78320. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78321. * @param result The vector3 to copy the position to
  78322. */
  78323. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78324. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78325. if (space == BABYLON.Space.LOCAL) {
  78326. var lm = this.getLocalMatrix();
  78327. result.x = lm.m[12];
  78328. result.y = lm.m[13];
  78329. result.z = lm.m[14];
  78330. }
  78331. else {
  78332. var wm = null;
  78333. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78334. if (mesh) {
  78335. wm = mesh.getWorldMatrix();
  78336. }
  78337. this._skeleton.computeAbsoluteTransforms();
  78338. var tmat = Bone._tmpMats[0];
  78339. if (mesh && wm) {
  78340. tmat.copyFrom(this.getAbsoluteTransform());
  78341. tmat.multiplyToRef(wm, tmat);
  78342. }
  78343. else {
  78344. tmat = this.getAbsoluteTransform();
  78345. }
  78346. result.x = tmat.m[12];
  78347. result.y = tmat.m[13];
  78348. result.z = tmat.m[14];
  78349. }
  78350. };
  78351. /**
  78352. * Get the absolute position of the bone (world space)
  78353. * @param mesh The mesh that this bone is attached to
  78354. * @returns The absolute position of the bone
  78355. */
  78356. Bone.prototype.getAbsolutePosition = function (mesh) {
  78357. if (mesh === void 0) { mesh = null; }
  78358. var pos = BABYLON.Vector3.Zero();
  78359. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78360. return pos;
  78361. };
  78362. /**
  78363. * Copy the absolute position of the bone (world space) to the result param
  78364. * @param mesh The mesh that this bone is attached to
  78365. * @param result The vector3 to copy the absolute position to
  78366. */
  78367. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78368. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78369. };
  78370. /**
  78371. * Compute the absolute transforms of this bone and its children
  78372. */
  78373. Bone.prototype.computeAbsoluteTransforms = function () {
  78374. this._compose();
  78375. if (this._parent) {
  78376. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78377. }
  78378. else {
  78379. this._absoluteTransform.copyFrom(this._localMatrix);
  78380. var poseMatrix = this._skeleton.getPoseMatrix();
  78381. if (poseMatrix) {
  78382. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78383. }
  78384. }
  78385. var children = this.children;
  78386. var len = children.length;
  78387. for (var i = 0; i < len; i++) {
  78388. children[i].computeAbsoluteTransforms();
  78389. }
  78390. };
  78391. /**
  78392. * Get the world direction from an axis that is in the local space of the bone
  78393. * @param localAxis The local direction that is used to compute the world direction
  78394. * @param mesh The mesh that this bone is attached to
  78395. * @returns The world direction
  78396. */
  78397. Bone.prototype.getDirection = function (localAxis, mesh) {
  78398. if (mesh === void 0) { mesh = null; }
  78399. var result = BABYLON.Vector3.Zero();
  78400. this.getDirectionToRef(localAxis, mesh, result);
  78401. return result;
  78402. };
  78403. /**
  78404. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78405. * @param localAxis The local direction that is used to compute the world direction
  78406. * @param mesh The mesh that this bone is attached to
  78407. * @param result The vector3 that the world direction will be copied to
  78408. */
  78409. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78410. if (mesh === void 0) { mesh = null; }
  78411. var wm = null;
  78412. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78413. if (mesh) {
  78414. wm = mesh.getWorldMatrix();
  78415. }
  78416. this._skeleton.computeAbsoluteTransforms();
  78417. var mat = Bone._tmpMats[0];
  78418. mat.copyFrom(this.getAbsoluteTransform());
  78419. if (mesh && wm) {
  78420. mat.multiplyToRef(wm, mat);
  78421. }
  78422. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78423. result.normalize();
  78424. };
  78425. /**
  78426. * Get the euler rotation of the bone in local or world space
  78427. * @param space The space that the rotation should be in
  78428. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78429. * @returns The euler rotation
  78430. */
  78431. Bone.prototype.getRotation = function (space, mesh) {
  78432. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78433. if (mesh === void 0) { mesh = null; }
  78434. var result = BABYLON.Vector3.Zero();
  78435. this.getRotationToRef(space, mesh, result);
  78436. return result;
  78437. };
  78438. /**
  78439. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78440. * @param space The space that the rotation should be in
  78441. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78442. * @param result The vector3 that the rotation should be copied to
  78443. */
  78444. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78445. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78446. if (mesh === void 0) { mesh = null; }
  78447. var quat = Bone._tmpQuat;
  78448. this.getRotationQuaternionToRef(space, mesh, quat);
  78449. quat.toEulerAnglesToRef(result);
  78450. };
  78451. /**
  78452. * Get the quaternion rotation of the bone in either local or world space
  78453. * @param space The space that the rotation should be in
  78454. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78455. * @returns The quaternion rotation
  78456. */
  78457. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78458. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78459. if (mesh === void 0) { mesh = null; }
  78460. var result = BABYLON.Quaternion.Identity();
  78461. this.getRotationQuaternionToRef(space, mesh, result);
  78462. return result;
  78463. };
  78464. /**
  78465. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78466. * @param space The space that the rotation should be in
  78467. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78468. * @param result The quaternion that the rotation should be copied to
  78469. */
  78470. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78471. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78472. if (mesh === void 0) { mesh = null; }
  78473. if (space == BABYLON.Space.LOCAL) {
  78474. this._decompose();
  78475. result.copyFrom(this._localRotation);
  78476. }
  78477. else {
  78478. var mat = Bone._tmpMats[0];
  78479. var amat = this.getAbsoluteTransform();
  78480. if (mesh) {
  78481. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78482. }
  78483. else {
  78484. mat.copyFrom(amat);
  78485. }
  78486. mat.m[0] *= this._scalingDeterminant;
  78487. mat.m[1] *= this._scalingDeterminant;
  78488. mat.m[2] *= this._scalingDeterminant;
  78489. mat.decompose(undefined, result, undefined);
  78490. }
  78491. };
  78492. /**
  78493. * Get the rotation matrix of the bone in local or world space
  78494. * @param space The space that the rotation should be in
  78495. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78496. * @returns The rotation matrix
  78497. */
  78498. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78499. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78500. var result = BABYLON.Matrix.Identity();
  78501. this.getRotationMatrixToRef(space, mesh, result);
  78502. return result;
  78503. };
  78504. /**
  78505. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78506. * @param space The space that the rotation should be in
  78507. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78508. * @param result The quaternion that the rotation should be copied to
  78509. */
  78510. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78511. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78512. if (space == BABYLON.Space.LOCAL) {
  78513. this.getLocalMatrix().getRotationMatrixToRef(result);
  78514. }
  78515. else {
  78516. var mat = Bone._tmpMats[0];
  78517. var amat = this.getAbsoluteTransform();
  78518. if (mesh) {
  78519. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78520. }
  78521. else {
  78522. mat.copyFrom(amat);
  78523. }
  78524. mat.m[0] *= this._scalingDeterminant;
  78525. mat.m[1] *= this._scalingDeterminant;
  78526. mat.m[2] *= this._scalingDeterminant;
  78527. mat.getRotationMatrixToRef(result);
  78528. }
  78529. };
  78530. /**
  78531. * Get the world position of a point that is in the local space of the bone
  78532. * @param position The local position
  78533. * @param mesh The mesh that this bone is attached to
  78534. * @returns The world position
  78535. */
  78536. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78537. if (mesh === void 0) { mesh = null; }
  78538. var result = BABYLON.Vector3.Zero();
  78539. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78540. return result;
  78541. };
  78542. /**
  78543. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78544. * @param position The local position
  78545. * @param mesh The mesh that this bone is attached to
  78546. * @param result The vector3 that the world position should be copied to
  78547. */
  78548. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78549. if (mesh === void 0) { mesh = null; }
  78550. var wm = null;
  78551. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78552. if (mesh) {
  78553. wm = mesh.getWorldMatrix();
  78554. }
  78555. this._skeleton.computeAbsoluteTransforms();
  78556. var tmat = Bone._tmpMats[0];
  78557. if (mesh && wm) {
  78558. tmat.copyFrom(this.getAbsoluteTransform());
  78559. tmat.multiplyToRef(wm, tmat);
  78560. }
  78561. else {
  78562. tmat = this.getAbsoluteTransform();
  78563. }
  78564. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78565. };
  78566. /**
  78567. * Get the local position of a point that is in world space
  78568. * @param position The world position
  78569. * @param mesh The mesh that this bone is attached to
  78570. * @returns The local position
  78571. */
  78572. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78573. if (mesh === void 0) { mesh = null; }
  78574. var result = BABYLON.Vector3.Zero();
  78575. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78576. return result;
  78577. };
  78578. /**
  78579. * Get the local position of a point that is in world space and copy it to the result param
  78580. * @param position The world position
  78581. * @param mesh The mesh that this bone is attached to
  78582. * @param result The vector3 that the local position should be copied to
  78583. */
  78584. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78585. if (mesh === void 0) { mesh = null; }
  78586. var wm = null;
  78587. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78588. if (mesh) {
  78589. wm = mesh.getWorldMatrix();
  78590. }
  78591. this._skeleton.computeAbsoluteTransforms();
  78592. var tmat = Bone._tmpMats[0];
  78593. tmat.copyFrom(this.getAbsoluteTransform());
  78594. if (mesh && wm) {
  78595. tmat.multiplyToRef(wm, tmat);
  78596. }
  78597. tmat.invert();
  78598. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78599. };
  78600. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78601. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78602. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78603. return Bone;
  78604. }(BABYLON.Node));
  78605. BABYLON.Bone = Bone;
  78606. })(BABYLON || (BABYLON = {}));
  78607. //# sourceMappingURL=babylon.bone.js.map
  78608. var BABYLON;
  78609. (function (BABYLON) {
  78610. /**
  78611. * Class used to apply inverse kinematics to bones
  78612. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78613. */
  78614. var BoneIKController = /** @class */ (function () {
  78615. /**
  78616. * Creates a new BoneIKController
  78617. * @param mesh defines the mesh to control
  78618. * @param bone defines the bone to control
  78619. * @param options defines options to set up the controller
  78620. */
  78621. function BoneIKController(mesh, bone, options) {
  78622. /**
  78623. * Gets or sets the target position
  78624. */
  78625. this.targetPosition = BABYLON.Vector3.Zero();
  78626. /**
  78627. * Gets or sets the pole target position
  78628. */
  78629. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78630. /**
  78631. * Gets or sets the pole target local offset
  78632. */
  78633. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78634. /**
  78635. * Gets or sets the pole angle
  78636. */
  78637. this.poleAngle = 0;
  78638. /**
  78639. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)
  78640. */
  78641. this.slerpAmount = 1;
  78642. this._bone1Quat = BABYLON.Quaternion.Identity();
  78643. this._bone1Mat = BABYLON.Matrix.Identity();
  78644. this._bone2Ang = Math.PI;
  78645. this._maxAngle = Math.PI;
  78646. this._rightHandedSystem = false;
  78647. this._bendAxis = BABYLON.Vector3.Right();
  78648. this._slerping = false;
  78649. this._adjustRoll = 0;
  78650. this._bone2 = bone;
  78651. this._bone1 = bone.getParent();
  78652. if (!this._bone1) {
  78653. return;
  78654. }
  78655. this.mesh = mesh;
  78656. var bonePos = bone.getPosition();
  78657. if (bone.getAbsoluteTransform().determinant() > 0) {
  78658. this._rightHandedSystem = true;
  78659. this._bendAxis.x = 0;
  78660. this._bendAxis.y = 0;
  78661. this._bendAxis.z = -1;
  78662. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78663. this._adjustRoll = Math.PI * .5;
  78664. this._bendAxis.z = 1;
  78665. }
  78666. }
  78667. if (this._bone1.length) {
  78668. var boneScale1 = this._bone1.getScale();
  78669. var boneScale2 = this._bone2.getScale();
  78670. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78671. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78672. }
  78673. else if (this._bone1.children[0]) {
  78674. mesh.computeWorldMatrix(true);
  78675. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78676. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78677. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78678. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78679. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78680. }
  78681. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78682. this.maxAngle = Math.PI;
  78683. if (options) {
  78684. if (options.targetMesh) {
  78685. this.targetMesh = options.targetMesh;
  78686. this.targetMesh.computeWorldMatrix(true);
  78687. }
  78688. if (options.poleTargetMesh) {
  78689. this.poleTargetMesh = options.poleTargetMesh;
  78690. this.poleTargetMesh.computeWorldMatrix(true);
  78691. }
  78692. else if (options.poleTargetBone) {
  78693. this.poleTargetBone = options.poleTargetBone;
  78694. }
  78695. else if (this._bone1.getParent()) {
  78696. this.poleTargetBone = this._bone1.getParent();
  78697. }
  78698. if (options.poleTargetLocalOffset) {
  78699. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78700. }
  78701. if (options.poleAngle) {
  78702. this.poleAngle = options.poleAngle;
  78703. }
  78704. if (options.bendAxis) {
  78705. this._bendAxis.copyFrom(options.bendAxis);
  78706. }
  78707. if (options.maxAngle) {
  78708. this.maxAngle = options.maxAngle;
  78709. }
  78710. if (options.slerpAmount) {
  78711. this.slerpAmount = options.slerpAmount;
  78712. }
  78713. }
  78714. }
  78715. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78716. /**
  78717. * Gets or sets maximum allowed angle
  78718. */
  78719. get: function () {
  78720. return this._maxAngle;
  78721. },
  78722. set: function (value) {
  78723. this._setMaxAngle(value);
  78724. },
  78725. enumerable: true,
  78726. configurable: true
  78727. });
  78728. BoneIKController.prototype._setMaxAngle = function (ang) {
  78729. if (ang < 0) {
  78730. ang = 0;
  78731. }
  78732. if (ang > Math.PI || ang == undefined) {
  78733. ang = Math.PI;
  78734. }
  78735. this._maxAngle = ang;
  78736. var a = this._bone1Length;
  78737. var b = this._bone2Length;
  78738. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78739. };
  78740. /**
  78741. * Force the controller to update the bones
  78742. */
  78743. BoneIKController.prototype.update = function () {
  78744. var bone1 = this._bone1;
  78745. if (!bone1) {
  78746. return;
  78747. }
  78748. var target = this.targetPosition;
  78749. var poleTarget = this.poleTargetPosition;
  78750. var mat1 = BoneIKController._tmpMats[0];
  78751. var mat2 = BoneIKController._tmpMats[1];
  78752. if (this.targetMesh) {
  78753. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78754. }
  78755. if (this.poleTargetBone) {
  78756. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78757. }
  78758. else if (this.poleTargetMesh) {
  78759. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78760. }
  78761. var bonePos = BoneIKController._tmpVecs[0];
  78762. var zaxis = BoneIKController._tmpVecs[1];
  78763. var xaxis = BoneIKController._tmpVecs[2];
  78764. var yaxis = BoneIKController._tmpVecs[3];
  78765. var upAxis = BoneIKController._tmpVecs[4];
  78766. var _tmpQuat = BoneIKController._tmpQuat;
  78767. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78768. poleTarget.subtractToRef(bonePos, upAxis);
  78769. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78770. upAxis.y = 1;
  78771. }
  78772. else {
  78773. upAxis.normalize();
  78774. }
  78775. target.subtractToRef(bonePos, yaxis);
  78776. yaxis.normalize();
  78777. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78778. zaxis.normalize();
  78779. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78780. xaxis.normalize();
  78781. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78782. var a = this._bone1Length;
  78783. var b = this._bone2Length;
  78784. var c = BABYLON.Vector3.Distance(bonePos, target);
  78785. if (this._maxReach > 0) {
  78786. c = Math.min(this._maxReach, c);
  78787. }
  78788. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78789. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78790. if (acosa > 1) {
  78791. acosa = 1;
  78792. }
  78793. if (acosb > 1) {
  78794. acosb = 1;
  78795. }
  78796. if (acosa < -1) {
  78797. acosa = -1;
  78798. }
  78799. if (acosb < -1) {
  78800. acosb = -1;
  78801. }
  78802. var angA = Math.acos(acosa);
  78803. var angB = Math.acos(acosb);
  78804. var angC = -angA - angB;
  78805. if (this._rightHandedSystem) {
  78806. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78807. mat2.multiplyToRef(mat1, mat1);
  78808. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78809. mat2.multiplyToRef(mat1, mat1);
  78810. }
  78811. else {
  78812. var _tmpVec = BoneIKController._tmpVecs[5];
  78813. _tmpVec.copyFrom(this._bendAxis);
  78814. _tmpVec.x *= -1;
  78815. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78816. mat2.multiplyToRef(mat1, mat1);
  78817. }
  78818. if (this.poleAngle) {
  78819. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78820. mat1.multiplyToRef(mat2, mat1);
  78821. }
  78822. if (this._bone1) {
  78823. if (this.slerpAmount < 1) {
  78824. if (!this._slerping) {
  78825. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78826. }
  78827. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78828. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78829. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78830. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78831. this._slerping = true;
  78832. }
  78833. else {
  78834. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78835. this._bone1Mat.copyFrom(mat1);
  78836. this._slerping = false;
  78837. }
  78838. }
  78839. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78840. this._bone2Ang = angC;
  78841. };
  78842. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78843. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78844. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78845. return BoneIKController;
  78846. }());
  78847. BABYLON.BoneIKController = BoneIKController;
  78848. })(BABYLON || (BABYLON = {}));
  78849. //# sourceMappingURL=babylon.boneIKController.js.map
  78850. var BABYLON;
  78851. (function (BABYLON) {
  78852. /**
  78853. * Class used to make a bone look toward a point in space
  78854. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78855. */
  78856. var BoneLookController = /** @class */ (function () {
  78857. /**
  78858. * Create a BoneLookController
  78859. * @param mesh the mesh that the bone belongs to
  78860. * @param bone the bone that will be looking to the target
  78861. * @param target the target Vector3 to look at
  78862. * @param settings optional settings:
  78863. * * maxYaw: the maximum angle the bone will yaw to
  78864. * * minYaw: the minimum angle the bone will yaw to
  78865. * * maxPitch: the maximum angle the bone will pitch to
  78866. * * minPitch: the minimum angle the bone will yaw to
  78867. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78868. * * upAxis: the up axis of the coordinate system
  78869. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78870. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78871. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78872. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78873. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78874. * * adjustRoll: used to make an adjustment to the roll of the bone
  78875. **/
  78876. function BoneLookController(mesh, bone, target, options) {
  78877. /**
  78878. * The up axis of the coordinate system that is used when the bone is rotated
  78879. */
  78880. this.upAxis = BABYLON.Vector3.Up();
  78881. /**
  78882. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78883. */
  78884. this.upAxisSpace = BABYLON.Space.LOCAL;
  78885. /**
  78886. * Used to make an adjustment to the yaw of the bone
  78887. */
  78888. this.adjustYaw = 0;
  78889. /**
  78890. * Used to make an adjustment to the pitch of the bone
  78891. */
  78892. this.adjustPitch = 0;
  78893. /**
  78894. * Used to make an adjustment to the roll of the bone
  78895. */
  78896. this.adjustRoll = 0;
  78897. /**
  78898. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)
  78899. */
  78900. this.slerpAmount = 1;
  78901. this._boneQuat = BABYLON.Quaternion.Identity();
  78902. this._slerping = false;
  78903. this._firstFrameSkipped = false;
  78904. this._fowardAxis = BABYLON.Vector3.Forward();
  78905. this.mesh = mesh;
  78906. this.bone = bone;
  78907. this.target = target;
  78908. if (options) {
  78909. if (options.adjustYaw) {
  78910. this.adjustYaw = options.adjustYaw;
  78911. }
  78912. if (options.adjustPitch) {
  78913. this.adjustPitch = options.adjustPitch;
  78914. }
  78915. if (options.adjustRoll) {
  78916. this.adjustRoll = options.adjustRoll;
  78917. }
  78918. if (options.maxYaw != null) {
  78919. this.maxYaw = options.maxYaw;
  78920. }
  78921. else {
  78922. this.maxYaw = Math.PI;
  78923. }
  78924. if (options.minYaw != null) {
  78925. this.minYaw = options.minYaw;
  78926. }
  78927. else {
  78928. this.minYaw = -Math.PI;
  78929. }
  78930. if (options.maxPitch != null) {
  78931. this.maxPitch = options.maxPitch;
  78932. }
  78933. else {
  78934. this.maxPitch = Math.PI;
  78935. }
  78936. if (options.minPitch != null) {
  78937. this.minPitch = options.minPitch;
  78938. }
  78939. else {
  78940. this.minPitch = -Math.PI;
  78941. }
  78942. if (options.slerpAmount != null) {
  78943. this.slerpAmount = options.slerpAmount;
  78944. }
  78945. if (options.upAxis != null) {
  78946. this.upAxis = options.upAxis;
  78947. }
  78948. if (options.upAxisSpace != null) {
  78949. this.upAxisSpace = options.upAxisSpace;
  78950. }
  78951. if (options.yawAxis != null || options.pitchAxis != null) {
  78952. var newYawAxis = BABYLON.Axis.Y;
  78953. var newPitchAxis = BABYLON.Axis.X;
  78954. if (options.yawAxis != null) {
  78955. newYawAxis = options.yawAxis.clone();
  78956. newYawAxis.normalize();
  78957. }
  78958. if (options.pitchAxis != null) {
  78959. newPitchAxis = options.pitchAxis.clone();
  78960. newPitchAxis.normalize();
  78961. }
  78962. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78963. this._transformYawPitch = BABYLON.Matrix.Identity();
  78964. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78965. this._transformYawPitchInv = this._transformYawPitch.clone();
  78966. this._transformYawPitch.invert();
  78967. }
  78968. }
  78969. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78970. this.upAxisSpace = BABYLON.Space.LOCAL;
  78971. }
  78972. }
  78973. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78974. /**
  78975. * Gets or sets the minimum yaw angle that the bone can look to
  78976. */
  78977. get: function () {
  78978. return this._minYaw;
  78979. },
  78980. set: function (value) {
  78981. this._minYaw = value;
  78982. this._minYawSin = Math.sin(value);
  78983. this._minYawCos = Math.cos(value);
  78984. if (this._maxYaw != null) {
  78985. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78986. this._yawRange = this._maxYaw - this._minYaw;
  78987. }
  78988. },
  78989. enumerable: true,
  78990. configurable: true
  78991. });
  78992. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78993. /**
  78994. * Gets or sets the maximum yaw angle that the bone can look to
  78995. */
  78996. get: function () {
  78997. return this._maxYaw;
  78998. },
  78999. set: function (value) {
  79000. this._maxYaw = value;
  79001. this._maxYawSin = Math.sin(value);
  79002. this._maxYawCos = Math.cos(value);
  79003. if (this._minYaw != null) {
  79004. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79005. this._yawRange = this._maxYaw - this._minYaw;
  79006. }
  79007. },
  79008. enumerable: true,
  79009. configurable: true
  79010. });
  79011. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79012. /**
  79013. * Gets or sets the minimum pitch angle that the bone can look to
  79014. */
  79015. get: function () {
  79016. return this._minPitch;
  79017. },
  79018. set: function (value) {
  79019. this._minPitch = value;
  79020. this._minPitchTan = Math.tan(value);
  79021. },
  79022. enumerable: true,
  79023. configurable: true
  79024. });
  79025. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79026. /**
  79027. * Gets or sets the maximum pitch angle that the bone can look to
  79028. */
  79029. get: function () {
  79030. return this._maxPitch;
  79031. },
  79032. set: function (value) {
  79033. this._maxPitch = value;
  79034. this._maxPitchTan = Math.tan(value);
  79035. },
  79036. enumerable: true,
  79037. configurable: true
  79038. });
  79039. /**
  79040. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79041. */
  79042. BoneLookController.prototype.update = function () {
  79043. //skip the first frame when slerping so that the mesh rotation is correct
  79044. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79045. this._firstFrameSkipped = true;
  79046. return;
  79047. }
  79048. var bone = this.bone;
  79049. var bonePos = BoneLookController._tmpVecs[0];
  79050. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79051. var target = this.target;
  79052. var _tmpMat1 = BoneLookController._tmpMats[0];
  79053. var _tmpMat2 = BoneLookController._tmpMats[1];
  79054. var mesh = this.mesh;
  79055. var parentBone = bone.getParent();
  79056. var upAxis = BoneLookController._tmpVecs[1];
  79057. upAxis.copyFrom(this.upAxis);
  79058. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79059. if (this._transformYawPitch) {
  79060. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79061. }
  79062. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79063. }
  79064. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79065. mesh.getDirectionToRef(upAxis, upAxis);
  79066. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79067. upAxis.normalize();
  79068. }
  79069. }
  79070. var checkYaw = false;
  79071. var checkPitch = false;
  79072. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79073. checkYaw = true;
  79074. }
  79075. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79076. checkPitch = true;
  79077. }
  79078. if (checkYaw || checkPitch) {
  79079. var spaceMat = BoneLookController._tmpMats[2];
  79080. var spaceMatInv = BoneLookController._tmpMats[3];
  79081. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79082. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79083. }
  79084. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79085. spaceMat.copyFrom(mesh.getWorldMatrix());
  79086. }
  79087. else {
  79088. var forwardAxis = BoneLookController._tmpVecs[2];
  79089. forwardAxis.copyFrom(this._fowardAxis);
  79090. if (this._transformYawPitch) {
  79091. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79092. }
  79093. if (parentBone) {
  79094. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79095. }
  79096. else {
  79097. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79098. }
  79099. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79100. rightAxis.normalize();
  79101. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79102. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79103. }
  79104. spaceMat.invertToRef(spaceMatInv);
  79105. var xzlen = null;
  79106. if (checkPitch) {
  79107. var localTarget = BoneLookController._tmpVecs[3];
  79108. target.subtractToRef(bonePos, localTarget);
  79109. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79110. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79111. var pitch = Math.atan2(localTarget.y, xzlen);
  79112. var newPitch = pitch;
  79113. if (pitch > this._maxPitch) {
  79114. localTarget.y = this._maxPitchTan * xzlen;
  79115. newPitch = this._maxPitch;
  79116. }
  79117. else if (pitch < this._minPitch) {
  79118. localTarget.y = this._minPitchTan * xzlen;
  79119. newPitch = this._minPitch;
  79120. }
  79121. if (pitch != newPitch) {
  79122. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79123. localTarget.addInPlace(bonePos);
  79124. target = localTarget;
  79125. }
  79126. }
  79127. if (checkYaw) {
  79128. var localTarget = BoneLookController._tmpVecs[4];
  79129. target.subtractToRef(bonePos, localTarget);
  79130. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79131. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79132. var newYaw = yaw;
  79133. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79134. if (xzlen == null) {
  79135. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79136. }
  79137. if (this._yawRange > Math.PI) {
  79138. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79139. localTarget.z = this._maxYawCos * xzlen;
  79140. localTarget.x = this._maxYawSin * xzlen;
  79141. newYaw = this._maxYaw;
  79142. }
  79143. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79144. localTarget.z = this._minYawCos * xzlen;
  79145. localTarget.x = this._minYawSin * xzlen;
  79146. newYaw = this._minYaw;
  79147. }
  79148. }
  79149. else {
  79150. if (yaw > this._maxYaw) {
  79151. localTarget.z = this._maxYawCos * xzlen;
  79152. localTarget.x = this._maxYawSin * xzlen;
  79153. newYaw = this._maxYaw;
  79154. }
  79155. else if (yaw < this._minYaw) {
  79156. localTarget.z = this._minYawCos * xzlen;
  79157. localTarget.x = this._minYawSin * xzlen;
  79158. newYaw = this._minYaw;
  79159. }
  79160. }
  79161. }
  79162. if (this._slerping && this._yawRange > Math.PI) {
  79163. //are we going to be crossing into the min/max region?
  79164. var boneFwd = BoneLookController._tmpVecs[8];
  79165. boneFwd.copyFrom(BABYLON.Axis.Z);
  79166. if (this._transformYawPitch) {
  79167. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79168. }
  79169. var boneRotMat = BoneLookController._tmpMats[4];
  79170. this._boneQuat.toRotationMatrix(boneRotMat);
  79171. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79172. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79173. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79174. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79175. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79176. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79177. if (angBtwTar > angBtwMidYaw) {
  79178. if (xzlen == null) {
  79179. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79180. }
  79181. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79182. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79183. if (angBtwMin < angBtwMax) {
  79184. newYaw = boneYaw + Math.PI * .75;
  79185. localTarget.z = Math.cos(newYaw) * xzlen;
  79186. localTarget.x = Math.sin(newYaw) * xzlen;
  79187. }
  79188. else {
  79189. newYaw = boneYaw - Math.PI * .75;
  79190. localTarget.z = Math.cos(newYaw) * xzlen;
  79191. localTarget.x = Math.sin(newYaw) * xzlen;
  79192. }
  79193. }
  79194. }
  79195. if (yaw != newYaw) {
  79196. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79197. localTarget.addInPlace(bonePos);
  79198. target = localTarget;
  79199. }
  79200. }
  79201. }
  79202. var zaxis = BoneLookController._tmpVecs[5];
  79203. var xaxis = BoneLookController._tmpVecs[6];
  79204. var yaxis = BoneLookController._tmpVecs[7];
  79205. var _tmpQuat = BoneLookController._tmpQuat;
  79206. target.subtractToRef(bonePos, zaxis);
  79207. zaxis.normalize();
  79208. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79209. xaxis.normalize();
  79210. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79211. yaxis.normalize();
  79212. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79213. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79214. return;
  79215. }
  79216. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79217. return;
  79218. }
  79219. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79220. return;
  79221. }
  79222. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79223. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79224. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79225. }
  79226. if (this.slerpAmount < 1) {
  79227. if (!this._slerping) {
  79228. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79229. }
  79230. if (this._transformYawPitch) {
  79231. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79232. }
  79233. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79234. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79235. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79236. this._slerping = true;
  79237. }
  79238. else {
  79239. if (this._transformYawPitch) {
  79240. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79241. }
  79242. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79243. this._slerping = false;
  79244. }
  79245. };
  79246. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79247. var angDiff = ang2 - ang1;
  79248. angDiff %= Math.PI * 2;
  79249. if (angDiff > Math.PI) {
  79250. angDiff -= Math.PI * 2;
  79251. }
  79252. else if (angDiff < -Math.PI) {
  79253. angDiff += Math.PI * 2;
  79254. }
  79255. return angDiff;
  79256. };
  79257. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79258. ang1 %= (2 * Math.PI);
  79259. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79260. ang2 %= (2 * Math.PI);
  79261. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79262. var ab = 0;
  79263. if (ang1 < ang2) {
  79264. ab = ang2 - ang1;
  79265. }
  79266. else {
  79267. ab = ang1 - ang2;
  79268. }
  79269. if (ab > Math.PI) {
  79270. ab = Math.PI * 2 - ab;
  79271. }
  79272. return ab;
  79273. };
  79274. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79275. ang %= (2 * Math.PI);
  79276. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79277. ang1 %= (2 * Math.PI);
  79278. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79279. ang2 %= (2 * Math.PI);
  79280. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79281. if (ang1 < ang2) {
  79282. if (ang > ang1 && ang < ang2) {
  79283. return true;
  79284. }
  79285. }
  79286. else {
  79287. if (ang > ang2 && ang < ang1) {
  79288. return true;
  79289. }
  79290. }
  79291. return false;
  79292. };
  79293. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79294. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79295. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79296. return BoneLookController;
  79297. }());
  79298. BABYLON.BoneLookController = BoneLookController;
  79299. })(BABYLON || (BABYLON = {}));
  79300. //# sourceMappingURL=babylon.boneLookController.js.map
  79301. var BABYLON;
  79302. (function (BABYLON) {
  79303. /**
  79304. * Class used to handle skinning animations
  79305. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79306. */
  79307. var Skeleton = /** @class */ (function () {
  79308. /**
  79309. * Creates a new skeleton
  79310. * @param name defines the skeleton name
  79311. * @param id defines the skeleton Id
  79312. * @param scene defines the hosting scene
  79313. */
  79314. function Skeleton(
  79315. /** defines the skeleton name */
  79316. name,
  79317. /** defines the skeleton Id */
  79318. id, scene) {
  79319. this.name = name;
  79320. this.id = id;
  79321. /**
  79322. * Gets the list of child bones
  79323. */
  79324. this.bones = new Array();
  79325. /**
  79326. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79327. */
  79328. this.needInitialSkinMatrix = false;
  79329. this._isDirty = true;
  79330. this._meshesWithPoseMatrix = new Array();
  79331. this._identity = BABYLON.Matrix.Identity();
  79332. this._ranges = {};
  79333. this._lastAbsoluteTransformsUpdateId = -1;
  79334. /**
  79335. * Specifies if the skeleton should be serialized
  79336. */
  79337. this.doNotSerialize = false;
  79338. this._animationPropertiesOverride = null;
  79339. // Events
  79340. /**
  79341. * An observable triggered before computing the skeleton's matrices
  79342. */
  79343. this.onBeforeComputeObservable = new BABYLON.Observable();
  79344. this.bones = [];
  79345. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79346. scene.skeletons.push(this);
  79347. //make sure it will recalculate the matrix next time prepare is called.
  79348. this._isDirty = true;
  79349. }
  79350. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79351. /**
  79352. * Gets or sets the animation properties override
  79353. */
  79354. get: function () {
  79355. if (!this._animationPropertiesOverride) {
  79356. return this._scene.animationPropertiesOverride;
  79357. }
  79358. return this._animationPropertiesOverride;
  79359. },
  79360. set: function (value) {
  79361. this._animationPropertiesOverride = value;
  79362. },
  79363. enumerable: true,
  79364. configurable: true
  79365. });
  79366. // Members
  79367. /**
  79368. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79369. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79370. * @returns a Float32Array containing matrices data
  79371. */
  79372. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79373. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79374. return mesh._bonesTransformMatrices;
  79375. }
  79376. if (!this._transformMatrices) {
  79377. this.prepare();
  79378. }
  79379. return this._transformMatrices;
  79380. };
  79381. /**
  79382. * Gets the current hosting scene
  79383. * @returns a scene object
  79384. */
  79385. Skeleton.prototype.getScene = function () {
  79386. return this._scene;
  79387. };
  79388. // Methods
  79389. /**
  79390. * Gets a string representing the current skeleton data
  79391. * @param fullDetails defines a boolean indicating if we want a verbose version
  79392. * @returns a string representing the current skeleton data
  79393. */
  79394. Skeleton.prototype.toString = function (fullDetails) {
  79395. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79396. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79397. if (fullDetails) {
  79398. ret += ", Ranges: {";
  79399. var first = true;
  79400. for (var name_1 in this._ranges) {
  79401. if (first) {
  79402. ret += ", ";
  79403. first = false;
  79404. }
  79405. ret += name_1;
  79406. }
  79407. ret += "}";
  79408. }
  79409. return ret;
  79410. };
  79411. /**
  79412. * Get bone's index searching by name
  79413. * @param name defines bone's name to search for
  79414. * @return the indice of the bone. Returns -1 if not found
  79415. */
  79416. Skeleton.prototype.getBoneIndexByName = function (name) {
  79417. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79418. if (this.bones[boneIndex].name === name) {
  79419. return boneIndex;
  79420. }
  79421. }
  79422. return -1;
  79423. };
  79424. /**
  79425. * Creater a new animation range
  79426. * @param name defines the name of the range
  79427. * @param from defines the start key
  79428. * @param to defines the end key
  79429. */
  79430. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79431. // check name not already in use
  79432. if (!this._ranges[name]) {
  79433. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79434. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79435. if (this.bones[i].animations[0]) {
  79436. this.bones[i].animations[0].createRange(name, from, to);
  79437. }
  79438. }
  79439. }
  79440. };
  79441. /**
  79442. * Delete a specific animation range
  79443. * @param name defines the name of the range
  79444. * @param deleteFrames defines if frames must be removed as well
  79445. */
  79446. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79447. if (deleteFrames === void 0) { deleteFrames = true; }
  79448. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79449. if (this.bones[i].animations[0]) {
  79450. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79451. }
  79452. }
  79453. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79454. };
  79455. /**
  79456. * Gets a specific animation range
  79457. * @param name defines the name of the range to look for
  79458. * @returns the requested animation range or null if not found
  79459. */
  79460. Skeleton.prototype.getAnimationRange = function (name) {
  79461. return this._ranges[name];
  79462. };
  79463. /**
  79464. * Gets the list of all animation ranges defined on this skeleton
  79465. * @returns an array
  79466. */
  79467. Skeleton.prototype.getAnimationRanges = function () {
  79468. var animationRanges = [];
  79469. var name;
  79470. var i = 0;
  79471. for (name in this._ranges) {
  79472. animationRanges[i] = this._ranges[name];
  79473. i++;
  79474. }
  79475. return animationRanges;
  79476. };
  79477. /**
  79478. * Copy animation range from a source skeleton.
  79479. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79480. * @param source defines the source skeleton
  79481. * @param name defines the name of the range to copy
  79482. * @param rescaleAsRequired defines if rescaling must be applied if required
  79483. * @returns true if operation was successful
  79484. */
  79485. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79486. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79487. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79488. return false;
  79489. }
  79490. var ret = true;
  79491. var frameOffset = this._getHighestAnimationFrame() + 1;
  79492. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79493. var boneDict = {};
  79494. var sourceBones = source.bones;
  79495. var nBones;
  79496. var i;
  79497. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79498. boneDict[sourceBones[i].name] = sourceBones[i];
  79499. }
  79500. if (this.bones.length !== sourceBones.length) {
  79501. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79502. ret = false;
  79503. }
  79504. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79505. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79506. var boneName = this.bones[i].name;
  79507. var sourceBone = boneDict[boneName];
  79508. if (sourceBone) {
  79509. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79510. }
  79511. else {
  79512. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79513. ret = false;
  79514. }
  79515. }
  79516. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79517. var range = source.getAnimationRange(name);
  79518. if (range) {
  79519. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79520. }
  79521. return ret;
  79522. };
  79523. /**
  79524. * Forces the skeleton to go to rest pose
  79525. */
  79526. Skeleton.prototype.returnToRest = function () {
  79527. for (var index = 0; index < this.bones.length; index++) {
  79528. this.bones[index].returnToRest();
  79529. }
  79530. };
  79531. Skeleton.prototype._getHighestAnimationFrame = function () {
  79532. var ret = 0;
  79533. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79534. if (this.bones[i].animations[0]) {
  79535. var highest = this.bones[i].animations[0].getHighestFrame();
  79536. if (ret < highest) {
  79537. ret = highest;
  79538. }
  79539. }
  79540. }
  79541. return ret;
  79542. };
  79543. /**
  79544. * Begin a specific animation range
  79545. * @param name defines the name of the range to start
  79546. * @param loop defines if looping must be turned on (false by default)
  79547. * @param speedRatio defines the speed ratio to apply (1 by default)
  79548. * @param onAnimationEnd defines a callback which will be called when animation will end
  79549. * @returns a new animatable
  79550. */
  79551. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79552. var range = this.getAnimationRange(name);
  79553. if (!range) {
  79554. return null;
  79555. }
  79556. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79557. };
  79558. /** @hidden */
  79559. Skeleton.prototype._markAsDirty = function () {
  79560. this._isDirty = true;
  79561. };
  79562. /** @hidden */
  79563. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79564. this._meshesWithPoseMatrix.push(mesh);
  79565. };
  79566. /** @hidden */
  79567. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79568. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79569. if (index > -1) {
  79570. this._meshesWithPoseMatrix.splice(index, 1);
  79571. }
  79572. };
  79573. /** @hidden */
  79574. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79575. this.onBeforeComputeObservable.notifyObservers(this);
  79576. for (var index = 0; index < this.bones.length; index++) {
  79577. var bone = this.bones[index];
  79578. var parentBone = bone.getParent();
  79579. if (parentBone) {
  79580. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79581. }
  79582. else {
  79583. if (initialSkinMatrix) {
  79584. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79585. }
  79586. else {
  79587. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79588. }
  79589. }
  79590. if (bone._index !== -1) {
  79591. var mappedIndex = bone._index === null ? index : bone._index;
  79592. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79593. }
  79594. }
  79595. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79596. };
  79597. /**
  79598. * Build all resources required to render a skeleton
  79599. */
  79600. Skeleton.prototype.prepare = function () {
  79601. if (!this._isDirty) {
  79602. return;
  79603. }
  79604. if (this.needInitialSkinMatrix) {
  79605. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79606. var mesh = this._meshesWithPoseMatrix[index];
  79607. var poseMatrix = mesh.getPoseMatrix();
  79608. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79609. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79610. }
  79611. if (this._synchronizedWithMesh !== mesh) {
  79612. this._synchronizedWithMesh = mesh;
  79613. // Prepare bones
  79614. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79615. var bone = this.bones[boneIndex];
  79616. if (!bone.getParent()) {
  79617. var matrix = bone.getBaseMatrix();
  79618. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79619. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79620. }
  79621. }
  79622. }
  79623. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79624. }
  79625. }
  79626. else {
  79627. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79628. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79629. }
  79630. this._computeTransformMatrices(this._transformMatrices, null);
  79631. }
  79632. this._isDirty = false;
  79633. this._scene._activeBones.addCount(this.bones.length, false);
  79634. };
  79635. /**
  79636. * Gets the list of animatables currently running for this skeleton
  79637. * @returns an array of animatables
  79638. */
  79639. Skeleton.prototype.getAnimatables = function () {
  79640. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79641. this._animatables = [];
  79642. for (var index = 0; index < this.bones.length; index++) {
  79643. this._animatables.push(this.bones[index]);
  79644. }
  79645. }
  79646. return this._animatables;
  79647. };
  79648. /**
  79649. * Clone the current skeleton
  79650. * @param name defines the name of the new skeleton
  79651. * @param id defines the id of the enw skeleton
  79652. * @returns the new skeleton
  79653. */
  79654. Skeleton.prototype.clone = function (name, id) {
  79655. var result = new Skeleton(name, id || name, this._scene);
  79656. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79657. for (var index = 0; index < this.bones.length; index++) {
  79658. var source = this.bones[index];
  79659. var parentBone = null;
  79660. var parent_1 = source.getParent();
  79661. if (parent_1) {
  79662. var parentIndex = this.bones.indexOf(parent_1);
  79663. parentBone = result.bones[parentIndex];
  79664. }
  79665. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79666. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79667. }
  79668. if (this._ranges) {
  79669. result._ranges = {};
  79670. for (var rangeName in this._ranges) {
  79671. var range = this._ranges[rangeName];
  79672. if (range) {
  79673. result._ranges[rangeName] = range.clone();
  79674. }
  79675. }
  79676. }
  79677. this._isDirty = true;
  79678. return result;
  79679. };
  79680. /**
  79681. * Enable animation blending for this skeleton
  79682. * @param blendingSpeed defines the blending speed to apply
  79683. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79684. */
  79685. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79686. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79687. this.bones.forEach(function (bone) {
  79688. bone.animations.forEach(function (animation) {
  79689. animation.enableBlending = true;
  79690. animation.blendingSpeed = blendingSpeed;
  79691. });
  79692. });
  79693. };
  79694. /**
  79695. * Releases all resources associated with the current skeleton
  79696. */
  79697. Skeleton.prototype.dispose = function () {
  79698. this._meshesWithPoseMatrix = [];
  79699. // Animations
  79700. this.getScene().stopAnimation(this);
  79701. // Remove from scene
  79702. this.getScene().removeSkeleton(this);
  79703. };
  79704. /**
  79705. * Serialize the skeleton in a JSON object
  79706. * @returns a JSON object
  79707. */
  79708. Skeleton.prototype.serialize = function () {
  79709. var serializationObject = {};
  79710. serializationObject.name = this.name;
  79711. serializationObject.id = this.id;
  79712. if (this.dimensionsAtRest) {
  79713. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79714. }
  79715. serializationObject.bones = [];
  79716. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79717. for (var index = 0; index < this.bones.length; index++) {
  79718. var bone = this.bones[index];
  79719. var parent_2 = bone.getParent();
  79720. var serializedBone = {
  79721. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79722. name: bone.name,
  79723. matrix: bone.getBaseMatrix().toArray(),
  79724. rest: bone.getRestPose().toArray()
  79725. };
  79726. serializationObject.bones.push(serializedBone);
  79727. if (bone.length) {
  79728. serializedBone.length = bone.length;
  79729. }
  79730. if (bone.metadata) {
  79731. serializedBone.metadata = bone.metadata;
  79732. }
  79733. if (bone.animations && bone.animations.length > 0) {
  79734. serializedBone.animation = bone.animations[0].serialize();
  79735. }
  79736. serializationObject.ranges = [];
  79737. for (var name in this._ranges) {
  79738. var source = this._ranges[name];
  79739. if (!source) {
  79740. continue;
  79741. }
  79742. var range = {};
  79743. range.name = name;
  79744. range.from = source.from;
  79745. range.to = source.to;
  79746. serializationObject.ranges.push(range);
  79747. }
  79748. }
  79749. return serializationObject;
  79750. };
  79751. /**
  79752. * Creates a new skeleton from serialized data
  79753. * @param parsedSkeleton defines the serialized data
  79754. * @param scene defines the hosting scene
  79755. * @returns a new skeleton
  79756. */
  79757. Skeleton.Parse = function (parsedSkeleton, scene) {
  79758. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79759. if (parsedSkeleton.dimensionsAtRest) {
  79760. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79761. }
  79762. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79763. var index;
  79764. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79765. var parsedBone = parsedSkeleton.bones[index];
  79766. var parentBone = null;
  79767. if (parsedBone.parentBoneIndex > -1) {
  79768. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79769. }
  79770. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79771. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79772. if (parsedBone.length) {
  79773. bone.length = parsedBone.length;
  79774. }
  79775. if (parsedBone.metadata) {
  79776. bone.metadata = parsedBone.metadata;
  79777. }
  79778. if (parsedBone.animation) {
  79779. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79780. }
  79781. }
  79782. // placed after bones, so createAnimationRange can cascade down
  79783. if (parsedSkeleton.ranges) {
  79784. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79785. var data = parsedSkeleton.ranges[index];
  79786. skeleton.createAnimationRange(data.name, data.from, data.to);
  79787. }
  79788. }
  79789. return skeleton;
  79790. };
  79791. /**
  79792. * Compute all node absolute transforms
  79793. * @param forceUpdate defines if computation must be done even if cache is up to date
  79794. */
  79795. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79796. if (forceUpdate === void 0) { forceUpdate = false; }
  79797. var renderId = this._scene.getRenderId();
  79798. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79799. this.bones[0].computeAbsoluteTransforms();
  79800. this._lastAbsoluteTransformsUpdateId = renderId;
  79801. }
  79802. };
  79803. /**
  79804. * Gets the root pose matrix
  79805. * @returns a matrix
  79806. */
  79807. Skeleton.prototype.getPoseMatrix = function () {
  79808. var poseMatrix = null;
  79809. if (this._meshesWithPoseMatrix.length > 0) {
  79810. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79811. }
  79812. return poseMatrix;
  79813. };
  79814. /**
  79815. * Sorts bones per internal index
  79816. */
  79817. Skeleton.prototype.sortBones = function () {
  79818. var bones = new Array();
  79819. var visited = new Array(this.bones.length);
  79820. for (var index = 0; index < this.bones.length; index++) {
  79821. this._sortBones(index, bones, visited);
  79822. }
  79823. this.bones = bones;
  79824. };
  79825. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79826. if (visited[index]) {
  79827. return;
  79828. }
  79829. visited[index] = true;
  79830. var bone = this.bones[index];
  79831. if (bone._index === undefined) {
  79832. bone._index = index;
  79833. }
  79834. var parentBone = bone.getParent();
  79835. if (parentBone) {
  79836. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79837. }
  79838. bones.push(bone);
  79839. };
  79840. return Skeleton;
  79841. }());
  79842. BABYLON.Skeleton = Skeleton;
  79843. })(BABYLON || (BABYLON = {}));
  79844. //# sourceMappingURL=babylon.skeleton.js.map
  79845. var BABYLON;
  79846. (function (BABYLON) {
  79847. var SphericalPolynomial = /** @class */ (function () {
  79848. function SphericalPolynomial() {
  79849. this.x = BABYLON.Vector3.Zero();
  79850. this.y = BABYLON.Vector3.Zero();
  79851. this.z = BABYLON.Vector3.Zero();
  79852. this.xx = BABYLON.Vector3.Zero();
  79853. this.yy = BABYLON.Vector3.Zero();
  79854. this.zz = BABYLON.Vector3.Zero();
  79855. this.xy = BABYLON.Vector3.Zero();
  79856. this.yz = BABYLON.Vector3.Zero();
  79857. this.zx = BABYLON.Vector3.Zero();
  79858. }
  79859. SphericalPolynomial.prototype.addAmbient = function (color) {
  79860. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79861. this.xx = this.xx.add(colorVector);
  79862. this.yy = this.yy.add(colorVector);
  79863. this.zz = this.zz.add(colorVector);
  79864. };
  79865. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79866. var result = new SphericalPolynomial();
  79867. result.x = harmonics.L11.scale(1.02333);
  79868. result.y = harmonics.L1_1.scale(1.02333);
  79869. result.z = harmonics.L10.scale(1.02333);
  79870. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79871. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79872. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79873. result.yz = harmonics.L2_1.scale(0.858086);
  79874. result.zx = harmonics.L21.scale(0.858086);
  79875. result.xy = harmonics.L2_2.scale(0.858086);
  79876. result.scale(1.0 / Math.PI);
  79877. return result;
  79878. };
  79879. SphericalPolynomial.prototype.scale = function (scale) {
  79880. this.x = this.x.scale(scale);
  79881. this.y = this.y.scale(scale);
  79882. this.z = this.z.scale(scale);
  79883. this.xx = this.xx.scale(scale);
  79884. this.yy = this.yy.scale(scale);
  79885. this.zz = this.zz.scale(scale);
  79886. this.yz = this.yz.scale(scale);
  79887. this.zx = this.zx.scale(scale);
  79888. this.xy = this.xy.scale(scale);
  79889. };
  79890. return SphericalPolynomial;
  79891. }());
  79892. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79893. var SphericalHarmonics = /** @class */ (function () {
  79894. function SphericalHarmonics() {
  79895. this.L00 = BABYLON.Vector3.Zero();
  79896. this.L1_1 = BABYLON.Vector3.Zero();
  79897. this.L10 = BABYLON.Vector3.Zero();
  79898. this.L11 = BABYLON.Vector3.Zero();
  79899. this.L2_2 = BABYLON.Vector3.Zero();
  79900. this.L2_1 = BABYLON.Vector3.Zero();
  79901. this.L20 = BABYLON.Vector3.Zero();
  79902. this.L21 = BABYLON.Vector3.Zero();
  79903. this.L22 = BABYLON.Vector3.Zero();
  79904. }
  79905. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79906. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79907. var c = colorVector.scale(deltaSolidAngle);
  79908. this.L00 = this.L00.add(c.scale(0.282095));
  79909. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79910. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79911. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79912. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79913. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79914. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79915. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79916. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79917. };
  79918. SphericalHarmonics.prototype.scale = function (scale) {
  79919. this.L00 = this.L00.scale(scale);
  79920. this.L1_1 = this.L1_1.scale(scale);
  79921. this.L10 = this.L10.scale(scale);
  79922. this.L11 = this.L11.scale(scale);
  79923. this.L2_2 = this.L2_2.scale(scale);
  79924. this.L2_1 = this.L2_1.scale(scale);
  79925. this.L20 = this.L20.scale(scale);
  79926. this.L21 = this.L21.scale(scale);
  79927. this.L22 = this.L22.scale(scale);
  79928. };
  79929. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79930. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79931. //
  79932. // E_lm = A_l * L_lm
  79933. //
  79934. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79935. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79936. // the scaling factors are given in equation 9.
  79937. // Constant (Band 0)
  79938. this.L00 = this.L00.scale(3.141593);
  79939. // Linear (Band 1)
  79940. this.L1_1 = this.L1_1.scale(2.094395);
  79941. this.L10 = this.L10.scale(2.094395);
  79942. this.L11 = this.L11.scale(2.094395);
  79943. // Quadratic (Band 2)
  79944. this.L2_2 = this.L2_2.scale(0.785398);
  79945. this.L2_1 = this.L2_1.scale(0.785398);
  79946. this.L20 = this.L20.scale(0.785398);
  79947. this.L21 = this.L21.scale(0.785398);
  79948. this.L22 = this.L22.scale(0.785398);
  79949. };
  79950. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79951. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79952. // L = (1/pi) * E * rho
  79953. //
  79954. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79955. this.scale(1.0 / Math.PI);
  79956. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79957. // (The pixel shader must apply albedo after texture fetches, etc).
  79958. };
  79959. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79960. var result = new SphericalHarmonics();
  79961. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79962. result.L1_1 = polynomial.y.scale(0.977204);
  79963. result.L10 = polynomial.z.scale(0.977204);
  79964. result.L11 = polynomial.x.scale(0.977204);
  79965. result.L2_2 = polynomial.xy.scale(1.16538);
  79966. result.L2_1 = polynomial.yz.scale(1.16538);
  79967. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79968. result.L21 = polynomial.zx.scale(1.16538);
  79969. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79970. result.scale(Math.PI);
  79971. return result;
  79972. };
  79973. return SphericalHarmonics;
  79974. }());
  79975. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79976. })(BABYLON || (BABYLON = {}));
  79977. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79978. var BABYLON;
  79979. (function (BABYLON) {
  79980. var FileFaceOrientation = /** @class */ (function () {
  79981. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79982. this.name = name;
  79983. this.worldAxisForNormal = worldAxisForNormal;
  79984. this.worldAxisForFileX = worldAxisForFileX;
  79985. this.worldAxisForFileY = worldAxisForFileY;
  79986. }
  79987. return FileFaceOrientation;
  79988. }());
  79989. ;
  79990. /**
  79991. * Helper class dealing with the extraction of spherical polynomial dataArray
  79992. * from a cube map.
  79993. */
  79994. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79995. function CubeMapToSphericalPolynomialTools() {
  79996. }
  79997. /**
  79998. * Converts a texture to the according Spherical Polynomial data.
  79999. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80000. *
  80001. * @param texture The texture to extract the information from.
  80002. * @return The Spherical Polynomial data.
  80003. */
  80004. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80005. if (!texture.isCube) {
  80006. // Only supports cube Textures currently.
  80007. return null;
  80008. }
  80009. var size = texture.getSize().width;
  80010. var right = texture.readPixels(0);
  80011. var left = texture.readPixels(1);
  80012. var up;
  80013. var down;
  80014. if (texture.isRenderTarget) {
  80015. up = texture.readPixels(3);
  80016. down = texture.readPixels(2);
  80017. }
  80018. else {
  80019. up = texture.readPixels(2);
  80020. down = texture.readPixels(3);
  80021. }
  80022. var front = texture.readPixels(4);
  80023. var back = texture.readPixels(5);
  80024. var gammaSpace = texture.gammaSpace;
  80025. // Always read as RGBA.
  80026. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80027. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80028. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80029. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80030. }
  80031. var cubeInfo = {
  80032. size: size,
  80033. right: right,
  80034. left: left,
  80035. up: up,
  80036. down: down,
  80037. front: front,
  80038. back: back,
  80039. format: format,
  80040. type: type,
  80041. gammaSpace: gammaSpace,
  80042. };
  80043. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80044. };
  80045. /**
  80046. * Converts a cubemap to the according Spherical Polynomial data.
  80047. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80048. *
  80049. * @param cubeInfo The Cube map to extract the information from.
  80050. * @return The Spherical Polynomial data.
  80051. */
  80052. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80053. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80054. var totalSolidAngle = 0.0;
  80055. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80056. var du = 2.0 / cubeInfo.size;
  80057. var dv = du;
  80058. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80059. var minUV = du * 0.5 - 1.0;
  80060. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80061. var fileFace = this.FileFaces[faceIndex];
  80062. var dataArray = cubeInfo[fileFace.name];
  80063. var v = minUV;
  80064. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80065. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80066. // Because SP is still linear, so summation is fine in that basis.
  80067. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80068. for (var y = 0; y < cubeInfo.size; y++) {
  80069. var u = minUV;
  80070. for (var x = 0; x < cubeInfo.size; x++) {
  80071. // World direction (not normalised)
  80072. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80073. worldDirection.normalize();
  80074. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80075. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80076. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80077. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80078. // Handle Integer types.
  80079. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80080. r /= 255;
  80081. g /= 255;
  80082. b /= 255;
  80083. }
  80084. // Handle Gamma space textures.
  80085. if (cubeInfo.gammaSpace) {
  80086. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80087. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80088. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80089. }
  80090. var color = new BABYLON.Color3(r, g, b);
  80091. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80092. totalSolidAngle += deltaSolidAngle;
  80093. u += du;
  80094. }
  80095. v += dv;
  80096. }
  80097. }
  80098. // Solid angle for entire sphere is 4*pi
  80099. var sphereSolidAngle = 4.0 * Math.PI;
  80100. // Adjust the solid angle to allow for how many faces we processed.
  80101. var facesProcessed = 6.0;
  80102. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80103. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80104. // This is needed because the numerical integration over the cube uses a
  80105. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80106. // and also to compensate for accumulative error due to float precision in the summation.
  80107. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80108. sphericalHarmonics.scale(correctionFactor);
  80109. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80110. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80111. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80112. };
  80113. CubeMapToSphericalPolynomialTools.FileFaces = [
  80114. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80115. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80116. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80117. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80118. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80119. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80120. ];
  80121. return CubeMapToSphericalPolynomialTools;
  80122. }());
  80123. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80124. })(BABYLON || (BABYLON = {}));
  80125. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80126. var BABYLON;
  80127. (function (BABYLON) {
  80128. /**
  80129. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80130. */
  80131. var PanoramaToCubeMapTools = /** @class */ (function () {
  80132. function PanoramaToCubeMapTools() {
  80133. }
  80134. /**
  80135. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80136. *
  80137. * @param float32Array The source data.
  80138. * @param inputWidth The width of the input panorama.
  80139. * @param inputhHeight The height of the input panorama.
  80140. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80141. * @return The cubemap data
  80142. */
  80143. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80144. if (!float32Array) {
  80145. throw "ConvertPanoramaToCubemap: input cannot be null";
  80146. }
  80147. if (float32Array.length != inputWidth * inputHeight * 3) {
  80148. throw "ConvertPanoramaToCubemap: input size is wrong";
  80149. }
  80150. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80151. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80152. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80153. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80154. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80155. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80156. return {
  80157. front: textureFront,
  80158. back: textureBack,
  80159. left: textureLeft,
  80160. right: textureRight,
  80161. up: textureUp,
  80162. down: textureDown,
  80163. size: size,
  80164. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80165. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80166. gammaSpace: false,
  80167. };
  80168. };
  80169. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80170. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80171. var textureArray = new Float32Array(buffer);
  80172. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80173. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80174. var dy = 1 / texSize;
  80175. var fy = 0;
  80176. for (var y = 0; y < texSize; y++) {
  80177. var xv1 = faceData[0];
  80178. var xv2 = faceData[2];
  80179. for (var x = 0; x < texSize; x++) {
  80180. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80181. v.normalize();
  80182. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80183. // 3 channels per pixels
  80184. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80185. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80186. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80187. xv1 = xv1.add(rotDX1);
  80188. xv2 = xv2.add(rotDX2);
  80189. }
  80190. fy += dy;
  80191. }
  80192. return textureArray;
  80193. };
  80194. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80195. var theta = Math.atan2(vDir.z, vDir.x);
  80196. var phi = Math.acos(vDir.y);
  80197. while (theta < -Math.PI)
  80198. theta += 2 * Math.PI;
  80199. while (theta > Math.PI)
  80200. theta -= 2 * Math.PI;
  80201. var dx = theta / Math.PI;
  80202. var dy = phi / Math.PI;
  80203. // recenter.
  80204. dx = dx * 0.5 + 0.5;
  80205. var px = Math.round(dx * inputWidth);
  80206. if (px < 0)
  80207. px = 0;
  80208. else if (px >= inputWidth)
  80209. px = inputWidth - 1;
  80210. var py = Math.round(dy * inputHeight);
  80211. if (py < 0)
  80212. py = 0;
  80213. else if (py >= inputHeight)
  80214. py = inputHeight - 1;
  80215. var inputY = (inputHeight - py - 1);
  80216. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80217. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80218. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80219. return {
  80220. r: r,
  80221. g: g,
  80222. b: b
  80223. };
  80224. };
  80225. PanoramaToCubeMapTools.FACE_FRONT = [
  80226. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80227. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80228. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80229. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80230. ];
  80231. PanoramaToCubeMapTools.FACE_BACK = [
  80232. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80233. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80234. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80235. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80236. ];
  80237. PanoramaToCubeMapTools.FACE_RIGHT = [
  80238. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80239. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80240. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80241. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80242. ];
  80243. PanoramaToCubeMapTools.FACE_LEFT = [
  80244. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80245. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80246. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80247. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80248. ];
  80249. PanoramaToCubeMapTools.FACE_DOWN = [
  80250. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80251. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80252. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80253. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80254. ];
  80255. PanoramaToCubeMapTools.FACE_UP = [
  80256. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80257. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80258. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80259. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80260. ];
  80261. return PanoramaToCubeMapTools;
  80262. }());
  80263. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80264. })(BABYLON || (BABYLON = {}));
  80265. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80266. var BABYLON;
  80267. (function (BABYLON) {
  80268. ;
  80269. /**
  80270. * This groups tools to convert HDR texture to native colors array.
  80271. */
  80272. var HDRTools = /** @class */ (function () {
  80273. function HDRTools() {
  80274. }
  80275. HDRTools.Ldexp = function (mantissa, exponent) {
  80276. if (exponent > 1023) {
  80277. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80278. }
  80279. if (exponent < -1074) {
  80280. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80281. }
  80282. return mantissa * Math.pow(2, exponent);
  80283. };
  80284. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80285. if (exponent > 0) { /*nonzero pixel*/
  80286. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80287. float32array[index + 0] = red * exponent;
  80288. float32array[index + 1] = green * exponent;
  80289. float32array[index + 2] = blue * exponent;
  80290. }
  80291. else {
  80292. float32array[index + 0] = 0;
  80293. float32array[index + 1] = 0;
  80294. float32array[index + 2] = 0;
  80295. }
  80296. };
  80297. HDRTools.readStringLine = function (uint8array, startIndex) {
  80298. var line = "";
  80299. var character = "";
  80300. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80301. character = String.fromCharCode(uint8array[i]);
  80302. if (character == "\n") {
  80303. break;
  80304. }
  80305. line += character;
  80306. }
  80307. return line;
  80308. };
  80309. /**
  80310. * Reads header information from an RGBE texture stored in a native array.
  80311. * More information on this format are available here:
  80312. * https://en.wikipedia.org/wiki/RGBE_image_format
  80313. *
  80314. * @param uint8array The binary file stored in native array.
  80315. * @return The header information.
  80316. */
  80317. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80318. var height = 0;
  80319. var width = 0;
  80320. var line = this.readStringLine(uint8array, 0);
  80321. if (line[0] != '#' || line[1] != '?') {
  80322. throw "Bad HDR Format.";
  80323. }
  80324. var endOfHeader = false;
  80325. var findFormat = false;
  80326. var lineIndex = 0;
  80327. do {
  80328. lineIndex += (line.length + 1);
  80329. line = this.readStringLine(uint8array, lineIndex);
  80330. if (line == "FORMAT=32-bit_rle_rgbe") {
  80331. findFormat = true;
  80332. }
  80333. else if (line.length == 0) {
  80334. endOfHeader = true;
  80335. }
  80336. } while (!endOfHeader);
  80337. if (!findFormat) {
  80338. throw "HDR Bad header format, unsupported FORMAT";
  80339. }
  80340. lineIndex += (line.length + 1);
  80341. line = this.readStringLine(uint8array, lineIndex);
  80342. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80343. var match = sizeRegexp.exec(line);
  80344. // TODO. Support +Y and -X if needed.
  80345. if (!match || match.length < 3) {
  80346. throw "HDR Bad header format, no size";
  80347. }
  80348. width = parseInt(match[2]);
  80349. height = parseInt(match[1]);
  80350. if (width < 8 || width > 0x7fff) {
  80351. throw "HDR Bad header format, unsupported size";
  80352. }
  80353. lineIndex += (line.length + 1);
  80354. return {
  80355. height: height,
  80356. width: width,
  80357. dataPosition: lineIndex
  80358. };
  80359. };
  80360. /**
  80361. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80362. * This RGBE texture needs to store the information as a panorama.
  80363. *
  80364. * More information on this format are available here:
  80365. * https://en.wikipedia.org/wiki/RGBE_image_format
  80366. *
  80367. * @param buffer The binary file stored in an array buffer.
  80368. * @param size The expected size of the extracted cubemap.
  80369. * @return The Cube Map information.
  80370. */
  80371. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80372. var uint8array = new Uint8Array(buffer);
  80373. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80374. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80375. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80376. return cubeMapData;
  80377. };
  80378. /**
  80379. * Returns the pixels data extracted from an RGBE texture.
  80380. * This pixels will be stored left to right up to down in the R G B order in one array.
  80381. *
  80382. * More information on this format are available here:
  80383. * https://en.wikipedia.org/wiki/RGBE_image_format
  80384. *
  80385. * @param uint8array The binary file stored in an array buffer.
  80386. * @param hdrInfo The header information of the file.
  80387. * @return The pixels data in RGB right to left up to down order.
  80388. */
  80389. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80390. // Keep for multi format supports.
  80391. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80392. };
  80393. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80394. var num_scanlines = hdrInfo.height;
  80395. var scanline_width = hdrInfo.width;
  80396. var a, b, c, d, count;
  80397. var dataIndex = hdrInfo.dataPosition;
  80398. var index = 0, endIndex = 0, i = 0;
  80399. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80400. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80401. // 3 channels of 4 bytes per pixel in float.
  80402. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80403. var resultArray = new Float32Array(resultBuffer);
  80404. // read in each successive scanline
  80405. while (num_scanlines > 0) {
  80406. a = uint8array[dataIndex++];
  80407. b = uint8array[dataIndex++];
  80408. c = uint8array[dataIndex++];
  80409. d = uint8array[dataIndex++];
  80410. if (a != 2 || b != 2 || (c & 0x80)) {
  80411. // this file is not run length encoded
  80412. throw "HDR Bad header format, not RLE";
  80413. }
  80414. if (((c << 8) | d) != scanline_width) {
  80415. throw "HDR Bad header format, wrong scan line width";
  80416. }
  80417. index = 0;
  80418. // read each of the four channels for the scanline into the buffer
  80419. for (i = 0; i < 4; i++) {
  80420. endIndex = (i + 1) * scanline_width;
  80421. while (index < endIndex) {
  80422. a = uint8array[dataIndex++];
  80423. b = uint8array[dataIndex++];
  80424. if (a > 128) {
  80425. // a run of the same value
  80426. count = a - 128;
  80427. if ((count == 0) || (count > endIndex - index)) {
  80428. throw "HDR Bad Format, bad scanline data (run)";
  80429. }
  80430. while (count-- > 0) {
  80431. scanLineArray[index++] = b;
  80432. }
  80433. }
  80434. else {
  80435. // a non-run
  80436. count = a;
  80437. if ((count == 0) || (count > endIndex - index)) {
  80438. throw "HDR Bad Format, bad scanline data (non-run)";
  80439. }
  80440. scanLineArray[index++] = b;
  80441. if (--count > 0) {
  80442. for (var j = 0; j < count; j++) {
  80443. scanLineArray[index++] = uint8array[dataIndex++];
  80444. }
  80445. }
  80446. }
  80447. }
  80448. }
  80449. // now convert data from buffer into floats
  80450. for (i = 0; i < scanline_width; i++) {
  80451. a = scanLineArray[i];
  80452. b = scanLineArray[i + scanline_width];
  80453. c = scanLineArray[i + 2 * scanline_width];
  80454. d = scanLineArray[i + 3 * scanline_width];
  80455. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80456. }
  80457. num_scanlines--;
  80458. }
  80459. return resultArray;
  80460. };
  80461. return HDRTools;
  80462. }());
  80463. BABYLON.HDRTools = HDRTools;
  80464. })(BABYLON || (BABYLON = {}));
  80465. //# sourceMappingURL=babylon.hdr.js.map
  80466. var BABYLON;
  80467. (function (BABYLON) {
  80468. /**
  80469. * This represents a texture coming from an HDR input.
  80470. *
  80471. * The only supported format is currently panorama picture stored in RGBE format.
  80472. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80473. */
  80474. var HDRCubeTexture = /** @class */ (function (_super) {
  80475. __extends(HDRCubeTexture, _super);
  80476. /**
  80477. * Instantiates an HDRTexture from the following parameters.
  80478. *
  80479. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80480. * @param scene The scene the texture will be used in
  80481. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80482. * @param noMipmap Forces to not generate the mipmap if true
  80483. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80484. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  80485. * @param reserved Reserved flag for internal use.
  80486. */
  80487. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80488. if (noMipmap === void 0) { noMipmap = false; }
  80489. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80490. if (gammaSpace === void 0) { gammaSpace = false; }
  80491. if (reserved === void 0) { reserved = false; }
  80492. if (onLoad === void 0) { onLoad = null; }
  80493. if (onError === void 0) { onError = null; }
  80494. var _this = _super.call(this, scene) || this;
  80495. _this._generateHarmonics = true;
  80496. _this._onLoad = null;
  80497. _this._onError = null;
  80498. /**
  80499. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80500. */
  80501. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80502. _this._isBlocking = true;
  80503. _this._rotationY = 0;
  80504. /**
  80505. * Gets or sets the center of the bounding box associated with the cube texture
  80506. * It must define where the camera used to render the texture was set
  80507. */
  80508. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80509. if (!url) {
  80510. return _this;
  80511. }
  80512. _this.name = url;
  80513. _this.url = url;
  80514. _this.hasAlpha = false;
  80515. _this.isCube = true;
  80516. _this._textureMatrix = BABYLON.Matrix.Identity();
  80517. _this._onLoad = onLoad;
  80518. _this._onError = onError;
  80519. _this.gammaSpace = gammaSpace;
  80520. _this._noMipmap = noMipmap;
  80521. _this._size = size;
  80522. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80523. if (!_this._texture) {
  80524. if (!scene.useDelayedTextureLoading) {
  80525. _this.loadTexture();
  80526. }
  80527. else {
  80528. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80529. }
  80530. }
  80531. return _this;
  80532. }
  80533. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80534. /**
  80535. * Gets wether or not the texture is blocking during loading.
  80536. */
  80537. get: function () {
  80538. return this._isBlocking;
  80539. },
  80540. /**
  80541. * Sets wether or not the texture is blocking during loading.
  80542. */
  80543. set: function (value) {
  80544. this._isBlocking = value;
  80545. },
  80546. enumerable: true,
  80547. configurable: true
  80548. });
  80549. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80550. /**
  80551. * Gets texture matrix rotation angle around Y axis radians.
  80552. */
  80553. get: function () {
  80554. return this._rotationY;
  80555. },
  80556. /**
  80557. * Sets texture matrix rotation angle around Y axis in radians.
  80558. */
  80559. set: function (value) {
  80560. this._rotationY = value;
  80561. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80562. },
  80563. enumerable: true,
  80564. configurable: true
  80565. });
  80566. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80567. get: function () {
  80568. return this._boundingBoxSize;
  80569. },
  80570. /**
  80571. * Gets or sets the size of the bounding box associated with the cube texture
  80572. * When defined, the cubemap will switch to local mode
  80573. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80574. * @example https://www.babylonjs-playground.com/#RNASML
  80575. */
  80576. set: function (value) {
  80577. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80578. return;
  80579. }
  80580. this._boundingBoxSize = value;
  80581. var scene = this.getScene();
  80582. if (scene) {
  80583. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80584. }
  80585. },
  80586. enumerable: true,
  80587. configurable: true
  80588. });
  80589. /**
  80590. * Occurs when the file is raw .hdr file.
  80591. */
  80592. HDRCubeTexture.prototype.loadTexture = function () {
  80593. var _this = this;
  80594. var callback = function (buffer) {
  80595. var scene = _this.getScene();
  80596. if (!scene) {
  80597. return null;
  80598. }
  80599. // Extract the raw linear data.
  80600. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80601. // Generate harmonics if needed.
  80602. if (_this._generateHarmonics) {
  80603. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80604. _this.sphericalPolynomial = sphericalPolynomial;
  80605. }
  80606. var results = [];
  80607. var byteArray = null;
  80608. // Push each faces.
  80609. for (var j = 0; j < 6; j++) {
  80610. // Create uintarray fallback.
  80611. if (!scene.getEngine().getCaps().textureFloat) {
  80612. // 3 channels of 1 bytes per pixel in bytes.
  80613. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80614. byteArray = new Uint8Array(byteBuffer);
  80615. }
  80616. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80617. // If special cases.
  80618. if (_this.gammaSpace || byteArray) {
  80619. for (var i = 0; i < _this._size * _this._size; i++) {
  80620. // Put in gamma space if requested.
  80621. if (_this.gammaSpace) {
  80622. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80623. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80624. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80625. }
  80626. // Convert to int texture for fallback.
  80627. if (byteArray) {
  80628. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80629. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80630. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80631. // May use luminance instead if the result is not accurate.
  80632. var max = Math.max(Math.max(r, g), b);
  80633. if (max > 255) {
  80634. var scale = 255 / max;
  80635. r *= scale;
  80636. g *= scale;
  80637. b *= scale;
  80638. }
  80639. byteArray[(i * 3) + 0] = r;
  80640. byteArray[(i * 3) + 1] = g;
  80641. byteArray[(i * 3) + 2] = b;
  80642. }
  80643. }
  80644. }
  80645. if (byteArray) {
  80646. results.push(byteArray);
  80647. }
  80648. else {
  80649. results.push(dataFace);
  80650. }
  80651. }
  80652. return results;
  80653. };
  80654. var scene = this.getScene();
  80655. if (scene) {
  80656. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  80657. }
  80658. };
  80659. HDRCubeTexture.prototype.clone = function () {
  80660. var scene = this.getScene();
  80661. if (!scene) {
  80662. return this;
  80663. }
  80664. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80665. // Base texture
  80666. newTexture.level = this.level;
  80667. newTexture.wrapU = this.wrapU;
  80668. newTexture.wrapV = this.wrapV;
  80669. newTexture.coordinatesIndex = this.coordinatesIndex;
  80670. newTexture.coordinatesMode = this.coordinatesMode;
  80671. return newTexture;
  80672. };
  80673. // Methods
  80674. HDRCubeTexture.prototype.delayLoad = function () {
  80675. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80676. return;
  80677. }
  80678. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80679. this._texture = this._getFromCache(this.url, this._noMipmap);
  80680. if (!this._texture) {
  80681. this.loadTexture();
  80682. }
  80683. };
  80684. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80685. return this._textureMatrix;
  80686. };
  80687. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80688. this._textureMatrix = value;
  80689. };
  80690. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80691. var texture = null;
  80692. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80693. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80694. texture.name = parsedTexture.name;
  80695. texture.hasAlpha = parsedTexture.hasAlpha;
  80696. texture.level = parsedTexture.level;
  80697. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80698. texture.isBlocking = parsedTexture.isBlocking;
  80699. }
  80700. if (texture) {
  80701. if (parsedTexture.boundingBoxPosition) {
  80702. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80703. }
  80704. if (parsedTexture.boundingBoxSize) {
  80705. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80706. }
  80707. if (parsedTexture.rotationY) {
  80708. texture.rotationY = parsedTexture.rotationY;
  80709. }
  80710. }
  80711. return texture;
  80712. };
  80713. HDRCubeTexture.prototype.serialize = function () {
  80714. if (!this.name) {
  80715. return null;
  80716. }
  80717. var serializationObject = {};
  80718. serializationObject.name = this.name;
  80719. serializationObject.hasAlpha = this.hasAlpha;
  80720. serializationObject.isCube = true;
  80721. serializationObject.level = this.level;
  80722. serializationObject.size = this._size;
  80723. serializationObject.coordinatesMode = this.coordinatesMode;
  80724. serializationObject.useInGammaSpace = this.gammaSpace;
  80725. serializationObject.generateHarmonics = this._generateHarmonics;
  80726. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80727. serializationObject.noMipmap = this._noMipmap;
  80728. serializationObject.isBlocking = this._isBlocking;
  80729. serializationObject.rotationY = this._rotationY;
  80730. return serializationObject;
  80731. };
  80732. HDRCubeTexture._facesMapping = [
  80733. "right",
  80734. "left",
  80735. "up",
  80736. "down",
  80737. "front",
  80738. "back"
  80739. ];
  80740. return HDRCubeTexture;
  80741. }(BABYLON.BaseTexture));
  80742. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80743. })(BABYLON || (BABYLON = {}));
  80744. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80745. var BABYLON;
  80746. (function (BABYLON) {
  80747. var IndexedVector2 = /** @class */ (function (_super) {
  80748. __extends(IndexedVector2, _super);
  80749. function IndexedVector2(original, index) {
  80750. var _this = _super.call(this, original.x, original.y) || this;
  80751. _this.index = index;
  80752. return _this;
  80753. }
  80754. return IndexedVector2;
  80755. }(BABYLON.Vector2));
  80756. var PolygonPoints = /** @class */ (function () {
  80757. function PolygonPoints() {
  80758. this.elements = new Array();
  80759. }
  80760. PolygonPoints.prototype.add = function (originalPoints) {
  80761. var _this = this;
  80762. var result = new Array();
  80763. originalPoints.forEach(function (point) {
  80764. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80765. var newPoint = new IndexedVector2(point, _this.elements.length);
  80766. result.push(newPoint);
  80767. _this.elements.push(newPoint);
  80768. }
  80769. });
  80770. return result;
  80771. };
  80772. PolygonPoints.prototype.computeBounds = function () {
  80773. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80774. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80775. this.elements.forEach(function (point) {
  80776. // x
  80777. if (point.x < lmin.x) {
  80778. lmin.x = point.x;
  80779. }
  80780. else if (point.x > lmax.x) {
  80781. lmax.x = point.x;
  80782. }
  80783. // y
  80784. if (point.y < lmin.y) {
  80785. lmin.y = point.y;
  80786. }
  80787. else if (point.y > lmax.y) {
  80788. lmax.y = point.y;
  80789. }
  80790. });
  80791. return {
  80792. min: lmin,
  80793. max: lmax,
  80794. width: lmax.x - lmin.x,
  80795. height: lmax.y - lmin.y
  80796. };
  80797. };
  80798. return PolygonPoints;
  80799. }());
  80800. var Polygon = /** @class */ (function () {
  80801. function Polygon() {
  80802. }
  80803. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80804. return [
  80805. new BABYLON.Vector2(xmin, ymin),
  80806. new BABYLON.Vector2(xmax, ymin),
  80807. new BABYLON.Vector2(xmax, ymax),
  80808. new BABYLON.Vector2(xmin, ymax)
  80809. ];
  80810. };
  80811. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80812. if (cx === void 0) { cx = 0; }
  80813. if (cy === void 0) { cy = 0; }
  80814. if (numberOfSides === void 0) { numberOfSides = 32; }
  80815. var result = new Array();
  80816. var angle = 0;
  80817. var increment = (Math.PI * 2) / numberOfSides;
  80818. for (var i = 0; i < numberOfSides; i++) {
  80819. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80820. angle -= increment;
  80821. }
  80822. return result;
  80823. };
  80824. Polygon.Parse = function (input) {
  80825. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80826. var i, result = [];
  80827. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80828. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80829. }
  80830. return result;
  80831. };
  80832. Polygon.StartingAt = function (x, y) {
  80833. return BABYLON.Path2.StartingAt(x, y);
  80834. };
  80835. return Polygon;
  80836. }());
  80837. BABYLON.Polygon = Polygon;
  80838. var PolygonMeshBuilder = /** @class */ (function () {
  80839. function PolygonMeshBuilder(name, contours, scene) {
  80840. this._points = new PolygonPoints();
  80841. this._outlinepoints = new PolygonPoints();
  80842. this._holes = new Array();
  80843. this._epoints = new Array();
  80844. this._eholes = new Array();
  80845. this._name = name;
  80846. this._scene = scene;
  80847. var points;
  80848. if (contours instanceof BABYLON.Path2) {
  80849. points = contours.getPoints();
  80850. }
  80851. else {
  80852. points = contours;
  80853. }
  80854. this._addToepoint(points);
  80855. this._points.add(points);
  80856. this._outlinepoints.add(points);
  80857. if (typeof earcut === 'undefined') {
  80858. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80859. }
  80860. }
  80861. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80862. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80863. var p = points_1[_i];
  80864. this._epoints.push(p.x, p.y);
  80865. }
  80866. };
  80867. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80868. this._points.add(hole);
  80869. var holepoints = new PolygonPoints();
  80870. holepoints.add(hole);
  80871. this._holes.push(holepoints);
  80872. this._eholes.push(this._epoints.length / 2);
  80873. this._addToepoint(hole);
  80874. return this;
  80875. };
  80876. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80877. var _this = this;
  80878. if (updatable === void 0) { updatable = false; }
  80879. if (depth === void 0) { depth = 0; }
  80880. var result = new BABYLON.Mesh(this._name, this._scene);
  80881. var normals = new Array();
  80882. var positions = new Array();
  80883. var uvs = new Array();
  80884. var bounds = this._points.computeBounds();
  80885. this._points.elements.forEach(function (p) {
  80886. normals.push(0, 1.0, 0);
  80887. positions.push(p.x, 0, p.y);
  80888. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80889. });
  80890. var indices = new Array();
  80891. var res = earcut(this._epoints, this._eholes, 2);
  80892. for (var i = 0; i < res.length; i++) {
  80893. indices.push(res[i]);
  80894. }
  80895. if (depth > 0) {
  80896. var positionscount = (positions.length / 3); //get the current pointcount
  80897. this._points.elements.forEach(function (p) {
  80898. normals.push(0, -1.0, 0);
  80899. positions.push(p.x, -depth, p.y);
  80900. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80901. });
  80902. var totalCount = indices.length;
  80903. for (var i = 0; i < totalCount; i += 3) {
  80904. var i0 = indices[i + 0];
  80905. var i1 = indices[i + 1];
  80906. var i2 = indices[i + 2];
  80907. indices.push(i2 + positionscount);
  80908. indices.push(i1 + positionscount);
  80909. indices.push(i0 + positionscount);
  80910. }
  80911. //Add the sides
  80912. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80913. this._holes.forEach(function (hole) {
  80914. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80915. });
  80916. }
  80917. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80918. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80919. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80920. result.setIndices(indices);
  80921. return result;
  80922. };
  80923. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80924. var StartIndex = positions.length / 3;
  80925. var ulength = 0;
  80926. for (var i = 0; i < points.elements.length; i++) {
  80927. var p = points.elements[i];
  80928. var p1;
  80929. if ((i + 1) > points.elements.length - 1) {
  80930. p1 = points.elements[0];
  80931. }
  80932. else {
  80933. p1 = points.elements[i + 1];
  80934. }
  80935. positions.push(p.x, 0, p.y);
  80936. positions.push(p.x, -depth, p.y);
  80937. positions.push(p1.x, 0, p1.y);
  80938. positions.push(p1.x, -depth, p1.y);
  80939. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80940. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80941. var v3 = v2.subtract(v1);
  80942. var v4 = new BABYLON.Vector3(0, 1, 0);
  80943. var vn = BABYLON.Vector3.Cross(v3, v4);
  80944. vn = vn.normalize();
  80945. uvs.push(ulength / bounds.width, 0);
  80946. uvs.push(ulength / bounds.width, 1);
  80947. ulength += v3.length();
  80948. uvs.push((ulength / bounds.width), 0);
  80949. uvs.push((ulength / bounds.width), 1);
  80950. if (!flip) {
  80951. normals.push(-vn.x, -vn.y, -vn.z);
  80952. normals.push(-vn.x, -vn.y, -vn.z);
  80953. normals.push(-vn.x, -vn.y, -vn.z);
  80954. normals.push(-vn.x, -vn.y, -vn.z);
  80955. indices.push(StartIndex);
  80956. indices.push(StartIndex + 1);
  80957. indices.push(StartIndex + 2);
  80958. indices.push(StartIndex + 1);
  80959. indices.push(StartIndex + 3);
  80960. indices.push(StartIndex + 2);
  80961. }
  80962. else {
  80963. normals.push(vn.x, vn.y, vn.z);
  80964. normals.push(vn.x, vn.y, vn.z);
  80965. normals.push(vn.x, vn.y, vn.z);
  80966. normals.push(vn.x, vn.y, vn.z);
  80967. indices.push(StartIndex);
  80968. indices.push(StartIndex + 2);
  80969. indices.push(StartIndex + 1);
  80970. indices.push(StartIndex + 1);
  80971. indices.push(StartIndex + 2);
  80972. indices.push(StartIndex + 3);
  80973. }
  80974. StartIndex += 4;
  80975. }
  80976. ;
  80977. };
  80978. return PolygonMeshBuilder;
  80979. }());
  80980. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80981. })(BABYLON || (BABYLON = {}));
  80982. //# sourceMappingURL=babylon.polygonMesh.js.map
  80983. var BABYLON;
  80984. (function (BABYLON) {
  80985. // Unique ID when we import meshes from Babylon to CSG
  80986. var currentCSGMeshId = 0;
  80987. // # class Vertex
  80988. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80989. // one to provide additional features like texture coordinates and vertex
  80990. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80991. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80992. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80993. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80994. // is not used anywhere else.
  80995. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80996. var Vertex = /** @class */ (function () {
  80997. function Vertex(pos, normal, uv) {
  80998. this.pos = pos;
  80999. this.normal = normal;
  81000. this.uv = uv;
  81001. }
  81002. Vertex.prototype.clone = function () {
  81003. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81004. };
  81005. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81006. // orientation of a polygon is flipped.
  81007. Vertex.prototype.flip = function () {
  81008. this.normal = this.normal.scale(-1);
  81009. };
  81010. // Create a new vertex between this vertex and `other` by linearly
  81011. // interpolating all properties using a parameter of `t`. Subclasses should
  81012. // override this to interpolate additional properties.
  81013. Vertex.prototype.interpolate = function (other, t) {
  81014. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  81015. };
  81016. return Vertex;
  81017. }());
  81018. // # class Plane
  81019. // Represents a plane in 3D space.
  81020. var Plane = /** @class */ (function () {
  81021. function Plane(normal, w) {
  81022. this.normal = normal;
  81023. this.w = w;
  81024. }
  81025. Plane.FromPoints = function (a, b, c) {
  81026. var v0 = c.subtract(a);
  81027. var v1 = b.subtract(a);
  81028. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81029. return null;
  81030. }
  81031. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81032. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81033. };
  81034. Plane.prototype.clone = function () {
  81035. return new Plane(this.normal.clone(), this.w);
  81036. };
  81037. Plane.prototype.flip = function () {
  81038. this.normal.scaleInPlace(-1);
  81039. this.w = -this.w;
  81040. };
  81041. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81042. // fragments in the appropriate lists. Coplanar polygons go into either
  81043. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81044. // respect to this plane. Polygons in front or in back of this plane go into
  81045. // either `front` or `back`.
  81046. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81047. var COPLANAR = 0;
  81048. var FRONT = 1;
  81049. var BACK = 2;
  81050. var SPANNING = 3;
  81051. // Classify each point as well as the entire polygon into one of the above
  81052. // four classes.
  81053. var polygonType = 0;
  81054. var types = [];
  81055. var i;
  81056. var t;
  81057. for (i = 0; i < polygon.vertices.length; i++) {
  81058. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81059. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81060. polygonType |= type;
  81061. types.push(type);
  81062. }
  81063. // Put the polygon in the correct list, splitting it when necessary.
  81064. switch (polygonType) {
  81065. case COPLANAR:
  81066. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81067. break;
  81068. case FRONT:
  81069. front.push(polygon);
  81070. break;
  81071. case BACK:
  81072. back.push(polygon);
  81073. break;
  81074. case SPANNING:
  81075. var f = [], b = [];
  81076. for (i = 0; i < polygon.vertices.length; i++) {
  81077. var j = (i + 1) % polygon.vertices.length;
  81078. var ti = types[i], tj = types[j];
  81079. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81080. if (ti !== BACK)
  81081. f.push(vi);
  81082. if (ti !== FRONT)
  81083. b.push(ti !== BACK ? vi.clone() : vi);
  81084. if ((ti | tj) === SPANNING) {
  81085. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81086. var v = vi.interpolate(vj, t);
  81087. f.push(v);
  81088. b.push(v.clone());
  81089. }
  81090. }
  81091. var poly;
  81092. if (f.length >= 3) {
  81093. poly = new Polygon(f, polygon.shared);
  81094. if (poly.plane)
  81095. front.push(poly);
  81096. }
  81097. if (b.length >= 3) {
  81098. poly = new Polygon(b, polygon.shared);
  81099. if (poly.plane)
  81100. back.push(poly);
  81101. }
  81102. break;
  81103. }
  81104. };
  81105. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81106. // point is on the plane.
  81107. Plane.EPSILON = 1e-5;
  81108. return Plane;
  81109. }());
  81110. // # class Polygon
  81111. // Represents a convex polygon. The vertices used to initialize a polygon must
  81112. // be coplanar and form a convex loop.
  81113. //
  81114. // Each convex polygon has a `shared` property, which is shared between all
  81115. // polygons that are clones of each other or were split from the same polygon.
  81116. // This can be used to define per-polygon properties (such as surface color).
  81117. var Polygon = /** @class */ (function () {
  81118. function Polygon(vertices, shared) {
  81119. this.vertices = vertices;
  81120. this.shared = shared;
  81121. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81122. }
  81123. Polygon.prototype.clone = function () {
  81124. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81125. return new Polygon(vertices, this.shared);
  81126. };
  81127. Polygon.prototype.flip = function () {
  81128. this.vertices.reverse().map(function (v) { v.flip(); });
  81129. this.plane.flip();
  81130. };
  81131. return Polygon;
  81132. }());
  81133. // # class Node
  81134. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81135. // by picking a polygon to split along. That polygon (and all other coplanar
  81136. // polygons) are added directly to that node and the other polygons are added to
  81137. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81138. // no distinction between internal and leaf nodes.
  81139. var Node = /** @class */ (function () {
  81140. function Node(polygons) {
  81141. this.plane = null;
  81142. this.front = null;
  81143. this.back = null;
  81144. this.polygons = new Array();
  81145. if (polygons) {
  81146. this.build(polygons);
  81147. }
  81148. }
  81149. Node.prototype.clone = function () {
  81150. var node = new Node();
  81151. node.plane = this.plane && this.plane.clone();
  81152. node.front = this.front && this.front.clone();
  81153. node.back = this.back && this.back.clone();
  81154. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81155. return node;
  81156. };
  81157. // Convert solid space to empty space and empty space to solid space.
  81158. Node.prototype.invert = function () {
  81159. for (var i = 0; i < this.polygons.length; i++) {
  81160. this.polygons[i].flip();
  81161. }
  81162. if (this.plane) {
  81163. this.plane.flip();
  81164. }
  81165. if (this.front) {
  81166. this.front.invert();
  81167. }
  81168. if (this.back) {
  81169. this.back.invert();
  81170. }
  81171. var temp = this.front;
  81172. this.front = this.back;
  81173. this.back = temp;
  81174. };
  81175. // Recursively remove all polygons in `polygons` that are inside this BSP
  81176. // tree.
  81177. Node.prototype.clipPolygons = function (polygons) {
  81178. if (!this.plane)
  81179. return polygons.slice();
  81180. var front = new Array(), back = new Array();
  81181. for (var i = 0; i < polygons.length; i++) {
  81182. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81183. }
  81184. if (this.front) {
  81185. front = this.front.clipPolygons(front);
  81186. }
  81187. if (this.back) {
  81188. back = this.back.clipPolygons(back);
  81189. }
  81190. else {
  81191. back = [];
  81192. }
  81193. return front.concat(back);
  81194. };
  81195. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81196. // `bsp`.
  81197. Node.prototype.clipTo = function (bsp) {
  81198. this.polygons = bsp.clipPolygons(this.polygons);
  81199. if (this.front)
  81200. this.front.clipTo(bsp);
  81201. if (this.back)
  81202. this.back.clipTo(bsp);
  81203. };
  81204. // Return a list of all polygons in this BSP tree.
  81205. Node.prototype.allPolygons = function () {
  81206. var polygons = this.polygons.slice();
  81207. if (this.front)
  81208. polygons = polygons.concat(this.front.allPolygons());
  81209. if (this.back)
  81210. polygons = polygons.concat(this.back.allPolygons());
  81211. return polygons;
  81212. };
  81213. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81214. // new polygons are filtered down to the bottom of the tree and become new
  81215. // nodes there. Each set of polygons is partitioned using the first polygon
  81216. // (no heuristic is used to pick a good split).
  81217. Node.prototype.build = function (polygons) {
  81218. if (!polygons.length)
  81219. return;
  81220. if (!this.plane)
  81221. this.plane = polygons[0].plane.clone();
  81222. var front = new Array(), back = new Array();
  81223. for (var i = 0; i < polygons.length; i++) {
  81224. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81225. }
  81226. if (front.length) {
  81227. if (!this.front)
  81228. this.front = new Node();
  81229. this.front.build(front);
  81230. }
  81231. if (back.length) {
  81232. if (!this.back)
  81233. this.back = new Node();
  81234. this.back.build(back);
  81235. }
  81236. };
  81237. return Node;
  81238. }());
  81239. var CSG = /** @class */ (function () {
  81240. function CSG() {
  81241. this.polygons = new Array();
  81242. }
  81243. // Convert BABYLON.Mesh to BABYLON.CSG
  81244. CSG.FromMesh = function (mesh) {
  81245. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81246. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81247. if (mesh instanceof BABYLON.Mesh) {
  81248. mesh.computeWorldMatrix(true);
  81249. matrix = mesh.getWorldMatrix();
  81250. meshPosition = mesh.position.clone();
  81251. meshRotation = mesh.rotation.clone();
  81252. if (mesh.rotationQuaternion) {
  81253. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81254. }
  81255. meshScaling = mesh.scaling.clone();
  81256. }
  81257. else {
  81258. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81259. }
  81260. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81261. var subMeshes = mesh.subMeshes;
  81262. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81263. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81264. vertices = [];
  81265. for (var j = 0; j < 3; j++) {
  81266. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81267. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81268. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81269. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81270. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81271. vertex = new Vertex(position, normal, uv);
  81272. vertices.push(vertex);
  81273. }
  81274. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81275. // To handle the case of degenerated triangle
  81276. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81277. if (polygon.plane)
  81278. polygons.push(polygon);
  81279. }
  81280. }
  81281. var csg = CSG.FromPolygons(polygons);
  81282. csg.matrix = matrix;
  81283. csg.position = meshPosition;
  81284. csg.rotation = meshRotation;
  81285. csg.scaling = meshScaling;
  81286. csg.rotationQuaternion = meshRotationQuaternion;
  81287. currentCSGMeshId++;
  81288. return csg;
  81289. };
  81290. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81291. CSG.FromPolygons = function (polygons) {
  81292. var csg = new CSG();
  81293. csg.polygons = polygons;
  81294. return csg;
  81295. };
  81296. CSG.prototype.clone = function () {
  81297. var csg = new CSG();
  81298. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81299. csg.copyTransformAttributes(this);
  81300. return csg;
  81301. };
  81302. CSG.prototype.union = function (csg) {
  81303. var a = new Node(this.clone().polygons);
  81304. var b = new Node(csg.clone().polygons);
  81305. a.clipTo(b);
  81306. b.clipTo(a);
  81307. b.invert();
  81308. b.clipTo(a);
  81309. b.invert();
  81310. a.build(b.allPolygons());
  81311. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81312. };
  81313. CSG.prototype.unionInPlace = function (csg) {
  81314. var a = new Node(this.polygons);
  81315. var b = new Node(csg.polygons);
  81316. a.clipTo(b);
  81317. b.clipTo(a);
  81318. b.invert();
  81319. b.clipTo(a);
  81320. b.invert();
  81321. a.build(b.allPolygons());
  81322. this.polygons = a.allPolygons();
  81323. };
  81324. CSG.prototype.subtract = function (csg) {
  81325. var a = new Node(this.clone().polygons);
  81326. var b = new Node(csg.clone().polygons);
  81327. a.invert();
  81328. a.clipTo(b);
  81329. b.clipTo(a);
  81330. b.invert();
  81331. b.clipTo(a);
  81332. b.invert();
  81333. a.build(b.allPolygons());
  81334. a.invert();
  81335. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81336. };
  81337. CSG.prototype.subtractInPlace = function (csg) {
  81338. var a = new Node(this.polygons);
  81339. var b = new Node(csg.polygons);
  81340. a.invert();
  81341. a.clipTo(b);
  81342. b.clipTo(a);
  81343. b.invert();
  81344. b.clipTo(a);
  81345. b.invert();
  81346. a.build(b.allPolygons());
  81347. a.invert();
  81348. this.polygons = a.allPolygons();
  81349. };
  81350. CSG.prototype.intersect = function (csg) {
  81351. var a = new Node(this.clone().polygons);
  81352. var b = new Node(csg.clone().polygons);
  81353. a.invert();
  81354. b.clipTo(a);
  81355. b.invert();
  81356. a.clipTo(b);
  81357. b.clipTo(a);
  81358. a.build(b.allPolygons());
  81359. a.invert();
  81360. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81361. };
  81362. CSG.prototype.intersectInPlace = function (csg) {
  81363. var a = new Node(this.polygons);
  81364. var b = new Node(csg.polygons);
  81365. a.invert();
  81366. b.clipTo(a);
  81367. b.invert();
  81368. a.clipTo(b);
  81369. b.clipTo(a);
  81370. a.build(b.allPolygons());
  81371. a.invert();
  81372. this.polygons = a.allPolygons();
  81373. };
  81374. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81375. // not modified.
  81376. CSG.prototype.inverse = function () {
  81377. var csg = this.clone();
  81378. csg.inverseInPlace();
  81379. return csg;
  81380. };
  81381. CSG.prototype.inverseInPlace = function () {
  81382. this.polygons.map(function (p) { p.flip(); });
  81383. };
  81384. // This is used to keep meshes transformations so they can be restored
  81385. // when we build back a Babylon Mesh
  81386. // NB : All CSG operations are performed in world coordinates
  81387. CSG.prototype.copyTransformAttributes = function (csg) {
  81388. this.matrix = csg.matrix;
  81389. this.position = csg.position;
  81390. this.rotation = csg.rotation;
  81391. this.scaling = csg.scaling;
  81392. this.rotationQuaternion = csg.rotationQuaternion;
  81393. return this;
  81394. };
  81395. // Build Raw mesh from CSG
  81396. // Coordinates here are in world space
  81397. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81398. var matrix = this.matrix.clone();
  81399. matrix.invert();
  81400. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  81401. if (keepSubMeshes) {
  81402. // Sort Polygons, since subMeshes are indices range
  81403. polygons.sort(function (a, b) {
  81404. if (a.shared.meshId === b.shared.meshId) {
  81405. return a.shared.subMeshId - b.shared.subMeshId;
  81406. }
  81407. else {
  81408. return a.shared.meshId - b.shared.meshId;
  81409. }
  81410. });
  81411. }
  81412. for (var i = 0, il = polygons.length; i < il; i++) {
  81413. polygon = polygons[i];
  81414. // Building SubMeshes
  81415. if (!subMesh_dict[polygon.shared.meshId]) {
  81416. subMesh_dict[polygon.shared.meshId] = {};
  81417. }
  81418. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81419. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81420. indexStart: +Infinity,
  81421. indexEnd: -Infinity,
  81422. materialIndex: polygon.shared.materialIndex
  81423. };
  81424. }
  81425. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81426. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81427. polygonIndices[0] = 0;
  81428. polygonIndices[1] = j - 1;
  81429. polygonIndices[2] = j;
  81430. for (var k = 0; k < 3; k++) {
  81431. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81432. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81433. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81434. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81435. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81436. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81437. // Check if 2 points can be merged
  81438. if (!(typeof vertex_idx !== 'undefined' &&
  81439. normals[vertex_idx * 3] === localNormal.x &&
  81440. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81441. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81442. uvs[vertex_idx * 2] === uv.x &&
  81443. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81444. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81445. uvs.push(uv.x, uv.y);
  81446. normals.push(normal.x, normal.y, normal.z);
  81447. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81448. }
  81449. indices.push(vertex_idx);
  81450. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81451. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81452. currentIndex++;
  81453. }
  81454. }
  81455. }
  81456. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81457. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81458. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81459. mesh.setIndices(indices, null);
  81460. if (keepSubMeshes) {
  81461. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81462. var materialIndexOffset = 0, materialMaxIndex;
  81463. mesh.subMeshes = new Array();
  81464. for (var m in subMesh_dict) {
  81465. materialMaxIndex = -1;
  81466. for (var sm in subMesh_dict[m]) {
  81467. subMesh_obj = subMesh_dict[m][sm];
  81468. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81469. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81470. }
  81471. materialIndexOffset += ++materialMaxIndex;
  81472. }
  81473. }
  81474. return mesh;
  81475. };
  81476. // Build Mesh from CSG taking material and transforms into account
  81477. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81478. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81479. mesh.material = material;
  81480. mesh.position.copyFrom(this.position);
  81481. mesh.rotation.copyFrom(this.rotation);
  81482. if (this.rotationQuaternion) {
  81483. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81484. }
  81485. mesh.scaling.copyFrom(this.scaling);
  81486. mesh.computeWorldMatrix(true);
  81487. return mesh;
  81488. };
  81489. return CSG;
  81490. }());
  81491. BABYLON.CSG = CSG;
  81492. })(BABYLON || (BABYLON = {}));
  81493. //# sourceMappingURL=babylon.csg.js.map
  81494. var BABYLON;
  81495. (function (BABYLON) {
  81496. var LensFlare = /** @class */ (function () {
  81497. function LensFlare(size, position, color, imgUrl, system) {
  81498. this.size = size;
  81499. this.position = position;
  81500. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81501. this.color = color || new BABYLON.Color3(1, 1, 1);
  81502. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81503. this._system = system;
  81504. system.lensFlares.push(this);
  81505. }
  81506. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81507. return new LensFlare(size, position, color, imgUrl, system);
  81508. };
  81509. LensFlare.prototype.dispose = function () {
  81510. if (this.texture) {
  81511. this.texture.dispose();
  81512. }
  81513. // Remove from scene
  81514. var index = this._system.lensFlares.indexOf(this);
  81515. this._system.lensFlares.splice(index, 1);
  81516. };
  81517. ;
  81518. return LensFlare;
  81519. }());
  81520. BABYLON.LensFlare = LensFlare;
  81521. })(BABYLON || (BABYLON = {}));
  81522. //# sourceMappingURL=babylon.lensFlare.js.map
  81523. var BABYLON;
  81524. (function (BABYLON) {
  81525. var LensFlareSystem = /** @class */ (function () {
  81526. function LensFlareSystem(name, emitter, scene) {
  81527. this.name = name;
  81528. this.lensFlares = new Array();
  81529. this.borderLimit = 300;
  81530. this.viewportBorder = 0;
  81531. this.layerMask = 0x0FFFFFFF;
  81532. this._vertexBuffers = {};
  81533. this._isEnabled = true;
  81534. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81535. this._emitter = emitter;
  81536. this.id = name;
  81537. scene.lensFlareSystems.push(this);
  81538. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81539. var engine = scene.getEngine();
  81540. // VBO
  81541. var vertices = [];
  81542. vertices.push(1, 1);
  81543. vertices.push(-1, 1);
  81544. vertices.push(-1, -1);
  81545. vertices.push(1, -1);
  81546. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81547. // Indices
  81548. var indices = [];
  81549. indices.push(0);
  81550. indices.push(1);
  81551. indices.push(2);
  81552. indices.push(0);
  81553. indices.push(2);
  81554. indices.push(3);
  81555. this._indexBuffer = engine.createIndexBuffer(indices);
  81556. // Effects
  81557. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81558. }
  81559. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81560. get: function () {
  81561. return this._isEnabled;
  81562. },
  81563. set: function (value) {
  81564. this._isEnabled = value;
  81565. },
  81566. enumerable: true,
  81567. configurable: true
  81568. });
  81569. LensFlareSystem.prototype.getScene = function () {
  81570. return this._scene;
  81571. };
  81572. LensFlareSystem.prototype.getEmitter = function () {
  81573. return this._emitter;
  81574. };
  81575. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81576. this._emitter = newEmitter;
  81577. };
  81578. LensFlareSystem.prototype.getEmitterPosition = function () {
  81579. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81580. };
  81581. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81582. var position = this.getEmitterPosition();
  81583. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81584. this._positionX = position.x;
  81585. this._positionY = position.y;
  81586. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81587. if (this.viewportBorder > 0) {
  81588. globalViewport.x -= this.viewportBorder;
  81589. globalViewport.y -= this.viewportBorder;
  81590. globalViewport.width += this.viewportBorder * 2;
  81591. globalViewport.height += this.viewportBorder * 2;
  81592. position.x += this.viewportBorder;
  81593. position.y += this.viewportBorder;
  81594. this._positionX += this.viewportBorder;
  81595. this._positionY += this.viewportBorder;
  81596. }
  81597. if (position.z > 0) {
  81598. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81599. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81600. return true;
  81601. }
  81602. return true;
  81603. }
  81604. return false;
  81605. };
  81606. LensFlareSystem.prototype._isVisible = function () {
  81607. if (!this._isEnabled || !this._scene.activeCamera) {
  81608. return false;
  81609. }
  81610. var emitterPosition = this.getEmitterPosition();
  81611. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81612. var distance = direction.length();
  81613. direction.normalize();
  81614. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81615. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81616. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81617. };
  81618. LensFlareSystem.prototype.render = function () {
  81619. if (!this._effect.isReady() || !this._scene.activeCamera)
  81620. return false;
  81621. var engine = this._scene.getEngine();
  81622. var viewport = this._scene.activeCamera.viewport;
  81623. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81624. // Position
  81625. if (!this.computeEffectivePosition(globalViewport)) {
  81626. return false;
  81627. }
  81628. // Visibility
  81629. if (!this._isVisible()) {
  81630. return false;
  81631. }
  81632. // Intensity
  81633. var awayX;
  81634. var awayY;
  81635. if (this._positionX < this.borderLimit + globalViewport.x) {
  81636. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81637. }
  81638. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81639. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81640. }
  81641. else {
  81642. awayX = 0;
  81643. }
  81644. if (this._positionY < this.borderLimit + globalViewport.y) {
  81645. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81646. }
  81647. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81648. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81649. }
  81650. else {
  81651. awayY = 0;
  81652. }
  81653. var away = (awayX > awayY) ? awayX : awayY;
  81654. away -= this.viewportBorder;
  81655. if (away > this.borderLimit) {
  81656. away = this.borderLimit;
  81657. }
  81658. var intensity = 1.0 - (away / this.borderLimit);
  81659. if (intensity < 0) {
  81660. return false;
  81661. }
  81662. if (intensity > 1.0) {
  81663. intensity = 1.0;
  81664. }
  81665. if (this.viewportBorder > 0) {
  81666. globalViewport.x += this.viewportBorder;
  81667. globalViewport.y += this.viewportBorder;
  81668. globalViewport.width -= this.viewportBorder * 2;
  81669. globalViewport.height -= this.viewportBorder * 2;
  81670. this._positionX -= this.viewportBorder;
  81671. this._positionY -= this.viewportBorder;
  81672. }
  81673. // Position
  81674. var centerX = globalViewport.x + globalViewport.width / 2;
  81675. var centerY = globalViewport.y + globalViewport.height / 2;
  81676. var distX = centerX - this._positionX;
  81677. var distY = centerY - this._positionY;
  81678. // Effects
  81679. engine.enableEffect(this._effect);
  81680. engine.setState(false);
  81681. engine.setDepthBuffer(false);
  81682. // VBOs
  81683. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81684. // Flares
  81685. for (var index = 0; index < this.lensFlares.length; index++) {
  81686. var flare = this.lensFlares[index];
  81687. engine.setAlphaMode(flare.alphaMode);
  81688. var x = centerX - (distX * flare.position);
  81689. var y = centerY - (distY * flare.position);
  81690. var cw = flare.size;
  81691. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81692. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81693. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81694. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81695. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81696. // Texture
  81697. this._effect.setTexture("textureSampler", flare.texture);
  81698. // Color
  81699. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81700. // Draw order
  81701. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81702. }
  81703. engine.setDepthBuffer(true);
  81704. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81705. return true;
  81706. };
  81707. LensFlareSystem.prototype.dispose = function () {
  81708. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81709. if (vertexBuffer) {
  81710. vertexBuffer.dispose();
  81711. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81712. }
  81713. if (this._indexBuffer) {
  81714. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81715. this._indexBuffer = null;
  81716. }
  81717. while (this.lensFlares.length) {
  81718. this.lensFlares[0].dispose();
  81719. }
  81720. // Remove from scene
  81721. var index = this._scene.lensFlareSystems.indexOf(this);
  81722. this._scene.lensFlareSystems.splice(index, 1);
  81723. };
  81724. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81725. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81726. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81727. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81728. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81729. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81730. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81731. var parsedFlare = parsedLensFlareSystem.flares[index];
  81732. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81733. }
  81734. return lensFlareSystem;
  81735. };
  81736. LensFlareSystem.prototype.serialize = function () {
  81737. var serializationObject = {};
  81738. serializationObject.id = this.id;
  81739. serializationObject.name = this.name;
  81740. serializationObject.emitterId = this.getEmitter().id;
  81741. serializationObject.borderLimit = this.borderLimit;
  81742. serializationObject.flares = [];
  81743. for (var index = 0; index < this.lensFlares.length; index++) {
  81744. var flare = this.lensFlares[index];
  81745. serializationObject.flares.push({
  81746. size: flare.size,
  81747. position: flare.position,
  81748. color: flare.color.asArray(),
  81749. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81750. });
  81751. }
  81752. return serializationObject;
  81753. };
  81754. return LensFlareSystem;
  81755. }());
  81756. BABYLON.LensFlareSystem = LensFlareSystem;
  81757. })(BABYLON || (BABYLON = {}));
  81758. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81759. var BABYLON;
  81760. (function (BABYLON) {
  81761. /**
  81762. * This is a holder class for the physics joint created by the physics plugin.
  81763. * It holds a set of functions to control the underlying joint.
  81764. */
  81765. var PhysicsJoint = /** @class */ (function () {
  81766. function PhysicsJoint(type, jointData) {
  81767. this.type = type;
  81768. this.jointData = jointData;
  81769. jointData.nativeParams = jointData.nativeParams || {};
  81770. }
  81771. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81772. get: function () {
  81773. return this._physicsJoint;
  81774. },
  81775. set: function (newJoint) {
  81776. if (this._physicsJoint) {
  81777. //remove from the wolrd
  81778. }
  81779. this._physicsJoint = newJoint;
  81780. },
  81781. enumerable: true,
  81782. configurable: true
  81783. });
  81784. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81785. set: function (physicsPlugin) {
  81786. this._physicsPlugin = physicsPlugin;
  81787. },
  81788. enumerable: true,
  81789. configurable: true
  81790. });
  81791. /**
  81792. * Execute a function that is physics-plugin specific.
  81793. * @param {Function} func the function that will be executed.
  81794. * It accepts two parameters: the physics world and the physics joint.
  81795. */
  81796. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81797. func(this._physicsPlugin.world, this._physicsJoint);
  81798. };
  81799. //TODO check if the native joints are the same
  81800. //Joint Types
  81801. PhysicsJoint.DistanceJoint = 0;
  81802. PhysicsJoint.HingeJoint = 1;
  81803. PhysicsJoint.BallAndSocketJoint = 2;
  81804. PhysicsJoint.WheelJoint = 3;
  81805. PhysicsJoint.SliderJoint = 4;
  81806. //OIMO
  81807. PhysicsJoint.PrismaticJoint = 5;
  81808. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81809. PhysicsJoint.UniversalJoint = 6;
  81810. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81811. //Cannon
  81812. //Similar to a Ball-Joint. Different in params
  81813. PhysicsJoint.PointToPointJoint = 8;
  81814. //Cannon only at the moment
  81815. PhysicsJoint.SpringJoint = 9;
  81816. PhysicsJoint.LockJoint = 10;
  81817. return PhysicsJoint;
  81818. }());
  81819. BABYLON.PhysicsJoint = PhysicsJoint;
  81820. /**
  81821. * A class representing a physics distance joint.
  81822. */
  81823. var DistanceJoint = /** @class */ (function (_super) {
  81824. __extends(DistanceJoint, _super);
  81825. function DistanceJoint(jointData) {
  81826. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81827. }
  81828. /**
  81829. * Update the predefined distance.
  81830. */
  81831. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81832. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81833. };
  81834. return DistanceJoint;
  81835. }(PhysicsJoint));
  81836. BABYLON.DistanceJoint = DistanceJoint;
  81837. var MotorEnabledJoint = /** @class */ (function (_super) {
  81838. __extends(MotorEnabledJoint, _super);
  81839. function MotorEnabledJoint(type, jointData) {
  81840. return _super.call(this, type, jointData) || this;
  81841. }
  81842. /**
  81843. * Set the motor values.
  81844. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81845. * @param {number} force the force to apply
  81846. * @param {number} maxForce max force for this motor.
  81847. */
  81848. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81849. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81850. };
  81851. /**
  81852. * Set the motor's limits.
  81853. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81854. */
  81855. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81856. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81857. };
  81858. return MotorEnabledJoint;
  81859. }(PhysicsJoint));
  81860. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81861. /**
  81862. * This class represents a single hinge physics joint
  81863. */
  81864. var HingeJoint = /** @class */ (function (_super) {
  81865. __extends(HingeJoint, _super);
  81866. function HingeJoint(jointData) {
  81867. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81868. }
  81869. /**
  81870. * Set the motor values.
  81871. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81872. * @param {number} force the force to apply
  81873. * @param {number} maxForce max force for this motor.
  81874. */
  81875. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81876. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81877. };
  81878. /**
  81879. * Set the motor's limits.
  81880. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81881. */
  81882. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81883. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81884. };
  81885. return HingeJoint;
  81886. }(MotorEnabledJoint));
  81887. BABYLON.HingeJoint = HingeJoint;
  81888. /**
  81889. * This class represents a dual hinge physics joint (same as wheel joint)
  81890. */
  81891. var Hinge2Joint = /** @class */ (function (_super) {
  81892. __extends(Hinge2Joint, _super);
  81893. function Hinge2Joint(jointData) {
  81894. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81895. }
  81896. /**
  81897. * Set the motor values.
  81898. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81899. * @param {number} force the force to apply
  81900. * @param {number} maxForce max force for this motor.
  81901. * @param {motorIndex} the motor's index, 0 or 1.
  81902. */
  81903. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81904. if (motorIndex === void 0) { motorIndex = 0; }
  81905. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81906. };
  81907. /**
  81908. * Set the motor limits.
  81909. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81910. * @param {number} upperLimit the upper limit
  81911. * @param {number} lowerLimit lower limit
  81912. * @param {motorIndex} the motor's index, 0 or 1.
  81913. */
  81914. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81915. if (motorIndex === void 0) { motorIndex = 0; }
  81916. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81917. };
  81918. return Hinge2Joint;
  81919. }(MotorEnabledJoint));
  81920. BABYLON.Hinge2Joint = Hinge2Joint;
  81921. })(BABYLON || (BABYLON = {}));
  81922. //# sourceMappingURL=babylon.physicsJoint.js.map
  81923. var BABYLON;
  81924. (function (BABYLON) {
  81925. var PhysicsImpostor = /** @class */ (function () {
  81926. function PhysicsImpostor(object, type, _options, _scene) {
  81927. if (_options === void 0) { _options = { mass: 0 }; }
  81928. var _this = this;
  81929. this.object = object;
  81930. this.type = type;
  81931. this._options = _options;
  81932. this._scene = _scene;
  81933. this._bodyUpdateRequired = false;
  81934. this._onBeforePhysicsStepCallbacks = new Array();
  81935. this._onAfterPhysicsStepCallbacks = new Array();
  81936. this._onPhysicsCollideCallbacks = [];
  81937. this._deltaPosition = BABYLON.Vector3.Zero();
  81938. this._isDisposed = false;
  81939. //temp variables for parent rotation calculations
  81940. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81941. this._tmpQuat = new BABYLON.Quaternion();
  81942. this._tmpQuat2 = new BABYLON.Quaternion();
  81943. /**
  81944. * this function is executed by the physics engine.
  81945. */
  81946. this.beforeStep = function () {
  81947. if (!_this._physicsEngine) {
  81948. return;
  81949. }
  81950. _this.object.translate(_this._deltaPosition, -1);
  81951. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81952. _this.object.computeWorldMatrix(false);
  81953. if (_this.object.parent && _this.object.rotationQuaternion) {
  81954. _this.getParentsRotation();
  81955. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81956. }
  81957. else {
  81958. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81959. }
  81960. if (!_this._options.disableBidirectionalTransformation) {
  81961. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81962. }
  81963. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81964. func(_this);
  81965. });
  81966. };
  81967. /**
  81968. * this function is executed by the physics engine.
  81969. */
  81970. this.afterStep = function () {
  81971. if (!_this._physicsEngine) {
  81972. return;
  81973. }
  81974. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81975. func(_this);
  81976. });
  81977. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81978. // object has now its world rotation. needs to be converted to local.
  81979. if (_this.object.parent && _this.object.rotationQuaternion) {
  81980. _this.getParentsRotation();
  81981. _this._tmpQuat.conjugateInPlace();
  81982. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81983. }
  81984. // take the position set and make it the absolute position of this object.
  81985. _this.object.setAbsolutePosition(_this.object.position);
  81986. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81987. _this.object.translate(_this._deltaPosition, 1);
  81988. };
  81989. /**
  81990. * Legacy collision detection event support
  81991. */
  81992. this.onCollideEvent = null;
  81993. //event and body object due to cannon's event-based architecture.
  81994. this.onCollide = function (e) {
  81995. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81996. return;
  81997. }
  81998. if (!_this._physicsEngine) {
  81999. return;
  82000. }
  82001. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82002. if (otherImpostor) {
  82003. // Legacy collision detection event support
  82004. if (_this.onCollideEvent) {
  82005. _this.onCollideEvent(_this, otherImpostor);
  82006. }
  82007. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82008. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82009. }).forEach(function (obj) {
  82010. obj.callback(_this, otherImpostor);
  82011. });
  82012. }
  82013. };
  82014. //sanity check!
  82015. if (!this.object) {
  82016. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82017. return;
  82018. }
  82019. //legacy support for old syntax.
  82020. if (!this._scene && object.getScene) {
  82021. this._scene = object.getScene();
  82022. }
  82023. if (!this._scene) {
  82024. return;
  82025. }
  82026. this._physicsEngine = this._scene.getPhysicsEngine();
  82027. if (!this._physicsEngine) {
  82028. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82029. }
  82030. else {
  82031. //set the object's quaternion, if not set
  82032. if (!this.object.rotationQuaternion) {
  82033. if (this.object.rotation) {
  82034. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82035. }
  82036. else {
  82037. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82038. }
  82039. }
  82040. //default options params
  82041. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82042. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82043. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82044. this._joints = [];
  82045. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82046. if (!this.object.parent || this._options.ignoreParent) {
  82047. this._init();
  82048. }
  82049. else if (this.object.parent.physicsImpostor) {
  82050. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82051. }
  82052. }
  82053. }
  82054. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82055. get: function () {
  82056. return this._isDisposed;
  82057. },
  82058. enumerable: true,
  82059. configurable: true
  82060. });
  82061. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82062. get: function () {
  82063. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82064. },
  82065. set: function (value) {
  82066. this.setMass(value);
  82067. },
  82068. enumerable: true,
  82069. configurable: true
  82070. });
  82071. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82072. get: function () {
  82073. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82074. },
  82075. set: function (value) {
  82076. if (!this._physicsEngine) {
  82077. return;
  82078. }
  82079. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82080. },
  82081. enumerable: true,
  82082. configurable: true
  82083. });
  82084. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82085. get: function () {
  82086. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82087. },
  82088. set: function (value) {
  82089. if (!this._physicsEngine) {
  82090. return;
  82091. }
  82092. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82093. },
  82094. enumerable: true,
  82095. configurable: true
  82096. });
  82097. /**
  82098. * This function will completly initialize this impostor.
  82099. * It will create a new body - but only if this mesh has no parent.
  82100. * If it has, this impostor will not be used other than to define the impostor
  82101. * of the child mesh.
  82102. */
  82103. PhysicsImpostor.prototype._init = function () {
  82104. if (!this._physicsEngine) {
  82105. return;
  82106. }
  82107. this._physicsEngine.removeImpostor(this);
  82108. this.physicsBody = null;
  82109. this._parent = this._parent || this._getPhysicsParent();
  82110. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82111. this._physicsEngine.addImpostor(this);
  82112. }
  82113. };
  82114. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82115. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82116. var parentMesh = this.object.parent;
  82117. return parentMesh.physicsImpostor;
  82118. }
  82119. return null;
  82120. };
  82121. /**
  82122. * Should a new body be generated.
  82123. */
  82124. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82125. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82126. };
  82127. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82128. this.forceUpdate();
  82129. };
  82130. /**
  82131. * Force a regeneration of this or the parent's impostor's body.
  82132. * Use under cautious - This will remove all joints already implemented.
  82133. */
  82134. PhysicsImpostor.prototype.forceUpdate = function () {
  82135. this._init();
  82136. if (this.parent && !this._options.ignoreParent) {
  82137. this.parent.forceUpdate();
  82138. }
  82139. };
  82140. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82141. /*public get mesh(): AbstractMesh {
  82142. return this._mesh;
  82143. }*/
  82144. /**
  82145. * Gets the body that holds this impostor. Either its own, or its parent.
  82146. */
  82147. get: function () {
  82148. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82149. },
  82150. /**
  82151. * Set the physics body. Used mainly by the physics engine/plugin
  82152. */
  82153. set: function (physicsBody) {
  82154. if (this._physicsBody && this._physicsEngine) {
  82155. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82156. }
  82157. this._physicsBody = physicsBody;
  82158. this.resetUpdateFlags();
  82159. },
  82160. enumerable: true,
  82161. configurable: true
  82162. });
  82163. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82164. get: function () {
  82165. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82166. },
  82167. set: function (value) {
  82168. this._parent = value;
  82169. },
  82170. enumerable: true,
  82171. configurable: true
  82172. });
  82173. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82174. this._bodyUpdateRequired = false;
  82175. };
  82176. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82177. if (this.object.getBoundingInfo) {
  82178. var q = this.object.rotationQuaternion;
  82179. //reset rotation
  82180. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82181. //calculate the world matrix with no rotation
  82182. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82183. var boundingInfo = this.object.getBoundingInfo();
  82184. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82185. //bring back the rotation
  82186. this.object.rotationQuaternion = q;
  82187. //calculate the world matrix with the new rotation
  82188. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82189. return size;
  82190. }
  82191. else {
  82192. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82193. }
  82194. };
  82195. PhysicsImpostor.prototype.getObjectCenter = function () {
  82196. if (this.object.getBoundingInfo) {
  82197. var boundingInfo = this.object.getBoundingInfo();
  82198. return boundingInfo.boundingBox.centerWorld;
  82199. }
  82200. else {
  82201. return this.object.position;
  82202. }
  82203. };
  82204. /**
  82205. * Get a specific parametes from the options parameter.
  82206. */
  82207. PhysicsImpostor.prototype.getParam = function (paramName) {
  82208. return this._options[paramName];
  82209. };
  82210. /**
  82211. * Sets a specific parameter in the options given to the physics plugin
  82212. */
  82213. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82214. this._options[paramName] = value;
  82215. this._bodyUpdateRequired = true;
  82216. };
  82217. /**
  82218. * Specifically change the body's mass option. Won't recreate the physics body object
  82219. */
  82220. PhysicsImpostor.prototype.setMass = function (mass) {
  82221. if (this.getParam("mass") !== mass) {
  82222. this.setParam("mass", mass);
  82223. }
  82224. if (this._physicsEngine) {
  82225. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82226. }
  82227. };
  82228. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82229. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82230. };
  82231. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82232. if (this._physicsEngine) {
  82233. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82234. }
  82235. };
  82236. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82237. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82238. };
  82239. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82240. if (this._physicsEngine) {
  82241. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82242. }
  82243. };
  82244. /**
  82245. * Execute a function with the physics plugin native code.
  82246. * Provide a function the will have two variables - the world object and the physics body object.
  82247. */
  82248. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82249. if (this._physicsEngine) {
  82250. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82251. }
  82252. };
  82253. /**
  82254. * Register a function that will be executed before the physics world is stepping forward.
  82255. */
  82256. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82257. this._onBeforePhysicsStepCallbacks.push(func);
  82258. };
  82259. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82260. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82261. if (index > -1) {
  82262. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82263. }
  82264. else {
  82265. BABYLON.Tools.Warn("Function to remove was not found");
  82266. }
  82267. };
  82268. /**
  82269. * Register a function that will be executed after the physics step
  82270. */
  82271. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82272. this._onAfterPhysicsStepCallbacks.push(func);
  82273. };
  82274. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82275. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82276. if (index > -1) {
  82277. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82278. }
  82279. else {
  82280. BABYLON.Tools.Warn("Function to remove was not found");
  82281. }
  82282. };
  82283. /**
  82284. * register a function that will be executed when this impostor collides against a different body.
  82285. */
  82286. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82287. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82288. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82289. };
  82290. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82291. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82292. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82293. if (index > -1) {
  82294. this._onPhysicsCollideCallbacks.splice(index, 1);
  82295. }
  82296. else {
  82297. BABYLON.Tools.Warn("Function to remove was not found");
  82298. }
  82299. };
  82300. PhysicsImpostor.prototype.getParentsRotation = function () {
  82301. var parent = this.object.parent;
  82302. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82303. while (parent) {
  82304. if (parent.rotationQuaternion) {
  82305. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82306. }
  82307. else {
  82308. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82309. }
  82310. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82311. parent = parent.parent;
  82312. }
  82313. return this._tmpQuat;
  82314. };
  82315. /**
  82316. * Apply a force
  82317. */
  82318. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82319. if (this._physicsEngine) {
  82320. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82321. }
  82322. return this;
  82323. };
  82324. /**
  82325. * Apply an impulse
  82326. */
  82327. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82328. if (this._physicsEngine) {
  82329. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82330. }
  82331. return this;
  82332. };
  82333. /**
  82334. * A help function to create a joint.
  82335. */
  82336. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82337. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82338. this.addJoint(otherImpostor, joint);
  82339. return this;
  82340. };
  82341. /**
  82342. * Add a joint to this impostor with a different impostor.
  82343. */
  82344. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82345. this._joints.push({
  82346. otherImpostor: otherImpostor,
  82347. joint: joint
  82348. });
  82349. if (this._physicsEngine) {
  82350. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82351. }
  82352. return this;
  82353. };
  82354. /**
  82355. * Will keep this body still, in a sleep mode.
  82356. */
  82357. PhysicsImpostor.prototype.sleep = function () {
  82358. if (this._physicsEngine) {
  82359. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82360. }
  82361. return this;
  82362. };
  82363. /**
  82364. * Wake the body up.
  82365. */
  82366. PhysicsImpostor.prototype.wakeUp = function () {
  82367. if (this._physicsEngine) {
  82368. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82369. }
  82370. return this;
  82371. };
  82372. PhysicsImpostor.prototype.clone = function (newObject) {
  82373. if (!newObject)
  82374. return null;
  82375. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82376. };
  82377. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82378. var _this = this;
  82379. //no dispose if no physics engine is available.
  82380. if (!this._physicsEngine) {
  82381. return;
  82382. }
  82383. this._joints.forEach(function (j) {
  82384. if (_this._physicsEngine) {
  82385. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82386. }
  82387. });
  82388. //dispose the physics body
  82389. this._physicsEngine.removeImpostor(this);
  82390. if (this.parent) {
  82391. this.parent.forceUpdate();
  82392. }
  82393. else {
  82394. /*this._object.getChildMeshes().forEach(function(mesh) {
  82395. if (mesh.physicsImpostor) {
  82396. if (disposeChildren) {
  82397. mesh.physicsImpostor.dispose();
  82398. mesh.physicsImpostor = null;
  82399. }
  82400. }
  82401. })*/
  82402. }
  82403. this._isDisposed = true;
  82404. };
  82405. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82406. this._deltaPosition.copyFrom(position);
  82407. };
  82408. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82409. if (!this._deltaRotation) {
  82410. this._deltaRotation = new BABYLON.Quaternion();
  82411. }
  82412. this._deltaRotation.copyFrom(rotation);
  82413. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82414. };
  82415. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82416. if (this._physicsEngine) {
  82417. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82418. }
  82419. return this;
  82420. };
  82421. PhysicsImpostor.prototype.getRadius = function () {
  82422. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82423. };
  82424. /**
  82425. * Sync a bone with this impostor
  82426. * @param bone The bone to sync to the impostor.
  82427. * @param boneMesh The mesh that the bone is influencing.
  82428. * @param jointPivot The pivot of the joint / bone in local space.
  82429. * @param distToJoint Optional distance from the impostor to the joint.
  82430. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82431. */
  82432. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82433. var tempVec = PhysicsImpostor._tmpVecs[0];
  82434. var mesh = this.object;
  82435. if (mesh.rotationQuaternion) {
  82436. if (adjustRotation) {
  82437. var tempQuat = PhysicsImpostor._tmpQuat;
  82438. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82439. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82440. }
  82441. else {
  82442. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82443. }
  82444. }
  82445. tempVec.x = 0;
  82446. tempVec.y = 0;
  82447. tempVec.z = 0;
  82448. if (jointPivot) {
  82449. tempVec.x = jointPivot.x;
  82450. tempVec.y = jointPivot.y;
  82451. tempVec.z = jointPivot.z;
  82452. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82453. if (distToJoint === undefined || distToJoint === null) {
  82454. distToJoint = jointPivot.length();
  82455. }
  82456. tempVec.x *= distToJoint;
  82457. tempVec.y *= distToJoint;
  82458. tempVec.z *= distToJoint;
  82459. }
  82460. if (bone.getParent()) {
  82461. tempVec.addInPlace(mesh.getAbsolutePosition());
  82462. bone.setAbsolutePosition(tempVec, boneMesh);
  82463. }
  82464. else {
  82465. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82466. boneMesh.position.x -= tempVec.x;
  82467. boneMesh.position.y -= tempVec.y;
  82468. boneMesh.position.z -= tempVec.z;
  82469. }
  82470. };
  82471. /**
  82472. * Sync impostor to a bone
  82473. * @param bone The bone that the impostor will be synced to.
  82474. * @param boneMesh The mesh that the bone is influencing.
  82475. * @param jointPivot The pivot of the joint / bone in local space.
  82476. * @param distToJoint Optional distance from the impostor to the joint.
  82477. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82478. * @param boneAxis Optional vector3 axis the bone is aligned with
  82479. */
  82480. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82481. var mesh = this.object;
  82482. if (mesh.rotationQuaternion) {
  82483. if (adjustRotation) {
  82484. var tempQuat = PhysicsImpostor._tmpQuat;
  82485. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82486. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82487. }
  82488. else {
  82489. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82490. }
  82491. }
  82492. var pos = PhysicsImpostor._tmpVecs[0];
  82493. var boneDir = PhysicsImpostor._tmpVecs[1];
  82494. if (!boneAxis) {
  82495. boneAxis = PhysicsImpostor._tmpVecs[2];
  82496. boneAxis.x = 0;
  82497. boneAxis.y = 1;
  82498. boneAxis.z = 0;
  82499. }
  82500. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82501. bone.getAbsolutePositionToRef(boneMesh, pos);
  82502. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82503. distToJoint = jointPivot.length();
  82504. }
  82505. if (distToJoint !== undefined && distToJoint !== null) {
  82506. pos.x += boneDir.x * distToJoint;
  82507. pos.y += boneDir.y * distToJoint;
  82508. pos.z += boneDir.z * distToJoint;
  82509. }
  82510. mesh.setAbsolutePosition(pos);
  82511. };
  82512. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82513. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82514. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82515. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82516. //Impostor types
  82517. PhysicsImpostor.NoImpostor = 0;
  82518. PhysicsImpostor.SphereImpostor = 1;
  82519. PhysicsImpostor.BoxImpostor = 2;
  82520. PhysicsImpostor.PlaneImpostor = 3;
  82521. PhysicsImpostor.MeshImpostor = 4;
  82522. PhysicsImpostor.CylinderImpostor = 7;
  82523. PhysicsImpostor.ParticleImpostor = 8;
  82524. PhysicsImpostor.HeightmapImpostor = 9;
  82525. return PhysicsImpostor;
  82526. }());
  82527. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82528. })(BABYLON || (BABYLON = {}));
  82529. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82530. var BABYLON;
  82531. (function (BABYLON) {
  82532. var PhysicsEngine = /** @class */ (function () {
  82533. function PhysicsEngine(gravity, _physicsPlugin) {
  82534. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82535. this._physicsPlugin = _physicsPlugin;
  82536. //new methods and parameters
  82537. this._impostors = [];
  82538. this._joints = [];
  82539. if (!this._physicsPlugin.isSupported()) {
  82540. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82541. + "Please make sure it is included.");
  82542. }
  82543. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82544. this.setGravity(gravity);
  82545. this.setTimeStep();
  82546. }
  82547. PhysicsEngine.prototype.setGravity = function (gravity) {
  82548. this.gravity = gravity;
  82549. this._physicsPlugin.setGravity(this.gravity);
  82550. };
  82551. /**
  82552. * Set the time step of the physics engine.
  82553. * default is 1/60.
  82554. * To slow it down, enter 1/600 for example.
  82555. * To speed it up, 1/30
  82556. * @param {number} newTimeStep the new timestep to apply to this world.
  82557. */
  82558. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82559. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82560. this._physicsPlugin.setTimeStep(newTimeStep);
  82561. };
  82562. /**
  82563. * Get the time step of the physics engine.
  82564. */
  82565. PhysicsEngine.prototype.getTimeStep = function () {
  82566. return this._physicsPlugin.getTimeStep();
  82567. };
  82568. PhysicsEngine.prototype.dispose = function () {
  82569. this._impostors.forEach(function (impostor) {
  82570. impostor.dispose();
  82571. });
  82572. this._physicsPlugin.dispose();
  82573. };
  82574. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82575. return this._physicsPlugin.name;
  82576. };
  82577. /**
  82578. * Adding a new impostor for the impostor tracking.
  82579. * This will be done by the impostor itself.
  82580. * @param {PhysicsImpostor} impostor the impostor to add
  82581. */
  82582. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82583. impostor.uniqueId = this._impostors.push(impostor);
  82584. //if no parent, generate the body
  82585. if (!impostor.parent) {
  82586. this._physicsPlugin.generatePhysicsBody(impostor);
  82587. }
  82588. };
  82589. /**
  82590. * Remove an impostor from the engine.
  82591. * This impostor and its mesh will not longer be updated by the physics engine.
  82592. * @param {PhysicsImpostor} impostor the impostor to remove
  82593. */
  82594. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82595. var index = this._impostors.indexOf(impostor);
  82596. if (index > -1) {
  82597. var removed = this._impostors.splice(index, 1);
  82598. //Is it needed?
  82599. if (removed.length) {
  82600. //this will also remove it from the world.
  82601. removed[0].physicsBody = null;
  82602. }
  82603. }
  82604. };
  82605. /**
  82606. * Add a joint to the physics engine
  82607. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82608. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82609. * @param {PhysicsJoint} the joint that will connect both impostors.
  82610. */
  82611. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82612. var impostorJoint = {
  82613. mainImpostor: mainImpostor,
  82614. connectedImpostor: connectedImpostor,
  82615. joint: joint
  82616. };
  82617. joint.physicsPlugin = this._physicsPlugin;
  82618. this._joints.push(impostorJoint);
  82619. this._physicsPlugin.generateJoint(impostorJoint);
  82620. };
  82621. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82622. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82623. return (impostorJoint.connectedImpostor === connectedImpostor
  82624. && impostorJoint.joint === joint
  82625. && impostorJoint.mainImpostor === mainImpostor);
  82626. });
  82627. if (matchingJoints.length) {
  82628. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82629. //TODO remove it from the list as well
  82630. }
  82631. };
  82632. /**
  82633. * Called by the scene. no need to call it.
  82634. */
  82635. PhysicsEngine.prototype._step = function (delta) {
  82636. var _this = this;
  82637. //check if any mesh has no body / requires an update
  82638. this._impostors.forEach(function (impostor) {
  82639. if (impostor.isBodyInitRequired()) {
  82640. _this._physicsPlugin.generatePhysicsBody(impostor);
  82641. }
  82642. });
  82643. if (delta > 0.1) {
  82644. delta = 0.1;
  82645. }
  82646. else if (delta <= 0) {
  82647. delta = 1.0 / 60.0;
  82648. }
  82649. this._physicsPlugin.executeStep(delta, this._impostors);
  82650. };
  82651. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82652. return this._physicsPlugin;
  82653. };
  82654. PhysicsEngine.prototype.getImpostors = function () {
  82655. return this._impostors;
  82656. };
  82657. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82658. for (var i = 0; i < this._impostors.length; ++i) {
  82659. if (this._impostors[i].object === object) {
  82660. return this._impostors[i];
  82661. }
  82662. }
  82663. return null;
  82664. };
  82665. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82666. for (var i = 0; i < this._impostors.length; ++i) {
  82667. if (this._impostors[i].physicsBody === body) {
  82668. return this._impostors[i];
  82669. }
  82670. }
  82671. return null;
  82672. };
  82673. // Statics
  82674. PhysicsEngine.Epsilon = 0.001;
  82675. return PhysicsEngine;
  82676. }());
  82677. BABYLON.PhysicsEngine = PhysicsEngine;
  82678. })(BABYLON || (BABYLON = {}));
  82679. //# sourceMappingURL=babylon.physicsEngine.js.map
  82680. var BABYLON;
  82681. (function (BABYLON) {
  82682. var PhysicsHelper = /** @class */ (function () {
  82683. function PhysicsHelper(scene) {
  82684. this._scene = scene;
  82685. this._physicsEngine = this._scene.getPhysicsEngine();
  82686. if (!this._physicsEngine) {
  82687. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82688. }
  82689. }
  82690. /**
  82691. * @param {Vector3} origin the origin of the explosion
  82692. * @param {number} radius the explosion radius
  82693. * @param {number} strength the explosion strength
  82694. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82695. */
  82696. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82697. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82698. if (!this._physicsEngine) {
  82699. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82700. return null;
  82701. }
  82702. var impostors = this._physicsEngine.getImpostors();
  82703. if (impostors.length === 0) {
  82704. return null;
  82705. }
  82706. var event = new PhysicsRadialExplosionEvent(this._scene);
  82707. impostors.forEach(function (impostor) {
  82708. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82709. if (!impostorForceAndContactPoint) {
  82710. return;
  82711. }
  82712. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82713. });
  82714. event.dispose(false);
  82715. return event;
  82716. };
  82717. /**
  82718. * @param {Vector3} origin the origin of the explosion
  82719. * @param {number} radius the explosion radius
  82720. * @param {number} strength the explosion strength
  82721. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82722. */
  82723. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82724. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82725. if (!this._physicsEngine) {
  82726. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82727. return null;
  82728. }
  82729. var impostors = this._physicsEngine.getImpostors();
  82730. if (impostors.length === 0) {
  82731. return null;
  82732. }
  82733. var event = new PhysicsRadialExplosionEvent(this._scene);
  82734. impostors.forEach(function (impostor) {
  82735. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82736. if (!impostorForceAndContactPoint) {
  82737. return;
  82738. }
  82739. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82740. });
  82741. event.dispose(false);
  82742. return event;
  82743. };
  82744. /**
  82745. * @param {Vector3} origin the origin of the explosion
  82746. * @param {number} radius the explosion radius
  82747. * @param {number} strength the explosion strength
  82748. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82749. */
  82750. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82751. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82752. if (!this._physicsEngine) {
  82753. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82754. return null;
  82755. }
  82756. var impostors = this._physicsEngine.getImpostors();
  82757. if (impostors.length === 0) {
  82758. return null;
  82759. }
  82760. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82761. event.dispose(false);
  82762. return event;
  82763. };
  82764. /**
  82765. * @param {Vector3} origin the origin of the updraft
  82766. * @param {number} radius the radius of the updraft
  82767. * @param {number} strength the strength of the updraft
  82768. * @param {number} height the height of the updraft
  82769. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82770. */
  82771. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82772. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82773. if (!this._physicsEngine) {
  82774. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82775. return null;
  82776. }
  82777. if (this._physicsEngine.getImpostors().length === 0) {
  82778. return null;
  82779. }
  82780. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82781. event.dispose(false);
  82782. return event;
  82783. };
  82784. /**
  82785. * @param {Vector3} origin the of the vortex
  82786. * @param {number} radius the radius of the vortex
  82787. * @param {number} strength the strength of the vortex
  82788. * @param {number} height the height of the vortex
  82789. */
  82790. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82791. if (!this._physicsEngine) {
  82792. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82793. return null;
  82794. }
  82795. if (this._physicsEngine.getImpostors().length === 0) {
  82796. return null;
  82797. }
  82798. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82799. event.dispose(false);
  82800. return event;
  82801. };
  82802. return PhysicsHelper;
  82803. }());
  82804. BABYLON.PhysicsHelper = PhysicsHelper;
  82805. /***** Radial explosion *****/
  82806. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82807. function PhysicsRadialExplosionEvent(scene) {
  82808. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82809. this._rays = [];
  82810. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82811. this._scene = scene;
  82812. }
  82813. /**
  82814. * Returns the data related to the radial explosion event (sphere & rays).
  82815. * @returns {PhysicsRadialExplosionEventData}
  82816. */
  82817. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82818. this._dataFetched = true;
  82819. return {
  82820. sphere: this._sphere,
  82821. rays: this._rays,
  82822. };
  82823. };
  82824. /**
  82825. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82826. * @param impostor
  82827. * @param {Vector3} origin the origin of the explosion
  82828. * @param {number} radius the explosion radius
  82829. * @param {number} strength the explosion strength
  82830. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82831. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82832. */
  82833. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82834. if (impostor.mass === 0) {
  82835. return null;
  82836. }
  82837. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82838. return null;
  82839. }
  82840. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82841. return null;
  82842. }
  82843. var impostorObjectCenter = impostor.getObjectCenter();
  82844. var direction = impostorObjectCenter.subtract(origin);
  82845. var ray = new BABYLON.Ray(origin, direction, radius);
  82846. this._rays.push(ray);
  82847. var hit = ray.intersectsMesh(impostor.object);
  82848. var contactPoint = hit.pickedPoint;
  82849. if (!contactPoint) {
  82850. return null;
  82851. }
  82852. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82853. if (distanceFromOrigin > radius) {
  82854. return null;
  82855. }
  82856. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82857. ? strength
  82858. : strength * (1 - (distanceFromOrigin / radius));
  82859. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82860. return { force: force, contactPoint: contactPoint };
  82861. };
  82862. /**
  82863. * Disposes the sphere.
  82864. * @param {bolean} force
  82865. */
  82866. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82867. var _this = this;
  82868. if (force === void 0) { force = true; }
  82869. if (force) {
  82870. this._sphere.dispose();
  82871. }
  82872. else {
  82873. setTimeout(function () {
  82874. if (!_this._dataFetched) {
  82875. _this._sphere.dispose();
  82876. }
  82877. }, 0);
  82878. }
  82879. };
  82880. /*** Helpers ***/
  82881. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82882. if (!this._sphere) {
  82883. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82884. this._sphere.isVisible = false;
  82885. }
  82886. };
  82887. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82888. var impostorObject = impostor.object;
  82889. this._prepareSphere();
  82890. this._sphere.position = origin;
  82891. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82892. this._sphere._updateBoundingInfo();
  82893. this._sphere.computeWorldMatrix(true);
  82894. return this._sphere.intersectsMesh(impostorObject, true);
  82895. };
  82896. return PhysicsRadialExplosionEvent;
  82897. }());
  82898. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82899. /***** Gravitational Field *****/
  82900. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82901. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82902. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82903. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82904. this._physicsHelper = physicsHelper;
  82905. this._scene = scene;
  82906. this._origin = origin;
  82907. this._radius = radius;
  82908. this._strength = strength;
  82909. this._falloff = falloff;
  82910. this._tickCallback = this._tick.bind(this);
  82911. }
  82912. /**
  82913. * Returns the data related to the gravitational field event (sphere).
  82914. * @returns {PhysicsGravitationalFieldEventData}
  82915. */
  82916. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82917. this._dataFetched = true;
  82918. return {
  82919. sphere: this._sphere,
  82920. };
  82921. };
  82922. /**
  82923. * Enables the gravitational field.
  82924. */
  82925. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82926. this._tickCallback.call(this);
  82927. this._scene.registerBeforeRender(this._tickCallback);
  82928. };
  82929. /**
  82930. * Disables the gravitational field.
  82931. */
  82932. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82933. this._scene.unregisterBeforeRender(this._tickCallback);
  82934. };
  82935. /**
  82936. * Disposes the sphere.
  82937. * @param {bolean} force
  82938. */
  82939. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82940. var _this = this;
  82941. if (force === void 0) { force = true; }
  82942. if (force) {
  82943. this._sphere.dispose();
  82944. }
  82945. else {
  82946. setTimeout(function () {
  82947. if (!_this._dataFetched) {
  82948. _this._sphere.dispose();
  82949. }
  82950. }, 0);
  82951. }
  82952. };
  82953. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82954. // Since the params won't change, we fetch the event only once
  82955. if (this._sphere) {
  82956. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82957. }
  82958. else {
  82959. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82960. if (radialExplosionEvent) {
  82961. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82962. }
  82963. }
  82964. };
  82965. return PhysicsGravitationalFieldEvent;
  82966. }());
  82967. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82968. /***** Updraft *****/
  82969. var PhysicsUpdraftEvent = /** @class */ (function () {
  82970. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82971. this._scene = _scene;
  82972. this._origin = _origin;
  82973. this._radius = _radius;
  82974. this._strength = _strength;
  82975. this._height = _height;
  82976. this._updraftMode = _updraftMode;
  82977. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82978. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82979. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82980. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82981. this._physicsEngine = this._scene.getPhysicsEngine();
  82982. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82983. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82984. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82985. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82986. }
  82987. this._tickCallback = this._tick.bind(this);
  82988. }
  82989. /**
  82990. * Returns the data related to the updraft event (cylinder).
  82991. * @returns {PhysicsUpdraftEventData}
  82992. */
  82993. PhysicsUpdraftEvent.prototype.getData = function () {
  82994. this._dataFetched = true;
  82995. return {
  82996. cylinder: this._cylinder,
  82997. };
  82998. };
  82999. /**
  83000. * Enables the updraft.
  83001. */
  83002. PhysicsUpdraftEvent.prototype.enable = function () {
  83003. this._tickCallback.call(this);
  83004. this._scene.registerBeforeRender(this._tickCallback);
  83005. };
  83006. /**
  83007. * Disables the cortex.
  83008. */
  83009. PhysicsUpdraftEvent.prototype.disable = function () {
  83010. this._scene.unregisterBeforeRender(this._tickCallback);
  83011. };
  83012. /**
  83013. * Disposes the sphere.
  83014. * @param {bolean} force
  83015. */
  83016. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83017. var _this = this;
  83018. if (force === void 0) { force = true; }
  83019. if (force) {
  83020. this._cylinder.dispose();
  83021. }
  83022. else {
  83023. setTimeout(function () {
  83024. if (!_this._dataFetched) {
  83025. _this._cylinder.dispose();
  83026. }
  83027. }, 0);
  83028. }
  83029. };
  83030. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83031. if (impostor.mass === 0) {
  83032. return null;
  83033. }
  83034. if (!this._intersectsWithCylinder(impostor)) {
  83035. return null;
  83036. }
  83037. var impostorObjectCenter = impostor.getObjectCenter();
  83038. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83039. var direction = this._originDirection;
  83040. }
  83041. else {
  83042. var direction = impostorObjectCenter.subtract(this._originTop);
  83043. }
  83044. var multiplier = this._strength * -1;
  83045. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83046. return { force: force, contactPoint: impostorObjectCenter };
  83047. };
  83048. PhysicsUpdraftEvent.prototype._tick = function () {
  83049. var _this = this;
  83050. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83051. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83052. if (!impostorForceAndContactPoint) {
  83053. return;
  83054. }
  83055. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83056. });
  83057. };
  83058. /*** Helpers ***/
  83059. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83060. if (!this._cylinder) {
  83061. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83062. height: this._height,
  83063. diameter: this._radius * 2,
  83064. }, this._scene);
  83065. this._cylinder.isVisible = false;
  83066. }
  83067. };
  83068. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83069. var impostorObject = impostor.object;
  83070. this._prepareCylinder();
  83071. this._cylinder.position = this._cylinderPosition;
  83072. return this._cylinder.intersectsMesh(impostorObject, true);
  83073. };
  83074. return PhysicsUpdraftEvent;
  83075. }());
  83076. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83077. /***** Vortex *****/
  83078. var PhysicsVortexEvent = /** @class */ (function () {
  83079. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83080. this._scene = _scene;
  83081. this._origin = _origin;
  83082. this._radius = _radius;
  83083. this._strength = _strength;
  83084. this._height = _height;
  83085. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83086. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83087. this._updraftMultiplier = 0.02;
  83088. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83089. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83090. this._physicsEngine = this._scene.getPhysicsEngine();
  83091. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83092. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83093. this._tickCallback = this._tick.bind(this);
  83094. }
  83095. /**
  83096. * Returns the data related to the vortex event (cylinder).
  83097. * @returns {PhysicsVortexEventData}
  83098. */
  83099. PhysicsVortexEvent.prototype.getData = function () {
  83100. this._dataFetched = true;
  83101. return {
  83102. cylinder: this._cylinder,
  83103. };
  83104. };
  83105. /**
  83106. * Enables the vortex.
  83107. */
  83108. PhysicsVortexEvent.prototype.enable = function () {
  83109. this._tickCallback.call(this);
  83110. this._scene.registerBeforeRender(this._tickCallback);
  83111. };
  83112. /**
  83113. * Disables the cortex.
  83114. */
  83115. PhysicsVortexEvent.prototype.disable = function () {
  83116. this._scene.unregisterBeforeRender(this._tickCallback);
  83117. };
  83118. /**
  83119. * Disposes the sphere.
  83120. * @param {bolean} force
  83121. */
  83122. PhysicsVortexEvent.prototype.dispose = function (force) {
  83123. var _this = this;
  83124. if (force === void 0) { force = true; }
  83125. if (force) {
  83126. this._cylinder.dispose();
  83127. }
  83128. else {
  83129. setTimeout(function () {
  83130. if (!_this._dataFetched) {
  83131. _this._cylinder.dispose();
  83132. }
  83133. }, 0);
  83134. }
  83135. };
  83136. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83137. if (impostor.mass === 0) {
  83138. return null;
  83139. }
  83140. if (!this._intersectsWithCylinder(impostor)) {
  83141. return null;
  83142. }
  83143. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83144. return null;
  83145. }
  83146. var impostorObjectCenter = impostor.getObjectCenter();
  83147. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  83148. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83149. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83150. var hit = ray.intersectsMesh(impostor.object);
  83151. var contactPoint = hit.pickedPoint;
  83152. if (!contactPoint) {
  83153. return null;
  83154. }
  83155. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83156. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83157. var directionToOrigin = contactPoint.normalize();
  83158. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83159. directionToOrigin = directionToOrigin.negate();
  83160. }
  83161. // TODO: find a more physically based solution
  83162. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83163. var forceX = directionToOrigin.x * this._strength / 8;
  83164. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83165. var forceZ = directionToOrigin.z * this._strength / 8;
  83166. }
  83167. else {
  83168. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83169. var forceY = this._originTop.y * this._updraftMultiplier;
  83170. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83171. }
  83172. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83173. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83174. return { force: force, contactPoint: impostorObjectCenter };
  83175. };
  83176. PhysicsVortexEvent.prototype._tick = function () {
  83177. var _this = this;
  83178. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83179. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83180. if (!impostorForceAndContactPoint) {
  83181. return;
  83182. }
  83183. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83184. });
  83185. };
  83186. /*** Helpers ***/
  83187. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83188. if (!this._cylinder) {
  83189. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83190. height: this._height,
  83191. diameter: this._radius * 2,
  83192. }, this._scene);
  83193. this._cylinder.isVisible = false;
  83194. }
  83195. };
  83196. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83197. var impostorObject = impostor.object;
  83198. this._prepareCylinder();
  83199. this._cylinder.position = this._cylinderPosition;
  83200. return this._cylinder.intersectsMesh(impostorObject, true);
  83201. };
  83202. return PhysicsVortexEvent;
  83203. }());
  83204. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83205. /***** Enums *****/
  83206. /**
  83207. * The strenght of the force in correspondence to the distance of the affected object
  83208. */
  83209. var PhysicsRadialImpulseFalloff;
  83210. (function (PhysicsRadialImpulseFalloff) {
  83211. /** Defines that impulse is constant in strength across it's whole radius */
  83212. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83213. /** DEfines that impulse gets weaker if it's further from the origin */
  83214. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83215. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83216. /**
  83217. * The strenght of the force in correspondence to the distance of the affected object
  83218. */
  83219. var PhysicsUpdraftMode;
  83220. (function (PhysicsUpdraftMode) {
  83221. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83222. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83223. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83224. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83225. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83226. })(BABYLON || (BABYLON = {}));
  83227. //# sourceMappingURL=babylon.physicsHelper.js.map
  83228. var BABYLON;
  83229. (function (BABYLON) {
  83230. var CannonJSPlugin = /** @class */ (function () {
  83231. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83232. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83233. if (iterations === void 0) { iterations = 10; }
  83234. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83235. this.name = "CannonJSPlugin";
  83236. this._physicsMaterials = new Array();
  83237. this._fixedTimeStep = 1 / 60;
  83238. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83239. this.BJSCANNON = CANNON;
  83240. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83241. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83242. this._tmpPosition = BABYLON.Vector3.Zero();
  83243. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83244. this._tmpUnityRotation = new BABYLON.Quaternion();
  83245. if (!this.isSupported()) {
  83246. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83247. return;
  83248. }
  83249. this._extendNamespace();
  83250. this.world = new this.BJSCANNON.World();
  83251. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83252. this.world.solver.iterations = iterations;
  83253. }
  83254. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83255. this.world.gravity.copy(gravity);
  83256. };
  83257. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83258. this._fixedTimeStep = timeStep;
  83259. };
  83260. CannonJSPlugin.prototype.getTimeStep = function () {
  83261. return this._fixedTimeStep;
  83262. };
  83263. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83264. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83265. };
  83266. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83267. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83268. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83269. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83270. };
  83271. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83272. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83273. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83274. impostor.physicsBody.applyForce(impulse, worldPoint);
  83275. };
  83276. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83277. //parent-child relationship. Does this impostor has a parent impostor?
  83278. if (impostor.parent) {
  83279. if (impostor.physicsBody) {
  83280. this.removePhysicsBody(impostor);
  83281. //TODO is that needed?
  83282. impostor.forceUpdate();
  83283. }
  83284. return;
  83285. }
  83286. //should a new body be created for this impostor?
  83287. if (impostor.isBodyInitRequired()) {
  83288. var shape = this._createShape(impostor);
  83289. //unregister events, if body is being changed
  83290. var oldBody = impostor.physicsBody;
  83291. if (oldBody) {
  83292. this.removePhysicsBody(impostor);
  83293. }
  83294. //create the body and material
  83295. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83296. var bodyCreationObject = {
  83297. mass: impostor.getParam("mass"),
  83298. material: material
  83299. };
  83300. // A simple extend, in case native options were used.
  83301. var nativeOptions = impostor.getParam("nativeOptions");
  83302. for (var key in nativeOptions) {
  83303. if (nativeOptions.hasOwnProperty(key)) {
  83304. bodyCreationObject[key] = nativeOptions[key];
  83305. }
  83306. }
  83307. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83308. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83309. this.world.addEventListener("preStep", impostor.beforeStep);
  83310. this.world.addEventListener("postStep", impostor.afterStep);
  83311. impostor.physicsBody.addShape(shape);
  83312. this.world.add(impostor.physicsBody);
  83313. //try to keep the body moving in the right direction by taking old properties.
  83314. //Should be tested!
  83315. if (oldBody) {
  83316. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83317. impostor.physicsBody[param].copy(oldBody[param]);
  83318. });
  83319. }
  83320. this._processChildMeshes(impostor);
  83321. }
  83322. //now update the body's transformation
  83323. this._updatePhysicsBodyTransformation(impostor);
  83324. };
  83325. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83326. var _this = this;
  83327. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83328. var currentRotation = mainImpostor.object.rotationQuaternion;
  83329. if (meshChildren.length) {
  83330. var processMesh = function (localPosition, mesh) {
  83331. if (!currentRotation || !mesh.rotationQuaternion) {
  83332. return;
  83333. }
  83334. var childImpostor = mesh.getPhysicsImpostor();
  83335. if (childImpostor) {
  83336. var parent = childImpostor.parent;
  83337. if (parent !== mainImpostor) {
  83338. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83339. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83340. if (childImpostor.physicsBody) {
  83341. _this.removePhysicsBody(childImpostor);
  83342. childImpostor.physicsBody = null;
  83343. }
  83344. childImpostor.parent = mainImpostor;
  83345. childImpostor.resetUpdateFlags();
  83346. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  83347. //Add the mass of the children.
  83348. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83349. }
  83350. }
  83351. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83352. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83353. };
  83354. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83355. }
  83356. };
  83357. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83358. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83359. this.world.removeEventListener("preStep", impostor.beforeStep);
  83360. this.world.removeEventListener("postStep", impostor.afterStep);
  83361. this.world.remove(impostor.physicsBody);
  83362. };
  83363. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83364. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83365. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83366. if (!mainBody || !connectedBody) {
  83367. return;
  83368. }
  83369. var constraint;
  83370. var jointData = impostorJoint.joint.jointData;
  83371. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83372. var constraintData = {
  83373. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83374. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83375. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83376. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83377. maxForce: jointData.nativeParams.maxForce,
  83378. collideConnected: !!jointData.collision
  83379. };
  83380. switch (impostorJoint.joint.type) {
  83381. case BABYLON.PhysicsJoint.HingeJoint:
  83382. case BABYLON.PhysicsJoint.Hinge2Joint:
  83383. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83384. break;
  83385. case BABYLON.PhysicsJoint.DistanceJoint:
  83386. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83387. break;
  83388. case BABYLON.PhysicsJoint.SpringJoint:
  83389. var springData = jointData;
  83390. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83391. restLength: springData.length,
  83392. stiffness: springData.stiffness,
  83393. damping: springData.damping,
  83394. localAnchorA: constraintData.pivotA,
  83395. localAnchorB: constraintData.pivotB
  83396. });
  83397. break;
  83398. case BABYLON.PhysicsJoint.LockJoint:
  83399. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83400. break;
  83401. case BABYLON.PhysicsJoint.PointToPointJoint:
  83402. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83403. default:
  83404. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83405. break;
  83406. }
  83407. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83408. constraint.collideConnected = !!jointData.collision;
  83409. impostorJoint.joint.physicsJoint = constraint;
  83410. //don't add spring as constraint, as it is not one.
  83411. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83412. this.world.addConstraint(constraint);
  83413. }
  83414. else {
  83415. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83416. constraint.applyForce();
  83417. });
  83418. }
  83419. };
  83420. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83421. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83422. };
  83423. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83424. var index;
  83425. var mat;
  83426. for (index = 0; index < this._physicsMaterials.length; index++) {
  83427. mat = this._physicsMaterials[index];
  83428. if (mat.friction === friction && mat.restitution === restitution) {
  83429. return mat;
  83430. }
  83431. }
  83432. var currentMat = new this.BJSCANNON.Material(name);
  83433. currentMat.friction = friction;
  83434. currentMat.restitution = restitution;
  83435. this._physicsMaterials.push(currentMat);
  83436. return currentMat;
  83437. };
  83438. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83439. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83440. };
  83441. CannonJSPlugin.prototype._createShape = function (impostor) {
  83442. var object = impostor.object;
  83443. var returnValue;
  83444. var extendSize = impostor.getObjectExtendSize();
  83445. switch (impostor.type) {
  83446. case BABYLON.PhysicsImpostor.SphereImpostor:
  83447. var radiusX = extendSize.x;
  83448. var radiusY = extendSize.y;
  83449. var radiusZ = extendSize.z;
  83450. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83451. break;
  83452. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83453. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83454. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83455. break;
  83456. case BABYLON.PhysicsImpostor.BoxImpostor:
  83457. var box = extendSize.scale(0.5);
  83458. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83459. break;
  83460. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83461. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83462. returnValue = new this.BJSCANNON.Plane();
  83463. break;
  83464. case BABYLON.PhysicsImpostor.MeshImpostor:
  83465. // should transform the vertex data to world coordinates!!
  83466. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83467. var rawFaces = object.getIndices ? object.getIndices() : [];
  83468. if (!rawVerts)
  83469. return;
  83470. // get only scale! so the object could transform correctly.
  83471. var oldPosition = object.position.clone();
  83472. var oldRotation = object.rotation && object.rotation.clone();
  83473. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83474. object.position.copyFromFloats(0, 0, 0);
  83475. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83476. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83477. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83478. var transform = object.computeWorldMatrix(true);
  83479. // convert rawVerts to object space
  83480. var temp = new Array();
  83481. var index;
  83482. for (index = 0; index < rawVerts.length; index += 3) {
  83483. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83484. }
  83485. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83486. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83487. //now set back the transformation!
  83488. object.position.copyFrom(oldPosition);
  83489. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83490. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83491. break;
  83492. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83493. var oldPosition2 = object.position.clone();
  83494. var oldRotation2 = object.rotation && object.rotation.clone();
  83495. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83496. object.position.copyFromFloats(0, 0, 0);
  83497. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83498. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83499. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83500. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83501. returnValue = this._createHeightmap(object);
  83502. object.position.copyFrom(oldPosition2);
  83503. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83504. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83505. object.computeWorldMatrix(true);
  83506. break;
  83507. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83508. returnValue = new this.BJSCANNON.Particle();
  83509. break;
  83510. }
  83511. return returnValue;
  83512. };
  83513. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83514. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83515. var transform = object.computeWorldMatrix(true);
  83516. // convert rawVerts to object space
  83517. var temp = new Array();
  83518. var index;
  83519. for (index = 0; index < pos.length; index += 3) {
  83520. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83521. }
  83522. pos = temp;
  83523. var matrix = new Array();
  83524. //For now pointDepth will not be used and will be automatically calculated.
  83525. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83526. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83527. var boundingInfo = object.getBoundingInfo();
  83528. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83529. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83530. var elementSize = dim * 2 / arraySize;
  83531. for (var i = 0; i < pos.length; i = i + 3) {
  83532. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83533. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83534. var y = -pos[i + 2] + minY;
  83535. if (!matrix[x]) {
  83536. matrix[x] = [];
  83537. }
  83538. if (!matrix[x][z]) {
  83539. matrix[x][z] = y;
  83540. }
  83541. matrix[x][z] = Math.max(y, matrix[x][z]);
  83542. }
  83543. for (var x = 0; x <= arraySize; ++x) {
  83544. if (!matrix[x]) {
  83545. var loc = 1;
  83546. while (!matrix[(x + loc) % arraySize]) {
  83547. loc++;
  83548. }
  83549. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83550. //console.log("missing x", x);
  83551. }
  83552. for (var z = 0; z <= arraySize; ++z) {
  83553. if (!matrix[x][z]) {
  83554. var loc = 1;
  83555. var newValue;
  83556. while (newValue === undefined) {
  83557. newValue = matrix[x][(z + loc++) % arraySize];
  83558. }
  83559. matrix[x][z] = newValue;
  83560. }
  83561. }
  83562. }
  83563. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83564. elementSize: elementSize
  83565. });
  83566. //For future reference, needed for body transformation
  83567. shape.minY = minY;
  83568. return shape;
  83569. };
  83570. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83571. var object = impostor.object;
  83572. //make sure it is updated...
  83573. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83574. // The delta between the mesh position and the mesh bounding box center
  83575. var bInfo = object.getBoundingInfo();
  83576. if (!bInfo)
  83577. return;
  83578. var center = impostor.getObjectCenter();
  83579. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83580. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83581. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83582. this._tmpPosition.copyFrom(center);
  83583. var quaternion = object.rotationQuaternion;
  83584. if (!quaternion) {
  83585. return;
  83586. }
  83587. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83588. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83589. //-90 DEG in X, precalculated
  83590. quaternion = quaternion.multiply(this._minus90X);
  83591. //Invert! (Precalculated, 90 deg in X)
  83592. //No need to clone. this will never change.
  83593. impostor.setDeltaRotation(this._plus90X);
  83594. }
  83595. //If it is a heightfield, if should be centered.
  83596. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83597. var mesh = object;
  83598. var boundingInfo = mesh.getBoundingInfo();
  83599. //calculate the correct body position:
  83600. var rotationQuaternion = mesh.rotationQuaternion;
  83601. mesh.rotationQuaternion = this._tmpUnityRotation;
  83602. mesh.computeWorldMatrix(true);
  83603. //get original center with no rotation
  83604. var c = center.clone();
  83605. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83606. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83607. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83608. mesh.setPreTransformMatrix(p);
  83609. mesh.computeWorldMatrix(true);
  83610. //calculate the translation
  83611. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83612. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83613. //add it inverted to the delta
  83614. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83615. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83616. //rotation is back
  83617. mesh.rotationQuaternion = rotationQuaternion;
  83618. mesh.setPreTransformMatrix(oldPivot);
  83619. mesh.computeWorldMatrix(true);
  83620. }
  83621. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83622. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83623. //this._tmpPosition.copyFrom(object.position);
  83624. }
  83625. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83626. //Now update the impostor object
  83627. impostor.physicsBody.position.copy(this._tmpPosition);
  83628. impostor.physicsBody.quaternion.copy(quaternion);
  83629. };
  83630. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83631. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83632. if (impostor.object.rotationQuaternion) {
  83633. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83634. }
  83635. };
  83636. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83637. impostor.physicsBody.position.copy(newPosition);
  83638. impostor.physicsBody.quaternion.copy(newRotation);
  83639. };
  83640. CannonJSPlugin.prototype.isSupported = function () {
  83641. return this.BJSCANNON !== undefined;
  83642. };
  83643. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83644. impostor.physicsBody.velocity.copy(velocity);
  83645. };
  83646. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83647. impostor.physicsBody.angularVelocity.copy(velocity);
  83648. };
  83649. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83650. var v = impostor.physicsBody.velocity;
  83651. if (!v) {
  83652. return null;
  83653. }
  83654. return new BABYLON.Vector3(v.x, v.y, v.z);
  83655. };
  83656. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83657. var v = impostor.physicsBody.angularVelocity;
  83658. if (!v) {
  83659. return null;
  83660. }
  83661. return new BABYLON.Vector3(v.x, v.y, v.z);
  83662. };
  83663. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83664. impostor.physicsBody.mass = mass;
  83665. impostor.physicsBody.updateMassProperties();
  83666. };
  83667. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83668. return impostor.physicsBody.mass;
  83669. };
  83670. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83671. return impostor.physicsBody.material.friction;
  83672. };
  83673. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83674. impostor.physicsBody.material.friction = friction;
  83675. };
  83676. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83677. return impostor.physicsBody.material.restitution;
  83678. };
  83679. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83680. impostor.physicsBody.material.restitution = restitution;
  83681. };
  83682. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83683. impostor.physicsBody.sleep();
  83684. };
  83685. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83686. impostor.physicsBody.wakeUp();
  83687. };
  83688. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83689. joint.physicsJoint.distance = maxDistance;
  83690. };
  83691. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83692. // if (!motorIndex) {
  83693. // joint.physicsJoint.enableMotor();
  83694. // }
  83695. // }
  83696. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83697. // if (!motorIndex) {
  83698. // joint.physicsJoint.disableMotor();
  83699. // }
  83700. // }
  83701. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83702. if (!motorIndex) {
  83703. joint.physicsJoint.enableMotor();
  83704. joint.physicsJoint.setMotorSpeed(speed);
  83705. if (maxForce) {
  83706. this.setLimit(joint, maxForce);
  83707. }
  83708. }
  83709. };
  83710. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83711. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83712. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83713. };
  83714. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83715. var body = impostor.physicsBody;
  83716. mesh.position.x = body.position.x;
  83717. mesh.position.y = body.position.y;
  83718. mesh.position.z = body.position.z;
  83719. if (mesh.rotationQuaternion) {
  83720. mesh.rotationQuaternion.x = body.quaternion.x;
  83721. mesh.rotationQuaternion.y = body.quaternion.y;
  83722. mesh.rotationQuaternion.z = body.quaternion.z;
  83723. mesh.rotationQuaternion.w = body.quaternion.w;
  83724. }
  83725. };
  83726. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83727. var shape = impostor.physicsBody.shapes[0];
  83728. return shape.boundingSphereRadius;
  83729. };
  83730. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83731. var shape = impostor.physicsBody.shapes[0];
  83732. result.x = shape.halfExtents.x * 2;
  83733. result.y = shape.halfExtents.y * 2;
  83734. result.z = shape.halfExtents.z * 2;
  83735. };
  83736. CannonJSPlugin.prototype.dispose = function () {
  83737. };
  83738. CannonJSPlugin.prototype._extendNamespace = function () {
  83739. //this will force cannon to execute at least one step when using interpolation
  83740. var step_tmp1 = new this.BJSCANNON.Vec3();
  83741. var Engine = this.BJSCANNON;
  83742. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83743. maxSubSteps = maxSubSteps || 10;
  83744. timeSinceLastCalled = timeSinceLastCalled || 0;
  83745. if (timeSinceLastCalled === 0) {
  83746. this.internalStep(dt);
  83747. this.time += dt;
  83748. }
  83749. else {
  83750. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83751. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83752. var t0 = performance.now();
  83753. for (var i = 0; i !== internalSteps; i++) {
  83754. this.internalStep(dt);
  83755. if (performance.now() - t0 > dt * 1000) {
  83756. break;
  83757. }
  83758. }
  83759. this.time += timeSinceLastCalled;
  83760. var h = this.time % dt;
  83761. var h_div_dt = h / dt;
  83762. var interpvelo = step_tmp1;
  83763. var bodies = this.bodies;
  83764. for (var j = 0; j !== bodies.length; j++) {
  83765. var b = bodies[j];
  83766. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83767. b.position.vsub(b.previousPosition, interpvelo);
  83768. interpvelo.scale(h_div_dt, interpvelo);
  83769. b.position.vadd(interpvelo, b.interpolatedPosition);
  83770. }
  83771. else {
  83772. b.interpolatedPosition.copy(b.position);
  83773. b.interpolatedQuaternion.copy(b.quaternion);
  83774. }
  83775. }
  83776. }
  83777. };
  83778. };
  83779. return CannonJSPlugin;
  83780. }());
  83781. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83782. })(BABYLON || (BABYLON = {}));
  83783. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83784. var BABYLON;
  83785. (function (BABYLON) {
  83786. var OimoJSPlugin = /** @class */ (function () {
  83787. function OimoJSPlugin(iterations) {
  83788. this.name = "OimoJSPlugin";
  83789. this._tmpImpostorsArray = [];
  83790. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83791. this.BJSOIMO = OIMO;
  83792. this.world = new this.BJSOIMO.World({
  83793. iterations: iterations
  83794. });
  83795. this.world.clear();
  83796. }
  83797. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83798. this.world.gravity.copy(gravity);
  83799. };
  83800. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83801. this.world.timeStep = timeStep;
  83802. };
  83803. OimoJSPlugin.prototype.getTimeStep = function () {
  83804. return this.world.timeStep;
  83805. };
  83806. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83807. var _this = this;
  83808. impostors.forEach(function (impostor) {
  83809. impostor.beforeStep();
  83810. });
  83811. this.world.step();
  83812. impostors.forEach(function (impostor) {
  83813. impostor.afterStep();
  83814. //update the ordered impostors array
  83815. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83816. });
  83817. //check for collisions
  83818. var contact = this.world.contacts;
  83819. while (contact !== null) {
  83820. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83821. contact = contact.next;
  83822. continue;
  83823. }
  83824. //is this body colliding with any other? get the impostor
  83825. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83826. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83827. if (!mainImpostor || !collidingImpostor) {
  83828. contact = contact.next;
  83829. continue;
  83830. }
  83831. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83832. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83833. contact = contact.next;
  83834. }
  83835. };
  83836. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83837. var mass = impostor.physicsBody.mass;
  83838. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83839. };
  83840. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83841. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83842. this.applyImpulse(impostor, force, contactPoint);
  83843. };
  83844. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83845. var _this = this;
  83846. //parent-child relationship. Does this impostor has a parent impostor?
  83847. if (impostor.parent) {
  83848. if (impostor.physicsBody) {
  83849. this.removePhysicsBody(impostor);
  83850. //TODO is that needed?
  83851. impostor.forceUpdate();
  83852. }
  83853. return;
  83854. }
  83855. if (impostor.isBodyInitRequired()) {
  83856. var bodyConfig = {
  83857. name: impostor.uniqueId,
  83858. //Oimo must have mass, also for static objects.
  83859. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83860. size: [],
  83861. type: [],
  83862. pos: [],
  83863. posShape: [],
  83864. rot: [],
  83865. rotShape: [],
  83866. move: impostor.getParam("mass") !== 0,
  83867. density: impostor.getParam("mass"),
  83868. friction: impostor.getParam("friction"),
  83869. restitution: impostor.getParam("restitution"),
  83870. //Supporting older versions of Oimo
  83871. world: this.world
  83872. };
  83873. var impostors = [impostor];
  83874. var addToArray = function (parent) {
  83875. if (!parent.getChildMeshes)
  83876. return;
  83877. parent.getChildMeshes().forEach(function (m) {
  83878. if (m.physicsImpostor) {
  83879. impostors.push(m.physicsImpostor);
  83880. //m.physicsImpostor._init();
  83881. }
  83882. });
  83883. };
  83884. addToArray(impostor.object);
  83885. var checkWithEpsilon_1 = function (value) {
  83886. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83887. };
  83888. impostors.forEach(function (i) {
  83889. if (!i.object.rotationQuaternion) {
  83890. return;
  83891. }
  83892. //get the correct bounding box
  83893. var oldQuaternion = i.object.rotationQuaternion;
  83894. var rot = oldQuaternion.toEulerAngles();
  83895. var extendSize = i.getObjectExtendSize();
  83896. var radToDeg = 57.295779513082320876;
  83897. if (i === impostor) {
  83898. var center = impostor.getObjectCenter();
  83899. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83900. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83901. //Can also use Array.prototype.push.apply
  83902. bodyConfig.pos.push(center.x);
  83903. bodyConfig.pos.push(center.y);
  83904. bodyConfig.pos.push(center.z);
  83905. bodyConfig.posShape.push(0, 0, 0);
  83906. //tmp solution
  83907. bodyConfig.rot.push(rot.x * radToDeg);
  83908. bodyConfig.rot.push(rot.y * radToDeg);
  83909. bodyConfig.rot.push(rot.z * radToDeg);
  83910. bodyConfig.rotShape.push(0, 0, 0);
  83911. }
  83912. else {
  83913. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83914. bodyConfig.posShape.push(localPosition.x);
  83915. bodyConfig.posShape.push(localPosition.y);
  83916. bodyConfig.posShape.push(localPosition.z);
  83917. bodyConfig.pos.push(0, 0, 0);
  83918. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83919. bodyConfig.rot.push(0);
  83920. bodyConfig.rot.push(0);
  83921. bodyConfig.rot.push(0);
  83922. bodyConfig.rotShape.push(rot.x * radToDeg);
  83923. bodyConfig.rotShape.push(rot.y * radToDeg);
  83924. bodyConfig.rotShape.push(rot.z * radToDeg);
  83925. }
  83926. // register mesh
  83927. switch (i.type) {
  83928. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83929. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83930. case BABYLON.PhysicsImpostor.SphereImpostor:
  83931. var radiusX = extendSize.x;
  83932. var radiusY = extendSize.y;
  83933. var radiusZ = extendSize.z;
  83934. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83935. bodyConfig.type.push('sphere');
  83936. //due to the way oimo works with compounds, add 3 times
  83937. bodyConfig.size.push(size);
  83938. bodyConfig.size.push(size);
  83939. bodyConfig.size.push(size);
  83940. break;
  83941. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83942. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83943. var sizeY = checkWithEpsilon_1(extendSize.y);
  83944. bodyConfig.type.push('cylinder');
  83945. bodyConfig.size.push(sizeX);
  83946. bodyConfig.size.push(sizeY);
  83947. //due to the way oimo works with compounds, add one more value.
  83948. bodyConfig.size.push(sizeY);
  83949. break;
  83950. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83951. case BABYLON.PhysicsImpostor.BoxImpostor:
  83952. default:
  83953. var sizeX = checkWithEpsilon_1(extendSize.x);
  83954. var sizeY = checkWithEpsilon_1(extendSize.y);
  83955. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83956. bodyConfig.type.push('box');
  83957. //if (i === impostor) {
  83958. bodyConfig.size.push(sizeX);
  83959. bodyConfig.size.push(sizeY);
  83960. bodyConfig.size.push(sizeZ);
  83961. //} else {
  83962. // bodyConfig.size.push(0,0,0);
  83963. //}
  83964. break;
  83965. }
  83966. //actually not needed, but hey...
  83967. i.object.rotationQuaternion = oldQuaternion;
  83968. });
  83969. impostor.physicsBody = this.world.add(bodyConfig);
  83970. }
  83971. else {
  83972. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83973. }
  83974. impostor.setDeltaPosition(this._tmpPositionVector);
  83975. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83976. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83977. };
  83978. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83979. //impostor.physicsBody.dispose();
  83980. //Same as : (older oimo versions)
  83981. this.world.removeRigidBody(impostor.physicsBody);
  83982. };
  83983. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83984. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83985. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83986. if (!mainBody || !connectedBody) {
  83987. return;
  83988. }
  83989. var jointData = impostorJoint.joint.jointData;
  83990. var options = jointData.nativeParams || {};
  83991. var type;
  83992. var nativeJointData = {
  83993. body1: mainBody,
  83994. body2: connectedBody,
  83995. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83996. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83997. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83998. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83999. min: options.min,
  84000. max: options.max,
  84001. collision: options.collision || jointData.collision,
  84002. spring: options.spring,
  84003. //supporting older version of Oimo
  84004. world: this.world
  84005. };
  84006. switch (impostorJoint.joint.type) {
  84007. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84008. type = "jointBall";
  84009. break;
  84010. case BABYLON.PhysicsJoint.SpringJoint:
  84011. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84012. var springData = jointData;
  84013. nativeJointData.min = springData.length || nativeJointData.min;
  84014. //Max should also be set, just make sure it is at least min
  84015. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84016. case BABYLON.PhysicsJoint.DistanceJoint:
  84017. type = "jointDistance";
  84018. nativeJointData.max = jointData.maxDistance;
  84019. break;
  84020. case BABYLON.PhysicsJoint.PrismaticJoint:
  84021. type = "jointPrisme";
  84022. break;
  84023. case BABYLON.PhysicsJoint.SliderJoint:
  84024. type = "jointSlide";
  84025. break;
  84026. case BABYLON.PhysicsJoint.WheelJoint:
  84027. type = "jointWheel";
  84028. break;
  84029. case BABYLON.PhysicsJoint.HingeJoint:
  84030. default:
  84031. type = "jointHinge";
  84032. break;
  84033. }
  84034. nativeJointData.type = type;
  84035. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84036. };
  84037. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84038. //Bug in Oimo prevents us from disposing a joint in the playground
  84039. //joint.joint.physicsJoint.dispose();
  84040. //So we will bruteforce it!
  84041. try {
  84042. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84043. }
  84044. catch (e) {
  84045. BABYLON.Tools.Warn(e);
  84046. }
  84047. };
  84048. OimoJSPlugin.prototype.isSupported = function () {
  84049. return this.BJSOIMO !== undefined;
  84050. };
  84051. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84052. if (!impostor.physicsBody.sleeping) {
  84053. //TODO check that
  84054. /*if (impostor.physicsBody.shapes.next) {
  84055. var parentShape = this._getLastShape(impostor.physicsBody);
  84056. impostor.object.position.copyFrom(parentShape.position);
  84057. console.log(parentShape.position);
  84058. } else {*/
  84059. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84060. //}
  84061. if (impostor.object.rotationQuaternion) {
  84062. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84063. }
  84064. }
  84065. };
  84066. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84067. var body = impostor.physicsBody;
  84068. body.position.copy(newPosition);
  84069. body.orientation.copy(newRotation);
  84070. body.syncShapes();
  84071. body.awake();
  84072. };
  84073. /*private _getLastShape(body: any): any {
  84074. var lastShape = body.shapes;
  84075. while (lastShape.next) {
  84076. lastShape = lastShape.next;
  84077. }
  84078. return lastShape;
  84079. }*/
  84080. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84081. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84082. };
  84083. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84084. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84085. };
  84086. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84087. var v = impostor.physicsBody.linearVelocity;
  84088. if (!v) {
  84089. return null;
  84090. }
  84091. return new BABYLON.Vector3(v.x, v.y, v.z);
  84092. };
  84093. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84094. var v = impostor.physicsBody.angularVelocity;
  84095. if (!v) {
  84096. return null;
  84097. }
  84098. return new BABYLON.Vector3(v.x, v.y, v.z);
  84099. };
  84100. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84101. var staticBody = mass === 0;
  84102. //this will actually set the body's density and not its mass.
  84103. //But this is how oimo treats the mass variable.
  84104. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84105. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84106. };
  84107. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84108. return impostor.physicsBody.shapes.density;
  84109. };
  84110. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84111. return impostor.physicsBody.shapes.friction;
  84112. };
  84113. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84114. impostor.physicsBody.shapes.friction = friction;
  84115. };
  84116. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84117. return impostor.physicsBody.shapes.restitution;
  84118. };
  84119. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84120. impostor.physicsBody.shapes.restitution = restitution;
  84121. };
  84122. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84123. impostor.physicsBody.sleep();
  84124. };
  84125. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84126. impostor.physicsBody.awake();
  84127. };
  84128. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84129. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84130. if (minDistance !== void 0) {
  84131. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84132. }
  84133. };
  84134. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84135. //TODO separate rotational and transational motors.
  84136. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84137. if (motor) {
  84138. motor.setMotor(speed, maxForce);
  84139. }
  84140. };
  84141. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84142. //TODO separate rotational and transational motors.
  84143. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84144. if (motor) {
  84145. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84146. }
  84147. };
  84148. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84149. var body = impostor.physicsBody;
  84150. mesh.position.x = body.position.x;
  84151. mesh.position.y = body.position.y;
  84152. mesh.position.z = body.position.z;
  84153. if (mesh.rotationQuaternion) {
  84154. mesh.rotationQuaternion.x = body.orientation.x;
  84155. mesh.rotationQuaternion.y = body.orientation.y;
  84156. mesh.rotationQuaternion.z = body.orientation.z;
  84157. mesh.rotationQuaternion.w = body.orientation.s;
  84158. }
  84159. };
  84160. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84161. return impostor.physicsBody.shapes.radius;
  84162. };
  84163. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84164. var shape = impostor.physicsBody.shapes;
  84165. result.x = shape.halfWidth * 2;
  84166. result.y = shape.halfHeight * 2;
  84167. result.z = shape.halfDepth * 2;
  84168. };
  84169. OimoJSPlugin.prototype.dispose = function () {
  84170. this.world.clear();
  84171. };
  84172. return OimoJSPlugin;
  84173. }());
  84174. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84175. })(BABYLON || (BABYLON = {}));
  84176. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84177. var BABYLON;
  84178. (function (BABYLON) {
  84179. /*
  84180. * Based on jsTGALoader - Javascript loader for TGA file
  84181. * By Vincent Thibault
  84182. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84183. */
  84184. var TGATools = /** @class */ (function () {
  84185. function TGATools() {
  84186. }
  84187. TGATools.GetTGAHeader = function (data) {
  84188. var offset = 0;
  84189. var header = {
  84190. id_length: data[offset++],
  84191. colormap_type: data[offset++],
  84192. image_type: data[offset++],
  84193. colormap_index: data[offset++] | data[offset++] << 8,
  84194. colormap_length: data[offset++] | data[offset++] << 8,
  84195. colormap_size: data[offset++],
  84196. origin: [
  84197. data[offset++] | data[offset++] << 8,
  84198. data[offset++] | data[offset++] << 8
  84199. ],
  84200. width: data[offset++] | data[offset++] << 8,
  84201. height: data[offset++] | data[offset++] << 8,
  84202. pixel_size: data[offset++],
  84203. flags: data[offset++]
  84204. };
  84205. return header;
  84206. };
  84207. TGATools.UploadContent = function (gl, data) {
  84208. // Not enough data to contain header ?
  84209. if (data.length < 19) {
  84210. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84211. return;
  84212. }
  84213. // Read Header
  84214. var offset = 18;
  84215. var header = TGATools.GetTGAHeader(data);
  84216. // Assume it's a valid Targa file.
  84217. if (header.id_length + offset > data.length) {
  84218. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84219. return;
  84220. }
  84221. // Skip not needed data
  84222. offset += header.id_length;
  84223. var use_rle = false;
  84224. var use_pal = false;
  84225. var use_grey = false;
  84226. // Get some informations.
  84227. switch (header.image_type) {
  84228. case TGATools._TYPE_RLE_INDEXED:
  84229. use_rle = true;
  84230. case TGATools._TYPE_INDEXED:
  84231. use_pal = true;
  84232. break;
  84233. case TGATools._TYPE_RLE_RGB:
  84234. use_rle = true;
  84235. case TGATools._TYPE_RGB:
  84236. // use_rgb = true;
  84237. break;
  84238. case TGATools._TYPE_RLE_GREY:
  84239. use_rle = true;
  84240. case TGATools._TYPE_GREY:
  84241. use_grey = true;
  84242. break;
  84243. }
  84244. var pixel_data;
  84245. // var numAlphaBits = header.flags & 0xf;
  84246. var pixel_size = header.pixel_size >> 3;
  84247. var pixel_total = header.width * header.height * pixel_size;
  84248. // Read palettes
  84249. var palettes;
  84250. if (use_pal) {
  84251. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84252. }
  84253. // Read LRE
  84254. if (use_rle) {
  84255. pixel_data = new Uint8Array(pixel_total);
  84256. var c, count, i;
  84257. var localOffset = 0;
  84258. var pixels = new Uint8Array(pixel_size);
  84259. while (offset < pixel_total && localOffset < pixel_total) {
  84260. c = data[offset++];
  84261. count = (c & 0x7f) + 1;
  84262. // RLE pixels
  84263. if (c & 0x80) {
  84264. // Bind pixel tmp array
  84265. for (i = 0; i < pixel_size; ++i) {
  84266. pixels[i] = data[offset++];
  84267. }
  84268. // Copy pixel array
  84269. for (i = 0; i < count; ++i) {
  84270. pixel_data.set(pixels, localOffset + i * pixel_size);
  84271. }
  84272. localOffset += pixel_size * count;
  84273. }
  84274. // Raw pixels
  84275. else {
  84276. count *= pixel_size;
  84277. for (i = 0; i < count; ++i) {
  84278. pixel_data[localOffset + i] = data[offset++];
  84279. }
  84280. localOffset += count;
  84281. }
  84282. }
  84283. }
  84284. // RAW Pixels
  84285. else {
  84286. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84287. }
  84288. // Load to texture
  84289. var x_start, y_start, x_step, y_step, y_end, x_end;
  84290. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84291. default:
  84292. case TGATools._ORIGIN_UL:
  84293. x_start = 0;
  84294. x_step = 1;
  84295. x_end = header.width;
  84296. y_start = 0;
  84297. y_step = 1;
  84298. y_end = header.height;
  84299. break;
  84300. case TGATools._ORIGIN_BL:
  84301. x_start = 0;
  84302. x_step = 1;
  84303. x_end = header.width;
  84304. y_start = header.height - 1;
  84305. y_step = -1;
  84306. y_end = -1;
  84307. break;
  84308. case TGATools._ORIGIN_UR:
  84309. x_start = header.width - 1;
  84310. x_step = -1;
  84311. x_end = -1;
  84312. y_start = 0;
  84313. y_step = 1;
  84314. y_end = header.height;
  84315. break;
  84316. case TGATools._ORIGIN_BR:
  84317. x_start = header.width - 1;
  84318. x_step = -1;
  84319. x_end = -1;
  84320. y_start = header.height - 1;
  84321. y_step = -1;
  84322. y_end = -1;
  84323. break;
  84324. }
  84325. // Load the specify method
  84326. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84327. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84328. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84329. };
  84330. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84331. var image = pixel_data, colormap = palettes;
  84332. var width = header.width, height = header.height;
  84333. var color, i = 0, x, y;
  84334. var imageData = new Uint8Array(width * height * 4);
  84335. for (y = y_start; y !== y_end; y += y_step) {
  84336. for (x = x_start; x !== x_end; x += x_step, i++) {
  84337. color = image[i];
  84338. imageData[(x + width * y) * 4 + 3] = 255;
  84339. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84340. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84341. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84342. }
  84343. }
  84344. return imageData;
  84345. };
  84346. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84347. var image = pixel_data;
  84348. var width = header.width, height = header.height;
  84349. var color, i = 0, x, y;
  84350. var imageData = new Uint8Array(width * height * 4);
  84351. for (y = y_start; y !== y_end; y += y_step) {
  84352. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84353. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84354. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84355. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84356. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84357. imageData[(x + width * y) * 4 + 0] = r;
  84358. imageData[(x + width * y) * 4 + 1] = g;
  84359. imageData[(x + width * y) * 4 + 2] = b;
  84360. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84361. }
  84362. }
  84363. return imageData;
  84364. };
  84365. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84366. var image = pixel_data;
  84367. var width = header.width, height = header.height;
  84368. var i = 0, x, y;
  84369. var imageData = new Uint8Array(width * height * 4);
  84370. for (y = y_start; y !== y_end; y += y_step) {
  84371. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84372. imageData[(x + width * y) * 4 + 3] = 255;
  84373. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84374. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84375. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84376. }
  84377. }
  84378. return imageData;
  84379. };
  84380. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84381. var image = pixel_data;
  84382. var width = header.width, height = header.height;
  84383. var i = 0, x, y;
  84384. var imageData = new Uint8Array(width * height * 4);
  84385. for (y = y_start; y !== y_end; y += y_step) {
  84386. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84387. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84388. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84389. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84390. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84391. }
  84392. }
  84393. return imageData;
  84394. };
  84395. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84396. var image = pixel_data;
  84397. var width = header.width, height = header.height;
  84398. var color, i = 0, x, y;
  84399. var imageData = new Uint8Array(width * height * 4);
  84400. for (y = y_start; y !== y_end; y += y_step) {
  84401. for (x = x_start; x !== x_end; x += x_step, i++) {
  84402. color = image[i];
  84403. imageData[(x + width * y) * 4 + 0] = color;
  84404. imageData[(x + width * y) * 4 + 1] = color;
  84405. imageData[(x + width * y) * 4 + 2] = color;
  84406. imageData[(x + width * y) * 4 + 3] = 255;
  84407. }
  84408. }
  84409. return imageData;
  84410. };
  84411. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84412. var image = pixel_data;
  84413. var width = header.width, height = header.height;
  84414. var i = 0, x, y;
  84415. var imageData = new Uint8Array(width * height * 4);
  84416. for (y = y_start; y !== y_end; y += y_step) {
  84417. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84418. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84419. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84420. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84421. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84422. }
  84423. }
  84424. return imageData;
  84425. };
  84426. //private static _TYPE_NO_DATA = 0;
  84427. TGATools._TYPE_INDEXED = 1;
  84428. TGATools._TYPE_RGB = 2;
  84429. TGATools._TYPE_GREY = 3;
  84430. TGATools._TYPE_RLE_INDEXED = 9;
  84431. TGATools._TYPE_RLE_RGB = 10;
  84432. TGATools._TYPE_RLE_GREY = 11;
  84433. TGATools._ORIGIN_MASK = 0x30;
  84434. TGATools._ORIGIN_SHIFT = 0x04;
  84435. TGATools._ORIGIN_BL = 0x00;
  84436. TGATools._ORIGIN_BR = 0x01;
  84437. TGATools._ORIGIN_UL = 0x02;
  84438. TGATools._ORIGIN_UR = 0x03;
  84439. return TGATools;
  84440. }());
  84441. BABYLON.TGATools = TGATools;
  84442. })(BABYLON || (BABYLON = {}));
  84443. //# sourceMappingURL=babylon.tga.js.map
  84444. var BABYLON;
  84445. (function (BABYLON) {
  84446. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84447. // All values and structures referenced from:
  84448. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84449. var DDS_MAGIC = 0x20534444;
  84450. var
  84451. //DDSD_CAPS = 0x1,
  84452. //DDSD_HEIGHT = 0x2,
  84453. //DDSD_WIDTH = 0x4,
  84454. //DDSD_PITCH = 0x8,
  84455. //DDSD_PIXELFORMAT = 0x1000,
  84456. DDSD_MIPMAPCOUNT = 0x20000;
  84457. //DDSD_LINEARSIZE = 0x80000,
  84458. //DDSD_DEPTH = 0x800000;
  84459. // var DDSCAPS_COMPLEX = 0x8,
  84460. // DDSCAPS_MIPMAP = 0x400000,
  84461. // DDSCAPS_TEXTURE = 0x1000;
  84462. var DDSCAPS2_CUBEMAP = 0x200;
  84463. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84464. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84465. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84466. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84467. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84468. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84469. // DDSCAPS2_VOLUME = 0x200000;
  84470. var
  84471. //DDPF_ALPHAPIXELS = 0x1,
  84472. //DDPF_ALPHA = 0x2,
  84473. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84474. //DDPF_YUV = 0x200,
  84475. DDPF_LUMINANCE = 0x20000;
  84476. function FourCCToInt32(value) {
  84477. return value.charCodeAt(0) +
  84478. (value.charCodeAt(1) << 8) +
  84479. (value.charCodeAt(2) << 16) +
  84480. (value.charCodeAt(3) << 24);
  84481. }
  84482. function Int32ToFourCC(value) {
  84483. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84484. }
  84485. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84486. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84487. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84488. var FOURCC_DX10 = FourCCToInt32("DX10");
  84489. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84490. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84491. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84492. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84493. var headerLengthInt = 31; // The header length in 32 bit ints
  84494. // Offsets into the header array
  84495. var off_magic = 0;
  84496. var off_size = 1;
  84497. var off_flags = 2;
  84498. var off_height = 3;
  84499. var off_width = 4;
  84500. var off_mipmapCount = 7;
  84501. var off_pfFlags = 20;
  84502. var off_pfFourCC = 21;
  84503. var off_RGBbpp = 22;
  84504. var off_RMask = 23;
  84505. var off_GMask = 24;
  84506. var off_BMask = 25;
  84507. var off_AMask = 26;
  84508. // var off_caps1 = 27;
  84509. var off_caps2 = 28;
  84510. // var off_caps3 = 29;
  84511. // var off_caps4 = 30;
  84512. var off_dxgiFormat = 32;
  84513. ;
  84514. var DDSTools = /** @class */ (function () {
  84515. function DDSTools() {
  84516. }
  84517. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84518. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84519. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84520. var mipmapCount = 1;
  84521. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84522. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84523. }
  84524. var fourCC = header[off_pfFourCC];
  84525. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84526. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84527. switch (fourCC) {
  84528. case FOURCC_D3DFMT_R16G16B16A16F:
  84529. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84530. break;
  84531. case FOURCC_D3DFMT_R32G32B32A32F:
  84532. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84533. break;
  84534. case FOURCC_DX10:
  84535. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84536. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84537. break;
  84538. }
  84539. }
  84540. return {
  84541. width: header[off_width],
  84542. height: header[off_height],
  84543. mipmapCount: mipmapCount,
  84544. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84545. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84546. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84547. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84548. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84549. dxgiFormat: dxgiFormat,
  84550. textureType: textureType
  84551. };
  84552. };
  84553. DDSTools._ToHalfFloat = function (value) {
  84554. if (!DDSTools._FloatView) {
  84555. DDSTools._FloatView = new Float32Array(1);
  84556. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84557. }
  84558. DDSTools._FloatView[0] = value;
  84559. var x = DDSTools._Int32View[0];
  84560. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84561. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84562. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84563. /* If zero, or denormal, or exponent underflows too much for a denormal
  84564. * half, return signed zero. */
  84565. if (e < 103) {
  84566. return bits;
  84567. }
  84568. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84569. if (e > 142) {
  84570. bits |= 0x7c00;
  84571. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84572. * not Inf, so make sure we set one mantissa bit too. */
  84573. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84574. return bits;
  84575. }
  84576. /* If exponent underflows but not too much, return a denormal */
  84577. if (e < 113) {
  84578. m |= 0x0800;
  84579. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84580. * to 1, which is OK. */
  84581. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84582. return bits;
  84583. }
  84584. bits |= ((e - 112) << 10) | (m >> 1);
  84585. bits += m & 1;
  84586. return bits;
  84587. };
  84588. DDSTools._FromHalfFloat = function (value) {
  84589. var s = (value & 0x8000) >> 15;
  84590. var e = (value & 0x7C00) >> 10;
  84591. var f = value & 0x03FF;
  84592. if (e === 0) {
  84593. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84594. }
  84595. else if (e == 0x1F) {
  84596. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84597. }
  84598. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84599. };
  84600. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84601. var destArray = new Float32Array(dataLength);
  84602. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84603. var index = 0;
  84604. for (var y = 0; y < height; y++) {
  84605. for (var x = 0; x < width; x++) {
  84606. var srcPos = (x + y * width) * 4;
  84607. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84608. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84609. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84610. if (DDSTools.StoreLODInAlphaChannel) {
  84611. destArray[index + 3] = lod;
  84612. }
  84613. else {
  84614. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84615. }
  84616. index += 4;
  84617. }
  84618. }
  84619. return destArray;
  84620. };
  84621. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84622. if (DDSTools.StoreLODInAlphaChannel) {
  84623. var destArray = new Uint16Array(dataLength);
  84624. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84625. var index = 0;
  84626. for (var y = 0; y < height; y++) {
  84627. for (var x = 0; x < width; x++) {
  84628. var srcPos = (x + y * width) * 4;
  84629. destArray[index] = srcData[srcPos];
  84630. destArray[index + 1] = srcData[srcPos + 1];
  84631. destArray[index + 2] = srcData[srcPos + 2];
  84632. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84633. index += 4;
  84634. }
  84635. }
  84636. return destArray;
  84637. }
  84638. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84639. };
  84640. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84641. if (DDSTools.StoreLODInAlphaChannel) {
  84642. var destArray = new Float32Array(dataLength);
  84643. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84644. var index = 0;
  84645. for (var y = 0; y < height; y++) {
  84646. for (var x = 0; x < width; x++) {
  84647. var srcPos = (x + y * width) * 4;
  84648. destArray[index] = srcData[srcPos];
  84649. destArray[index + 1] = srcData[srcPos + 1];
  84650. destArray[index + 2] = srcData[srcPos + 2];
  84651. destArray[index + 3] = lod;
  84652. index += 4;
  84653. }
  84654. }
  84655. return destArray;
  84656. }
  84657. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84658. };
  84659. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84660. var destArray = new Uint8Array(dataLength);
  84661. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84662. var index = 0;
  84663. for (var y = 0; y < height; y++) {
  84664. for (var x = 0; x < width; x++) {
  84665. var srcPos = (x + y * width) * 4;
  84666. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84667. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84668. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84669. if (DDSTools.StoreLODInAlphaChannel) {
  84670. destArray[index + 3] = lod;
  84671. }
  84672. else {
  84673. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84674. }
  84675. index += 4;
  84676. }
  84677. }
  84678. return destArray;
  84679. };
  84680. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84681. var destArray = new Uint8Array(dataLength);
  84682. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84683. var index = 0;
  84684. for (var y = 0; y < height; y++) {
  84685. for (var x = 0; x < width; x++) {
  84686. var srcPos = (x + y * width) * 4;
  84687. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84688. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84689. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84690. if (DDSTools.StoreLODInAlphaChannel) {
  84691. destArray[index + 3] = lod;
  84692. }
  84693. else {
  84694. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84695. }
  84696. index += 4;
  84697. }
  84698. }
  84699. return destArray;
  84700. };
  84701. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84702. var byteArray = new Uint8Array(dataLength);
  84703. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84704. var index = 0;
  84705. for (var y = 0; y < height; y++) {
  84706. for (var x = 0; x < width; x++) {
  84707. var srcPos = (x + y * width) * 4;
  84708. byteArray[index] = srcData[srcPos + rOffset];
  84709. byteArray[index + 1] = srcData[srcPos + gOffset];
  84710. byteArray[index + 2] = srcData[srcPos + bOffset];
  84711. byteArray[index + 3] = srcData[srcPos + aOffset];
  84712. index += 4;
  84713. }
  84714. }
  84715. return byteArray;
  84716. };
  84717. DDSTools._ExtractLongWordOrder = function (value) {
  84718. if (value === 0 || value === 255 || value === -16777216) {
  84719. return 0;
  84720. }
  84721. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84722. };
  84723. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84724. var byteArray = new Uint8Array(dataLength);
  84725. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84726. var index = 0;
  84727. for (var y = 0; y < height; y++) {
  84728. for (var x = 0; x < width; x++) {
  84729. var srcPos = (x + y * width) * 3;
  84730. byteArray[index] = srcData[srcPos + rOffset];
  84731. byteArray[index + 1] = srcData[srcPos + gOffset];
  84732. byteArray[index + 2] = srcData[srcPos + bOffset];
  84733. index += 3;
  84734. }
  84735. }
  84736. return byteArray;
  84737. };
  84738. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84739. var byteArray = new Uint8Array(dataLength);
  84740. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84741. var index = 0;
  84742. for (var y = 0; y < height; y++) {
  84743. for (var x = 0; x < width; x++) {
  84744. var srcPos = (x + y * width);
  84745. byteArray[index] = srcData[srcPos];
  84746. index++;
  84747. }
  84748. }
  84749. return byteArray;
  84750. };
  84751. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84752. if (lodIndex === void 0) { lodIndex = -1; }
  84753. var sphericalPolynomialFaces = null;
  84754. if (info.sphericalPolynomial) {
  84755. sphericalPolynomialFaces = new Array();
  84756. }
  84757. var ext = engine.getCaps().s3tc;
  84758. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84759. var fourCC, width, height, dataLength = 0, dataOffset;
  84760. var byteArray, mipmapCount, mip;
  84761. var internalFormat = 0;
  84762. var format = 0;
  84763. var blockBytes = 1;
  84764. if (header[off_magic] !== DDS_MAGIC) {
  84765. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84766. return;
  84767. }
  84768. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84769. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84770. return;
  84771. }
  84772. if (info.isCompressed && !ext) {
  84773. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84774. return;
  84775. }
  84776. var bpp = header[off_RGBbpp];
  84777. dataOffset = header[off_size] + 4;
  84778. var computeFormats = false;
  84779. if (info.isFourCC) {
  84780. fourCC = header[off_pfFourCC];
  84781. switch (fourCC) {
  84782. case FOURCC_DXT1:
  84783. blockBytes = 8;
  84784. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84785. break;
  84786. case FOURCC_DXT3:
  84787. blockBytes = 16;
  84788. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84789. break;
  84790. case FOURCC_DXT5:
  84791. blockBytes = 16;
  84792. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84793. break;
  84794. case FOURCC_D3DFMT_R16G16B16A16F:
  84795. computeFormats = true;
  84796. break;
  84797. case FOURCC_D3DFMT_R32G32B32A32F:
  84798. computeFormats = true;
  84799. break;
  84800. case FOURCC_DX10:
  84801. // There is an additionnal header so dataOffset need to be changed
  84802. dataOffset += 5 * 4; // 5 uints
  84803. var supported = false;
  84804. switch (info.dxgiFormat) {
  84805. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84806. computeFormats = true;
  84807. supported = true;
  84808. break;
  84809. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84810. info.isRGB = true;
  84811. info.isFourCC = false;
  84812. bpp = 32;
  84813. supported = true;
  84814. break;
  84815. }
  84816. if (supported) {
  84817. break;
  84818. }
  84819. default:
  84820. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84821. return;
  84822. }
  84823. }
  84824. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84825. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84826. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84827. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84828. if (computeFormats) {
  84829. format = engine._getWebGLTextureType(info.textureType);
  84830. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84831. }
  84832. mipmapCount = 1;
  84833. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84834. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84835. }
  84836. for (var face = 0; face < faces; face++) {
  84837. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84838. width = header[off_width];
  84839. height = header[off_height];
  84840. for (mip = 0; mip < mipmapCount; ++mip) {
  84841. if (lodIndex === -1 || lodIndex === mip) {
  84842. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84843. var i = (lodIndex === -1) ? mip : 0;
  84844. if (!info.isCompressed && info.isFourCC) {
  84845. dataLength = width * height * 4;
  84846. var floatArray = null;
  84847. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84848. if (bpp === 128) {
  84849. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84850. if (sphericalPolynomialFaces && i == 0) {
  84851. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84852. }
  84853. }
  84854. else if (bpp === 64) {
  84855. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84856. if (sphericalPolynomialFaces && i == 0) {
  84857. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84858. }
  84859. }
  84860. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84861. format = engine._getWebGLTextureType(info.textureType);
  84862. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84863. }
  84864. else {
  84865. if (bpp === 128) {
  84866. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84867. if (sphericalPolynomialFaces && i == 0) {
  84868. sphericalPolynomialFaces.push(floatArray);
  84869. }
  84870. }
  84871. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84872. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84873. if (sphericalPolynomialFaces && i == 0) {
  84874. sphericalPolynomialFaces.push(floatArray);
  84875. }
  84876. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84877. format = engine._getWebGLTextureType(info.textureType);
  84878. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84879. }
  84880. else { // 64
  84881. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84882. if (sphericalPolynomialFaces && i == 0) {
  84883. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84884. }
  84885. }
  84886. }
  84887. if (floatArray) {
  84888. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84889. }
  84890. }
  84891. else if (info.isRGB) {
  84892. if (bpp === 24) {
  84893. dataLength = width * height * 3;
  84894. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84895. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84896. }
  84897. else { // 32
  84898. dataLength = width * height * 4;
  84899. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84900. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84901. }
  84902. }
  84903. else if (info.isLuminance) {
  84904. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84905. var unpaddedRowSize = width;
  84906. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84907. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84908. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84909. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84910. }
  84911. else {
  84912. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84913. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84914. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84915. }
  84916. }
  84917. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84918. width *= 0.5;
  84919. height *= 0.5;
  84920. width = Math.max(1.0, width);
  84921. height = Math.max(1.0, height);
  84922. }
  84923. if (currentFace !== undefined) {
  84924. // Loading a single face
  84925. break;
  84926. }
  84927. }
  84928. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84929. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84930. size: header[off_width],
  84931. right: sphericalPolynomialFaces[0],
  84932. left: sphericalPolynomialFaces[1],
  84933. up: sphericalPolynomialFaces[2],
  84934. down: sphericalPolynomialFaces[3],
  84935. front: sphericalPolynomialFaces[4],
  84936. back: sphericalPolynomialFaces[5],
  84937. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84938. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84939. gammaSpace: false,
  84940. });
  84941. }
  84942. else {
  84943. info.sphericalPolynomial = undefined;
  84944. }
  84945. };
  84946. DDSTools.StoreLODInAlphaChannel = false;
  84947. return DDSTools;
  84948. }());
  84949. BABYLON.DDSTools = DDSTools;
  84950. })(BABYLON || (BABYLON = {}));
  84951. //# sourceMappingURL=babylon.dds.js.map
  84952. var BABYLON;
  84953. (function (BABYLON) {
  84954. /**
  84955. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84956. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84957. */
  84958. var KhronosTextureContainer = /** @class */ (function () {
  84959. /**
  84960. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84961. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84962. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84963. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84964. */
  84965. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84966. this.arrayBuffer = arrayBuffer;
  84967. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84968. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84969. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84970. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84971. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84972. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84973. BABYLON.Tools.Error("texture missing KTX identifier");
  84974. return;
  84975. }
  84976. // load the reset of the header in native 32 bit int
  84977. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84978. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84979. var oppositeEndianess = header[0] === 0x01020304;
  84980. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84981. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84982. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84983. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84984. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84985. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84986. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84987. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84988. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84989. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84990. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84991. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84992. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84993. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84994. if (this.glType !== 0) {
  84995. BABYLON.Tools.Error("only compressed formats currently supported");
  84996. return;
  84997. }
  84998. else {
  84999. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85000. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85001. }
  85002. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85003. BABYLON.Tools.Error("only 2D textures currently supported");
  85004. return;
  85005. }
  85006. if (this.numberOfArrayElements !== 0) {
  85007. BABYLON.Tools.Error("texture arrays not currently supported");
  85008. return;
  85009. }
  85010. if (this.numberOfFaces !== facesExpected) {
  85011. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85012. return;
  85013. }
  85014. // we now have a completely validated file, so could use existence of loadType as success
  85015. // would need to make this more elaborate & adjust checks above to support more than one load type
  85016. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85017. }
  85018. // not as fast hardware based, but will probably never need to use
  85019. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85020. return ((val & 0xFF) << 24)
  85021. | ((val & 0xFF00) << 8)
  85022. | ((val >> 8) & 0xFF00)
  85023. | ((val >> 24) & 0xFF);
  85024. };
  85025. /**
  85026. * It is assumed that the texture has already been created & is currently bound
  85027. */
  85028. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85029. switch (this.loadType) {
  85030. case KhronosTextureContainer.COMPRESSED_2D:
  85031. this._upload2DCompressedLevels(gl, loadMipmaps);
  85032. break;
  85033. case KhronosTextureContainer.TEX_2D:
  85034. case KhronosTextureContainer.COMPRESSED_3D:
  85035. case KhronosTextureContainer.TEX_3D:
  85036. }
  85037. };
  85038. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85039. // initialize width & height for level 1
  85040. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85041. var width = this.pixelWidth;
  85042. var height = this.pixelHeight;
  85043. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85044. for (var level = 0; level < mipmapCount; level++) {
  85045. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85046. for (var face = 0; face < this.numberOfFaces; face++) {
  85047. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85048. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85049. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85050. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85051. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85052. }
  85053. width = Math.max(1.0, width * 0.5);
  85054. height = Math.max(1.0, height * 0.5);
  85055. }
  85056. };
  85057. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85058. // load types
  85059. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85060. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85061. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85062. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85063. return KhronosTextureContainer;
  85064. }());
  85065. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85066. })(BABYLON || (BABYLON = {}));
  85067. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85068. var BABYLON;
  85069. (function (BABYLON) {
  85070. var Debug;
  85071. (function (Debug) {
  85072. /**
  85073. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  85074. */
  85075. var SkeletonViewer = /** @class */ (function () {
  85076. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  85077. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85078. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85079. this.skeleton = skeleton;
  85080. this.mesh = mesh;
  85081. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85082. this.renderingGroupId = renderingGroupId;
  85083. this.color = BABYLON.Color3.White();
  85084. this._debugLines = new Array();
  85085. this._isEnabled = false;
  85086. this._scene = scene;
  85087. this.update();
  85088. this._renderFunction = this.update.bind(this);
  85089. }
  85090. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85091. get: function () {
  85092. return this._isEnabled;
  85093. },
  85094. set: function (value) {
  85095. if (this._isEnabled === value) {
  85096. return;
  85097. }
  85098. this._isEnabled = value;
  85099. if (value) {
  85100. this._scene.registerBeforeRender(this._renderFunction);
  85101. }
  85102. else {
  85103. this._scene.unregisterBeforeRender(this._renderFunction);
  85104. }
  85105. },
  85106. enumerable: true,
  85107. configurable: true
  85108. });
  85109. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85110. if (x === void 0) { x = 0; }
  85111. if (y === void 0) { y = 0; }
  85112. if (z === void 0) { z = 0; }
  85113. var tmat = BABYLON.Tmp.Matrix[0];
  85114. var parentBone = bone.getParent();
  85115. tmat.copyFrom(bone.getLocalMatrix());
  85116. if (x !== 0 || y !== 0 || z !== 0) {
  85117. var tmat2 = BABYLON.Tmp.Matrix[1];
  85118. BABYLON.Matrix.IdentityToRef(tmat2);
  85119. tmat2.m[12] = x;
  85120. tmat2.m[13] = y;
  85121. tmat2.m[14] = z;
  85122. tmat2.multiplyToRef(tmat, tmat);
  85123. }
  85124. if (parentBone) {
  85125. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85126. }
  85127. tmat.multiplyToRef(meshMat, tmat);
  85128. position.x = tmat.m[12];
  85129. position.y = tmat.m[13];
  85130. position.z = tmat.m[14];
  85131. };
  85132. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85133. var len = bones.length;
  85134. var meshPos = this.mesh.position;
  85135. for (var i = 0; i < len; i++) {
  85136. var bone = bones[i];
  85137. var points = this._debugLines[i];
  85138. if (!points) {
  85139. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85140. this._debugLines[i] = points;
  85141. }
  85142. this._getBonePosition(points[0], bone, meshMat);
  85143. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85144. points[0].subtractInPlace(meshPos);
  85145. points[1].subtractInPlace(meshPos);
  85146. }
  85147. };
  85148. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85149. var len = bones.length;
  85150. var boneNum = 0;
  85151. var meshPos = this.mesh.position;
  85152. for (var i = len - 1; i >= 0; i--) {
  85153. var childBone = bones[i];
  85154. var parentBone = childBone.getParent();
  85155. if (!parentBone) {
  85156. continue;
  85157. }
  85158. var points = this._debugLines[boneNum];
  85159. if (!points) {
  85160. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85161. this._debugLines[boneNum] = points;
  85162. }
  85163. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85164. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85165. points[0].subtractInPlace(meshPos);
  85166. points[1].subtractInPlace(meshPos);
  85167. boneNum++;
  85168. }
  85169. };
  85170. SkeletonViewer.prototype.update = function () {
  85171. if (this.autoUpdateBonesMatrices) {
  85172. this.skeleton.computeAbsoluteTransforms();
  85173. }
  85174. if (this.skeleton.bones[0].length === undefined) {
  85175. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85176. }
  85177. else {
  85178. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85179. }
  85180. if (!this._debugMesh) {
  85181. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85182. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85183. }
  85184. else {
  85185. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85186. }
  85187. this._debugMesh.position.copyFrom(this.mesh.position);
  85188. this._debugMesh.color = this.color;
  85189. };
  85190. SkeletonViewer.prototype.dispose = function () {
  85191. if (this._debugMesh) {
  85192. this.isEnabled = false;
  85193. this._debugMesh.dispose();
  85194. this._debugMesh = null;
  85195. }
  85196. };
  85197. return SkeletonViewer;
  85198. }());
  85199. Debug.SkeletonViewer = SkeletonViewer;
  85200. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85201. })(BABYLON || (BABYLON = {}));
  85202. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85203. /**
  85204. * Module Debug contains the (visual) components to debug a scene correctly
  85205. */
  85206. var BABYLON;
  85207. (function (BABYLON) {
  85208. var Debug;
  85209. (function (Debug) {
  85210. /**
  85211. * The Axes viewer will show 3 axes in a specific point in space
  85212. */
  85213. var AxesViewer = /** @class */ (function () {
  85214. function AxesViewer(scene, scaleLines) {
  85215. if (scaleLines === void 0) { scaleLines = 1; }
  85216. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85217. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85218. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85219. this.scaleLines = 1;
  85220. this.scaleLines = scaleLines;
  85221. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85222. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85223. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85224. this._xmesh.renderingGroupId = 2;
  85225. this._ymesh.renderingGroupId = 2;
  85226. this._zmesh.renderingGroupId = 2;
  85227. this._xmesh.material.checkReadyOnlyOnce = true;
  85228. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85229. this._ymesh.material.checkReadyOnlyOnce = true;
  85230. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85231. this._zmesh.material.checkReadyOnlyOnce = true;
  85232. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85233. this.scene = scene;
  85234. }
  85235. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85236. var scaleLines = this.scaleLines;
  85237. if (this._xmesh) {
  85238. this._xmesh.position.copyFrom(position);
  85239. }
  85240. if (this._ymesh) {
  85241. this._ymesh.position.copyFrom(position);
  85242. }
  85243. if (this._zmesh) {
  85244. this._zmesh.position.copyFrom(position);
  85245. }
  85246. var point2 = this._xline[1];
  85247. point2.x = xaxis.x * scaleLines;
  85248. point2.y = xaxis.y * scaleLines;
  85249. point2.z = xaxis.z * scaleLines;
  85250. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85251. point2 = this._yline[1];
  85252. point2.x = yaxis.x * scaleLines;
  85253. point2.y = yaxis.y * scaleLines;
  85254. point2.z = yaxis.z * scaleLines;
  85255. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85256. point2 = this._zline[1];
  85257. point2.x = zaxis.x * scaleLines;
  85258. point2.y = zaxis.y * scaleLines;
  85259. point2.z = zaxis.z * scaleLines;
  85260. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85261. };
  85262. AxesViewer.prototype.dispose = function () {
  85263. if (this._xmesh) {
  85264. this._xmesh.dispose();
  85265. }
  85266. if (this._ymesh) {
  85267. this._ymesh.dispose();
  85268. }
  85269. if (this._zmesh) {
  85270. this._zmesh.dispose();
  85271. }
  85272. this._xmesh = null;
  85273. this._ymesh = null;
  85274. this._zmesh = null;
  85275. this.scene = null;
  85276. };
  85277. return AxesViewer;
  85278. }());
  85279. Debug.AxesViewer = AxesViewer;
  85280. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85281. })(BABYLON || (BABYLON = {}));
  85282. //# sourceMappingURL=babylon.axesViewer.js.map
  85283. var BABYLON;
  85284. (function (BABYLON) {
  85285. var Debug;
  85286. (function (Debug) {
  85287. /**
  85288. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85289. */
  85290. var BoneAxesViewer = /** @class */ (function (_super) {
  85291. __extends(BoneAxesViewer, _super);
  85292. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85293. if (scaleLines === void 0) { scaleLines = 1; }
  85294. var _this = _super.call(this, scene, scaleLines) || this;
  85295. _this.pos = BABYLON.Vector3.Zero();
  85296. _this.xaxis = BABYLON.Vector3.Zero();
  85297. _this.yaxis = BABYLON.Vector3.Zero();
  85298. _this.zaxis = BABYLON.Vector3.Zero();
  85299. _this.mesh = mesh;
  85300. _this.bone = bone;
  85301. return _this;
  85302. }
  85303. BoneAxesViewer.prototype.update = function () {
  85304. if (!this.mesh || !this.bone) {
  85305. return;
  85306. }
  85307. var bone = this.bone;
  85308. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85309. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85310. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85311. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85312. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85313. };
  85314. BoneAxesViewer.prototype.dispose = function () {
  85315. if (this.mesh) {
  85316. this.mesh = null;
  85317. this.bone = null;
  85318. _super.prototype.dispose.call(this);
  85319. }
  85320. };
  85321. return BoneAxesViewer;
  85322. }(Debug.AxesViewer));
  85323. Debug.BoneAxesViewer = BoneAxesViewer;
  85324. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85325. })(BABYLON || (BABYLON = {}));
  85326. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85327. var BABYLON;
  85328. (function (BABYLON) {
  85329. var RayHelper = /** @class */ (function () {
  85330. function RayHelper(ray) {
  85331. this.ray = ray;
  85332. }
  85333. RayHelper.CreateAndShow = function (ray, scene, color) {
  85334. var helper = new RayHelper(ray);
  85335. helper.show(scene, color);
  85336. return helper;
  85337. };
  85338. RayHelper.prototype.show = function (scene, color) {
  85339. if (!this._renderFunction && this.ray) {
  85340. var ray = this.ray;
  85341. this._renderFunction = this._render.bind(this);
  85342. this._scene = scene;
  85343. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85344. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85345. if (this._renderFunction) {
  85346. this._scene.registerBeforeRender(this._renderFunction);
  85347. }
  85348. }
  85349. if (color && this._renderLine) {
  85350. this._renderLine.color.copyFrom(color);
  85351. }
  85352. };
  85353. RayHelper.prototype.hide = function () {
  85354. if (this._renderFunction && this._scene) {
  85355. this._scene.unregisterBeforeRender(this._renderFunction);
  85356. this._scene = null;
  85357. this._renderFunction = null;
  85358. if (this._renderLine) {
  85359. this._renderLine.dispose();
  85360. this._renderLine = null;
  85361. }
  85362. this._renderPoints = [];
  85363. }
  85364. };
  85365. RayHelper.prototype._render = function () {
  85366. var ray = this.ray;
  85367. if (!ray) {
  85368. return;
  85369. }
  85370. var point = this._renderPoints[1];
  85371. var len = Math.min(ray.length, 1000000);
  85372. point.copyFrom(ray.direction);
  85373. point.scaleInPlace(len);
  85374. point.addInPlace(ray.origin);
  85375. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85376. };
  85377. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85378. this._attachedToMesh = mesh;
  85379. var ray = this.ray;
  85380. if (!ray) {
  85381. return;
  85382. }
  85383. if (!ray.direction) {
  85384. ray.direction = BABYLON.Vector3.Zero();
  85385. }
  85386. if (!ray.origin) {
  85387. ray.origin = BABYLON.Vector3.Zero();
  85388. }
  85389. if (length) {
  85390. ray.length = length;
  85391. }
  85392. if (!meshSpaceOrigin) {
  85393. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85394. }
  85395. if (!meshSpaceDirection) {
  85396. // -1 so that this will work with Mesh.lookAt
  85397. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85398. }
  85399. if (!this._meshSpaceDirection) {
  85400. this._meshSpaceDirection = meshSpaceDirection.clone();
  85401. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85402. }
  85403. else {
  85404. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85405. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85406. }
  85407. if (!this._updateToMeshFunction) {
  85408. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85409. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85410. }
  85411. this._updateToMesh();
  85412. };
  85413. RayHelper.prototype.detachFromMesh = function () {
  85414. if (this._attachedToMesh) {
  85415. if (this._updateToMeshFunction) {
  85416. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85417. }
  85418. this._attachedToMesh = null;
  85419. this._updateToMeshFunction = null;
  85420. }
  85421. };
  85422. RayHelper.prototype._updateToMesh = function () {
  85423. var ray = this.ray;
  85424. if (!this._attachedToMesh || !ray) {
  85425. return;
  85426. }
  85427. if (this._attachedToMesh._isDisposed) {
  85428. this.detachFromMesh();
  85429. return;
  85430. }
  85431. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85432. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85433. };
  85434. RayHelper.prototype.dispose = function () {
  85435. this.hide();
  85436. this.detachFromMesh();
  85437. this.ray = null;
  85438. };
  85439. return RayHelper;
  85440. }());
  85441. BABYLON.RayHelper = RayHelper;
  85442. })(BABYLON || (BABYLON = {}));
  85443. //# sourceMappingURL=babylon.rayHelper.js.map
  85444. var BABYLON;
  85445. (function (BABYLON) {
  85446. // load the inspector using require, if not present in the global namespace.
  85447. var DebugLayer = /** @class */ (function () {
  85448. function DebugLayer(scene) {
  85449. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85450. this._scene = scene;
  85451. // load inspector using require, if it doesn't exist on the global namespace.
  85452. }
  85453. /** Creates the inspector window. */
  85454. DebugLayer.prototype._createInspector = function (config) {
  85455. if (config === void 0) { config = {}; }
  85456. var popup = config.popup || false;
  85457. var initialTab = config.initialTab || 0;
  85458. var parentElement = config.parentElement || null;
  85459. if (!this._inspector) {
  85460. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85461. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85462. } // else nothing to do,; instance is already existing
  85463. };
  85464. DebugLayer.prototype.isVisible = function () {
  85465. if (!this._inspector) {
  85466. return false;
  85467. }
  85468. return true;
  85469. };
  85470. DebugLayer.prototype.hide = function () {
  85471. if (this._inspector) {
  85472. try {
  85473. this._inspector.dispose();
  85474. }
  85475. catch (e) {
  85476. // If the inspector has been removed directly from the inspector tool
  85477. }
  85478. this._inspector = null;
  85479. }
  85480. };
  85481. DebugLayer.prototype.show = function (config) {
  85482. if (config === void 0) { config = {}; }
  85483. if (typeof this.BJSINSPECTOR == 'undefined') {
  85484. // Load inspector and add it to the DOM
  85485. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85486. }
  85487. else {
  85488. // Otherwise creates the inspector
  85489. this._createInspector(config);
  85490. }
  85491. };
  85492. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85493. return DebugLayer;
  85494. }());
  85495. BABYLON.DebugLayer = DebugLayer;
  85496. })(BABYLON || (BABYLON = {}));
  85497. //# sourceMappingURL=babylon.debugLayer.js.map
  85498. var BABYLON;
  85499. (function (BABYLON) {
  85500. var Debug;
  85501. (function (Debug) {
  85502. /**
  85503. * Used to show the physics impostor around the specific mesh.
  85504. */
  85505. var PhysicsViewer = /** @class */ (function () {
  85506. function PhysicsViewer(scene) {
  85507. this._impostors = [];
  85508. this._meshes = [];
  85509. this._numMeshes = 0;
  85510. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85511. var physicEngine = this._scene.getPhysicsEngine();
  85512. if (physicEngine) {
  85513. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85514. }
  85515. }
  85516. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85517. var plugin = this._physicsEnginePlugin;
  85518. for (var i = 0; i < this._numMeshes; i++) {
  85519. var impostor = this._impostors[i];
  85520. if (!impostor) {
  85521. continue;
  85522. }
  85523. if (impostor.isDisposed) {
  85524. this.hideImpostor(this._impostors[i--]);
  85525. }
  85526. else {
  85527. var mesh = this._meshes[i];
  85528. if (mesh && plugin) {
  85529. plugin.syncMeshWithImpostor(mesh, impostor);
  85530. }
  85531. }
  85532. }
  85533. };
  85534. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85535. if (!this._scene) {
  85536. return;
  85537. }
  85538. for (var i = 0; i < this._numMeshes; i++) {
  85539. if (this._impostors[i] == impostor) {
  85540. return;
  85541. }
  85542. }
  85543. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85544. if (debugMesh) {
  85545. this._impostors[this._numMeshes] = impostor;
  85546. this._meshes[this._numMeshes] = debugMesh;
  85547. if (this._numMeshes === 0) {
  85548. this._renderFunction = this._updateDebugMeshes.bind(this);
  85549. this._scene.registerBeforeRender(this._renderFunction);
  85550. }
  85551. this._numMeshes++;
  85552. }
  85553. };
  85554. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85555. if (!impostor || !this._scene) {
  85556. return;
  85557. }
  85558. var removed = false;
  85559. for (var i = 0; i < this._numMeshes; i++) {
  85560. if (this._impostors[i] == impostor) {
  85561. var mesh = this._meshes[i];
  85562. if (!mesh) {
  85563. continue;
  85564. }
  85565. this._scene.removeMesh(mesh);
  85566. mesh.dispose();
  85567. this._numMeshes--;
  85568. if (this._numMeshes > 0) {
  85569. this._meshes[i] = this._meshes[this._numMeshes];
  85570. this._impostors[i] = this._impostors[this._numMeshes];
  85571. this._meshes[this._numMeshes] = null;
  85572. this._impostors[this._numMeshes] = null;
  85573. }
  85574. else {
  85575. this._meshes[0] = null;
  85576. this._impostors[0] = null;
  85577. }
  85578. removed = true;
  85579. break;
  85580. }
  85581. }
  85582. if (removed && this._numMeshes === 0) {
  85583. this._scene.unregisterBeforeRender(this._renderFunction);
  85584. }
  85585. };
  85586. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85587. if (!this._debugMaterial) {
  85588. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85589. this._debugMaterial.wireframe = true;
  85590. }
  85591. return this._debugMaterial;
  85592. };
  85593. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85594. if (!this._debugBoxMesh) {
  85595. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85596. this._debugBoxMesh.renderingGroupId = 1;
  85597. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85598. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85599. scene.removeMesh(this._debugBoxMesh);
  85600. }
  85601. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85602. };
  85603. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85604. if (!this._debugSphereMesh) {
  85605. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85606. this._debugSphereMesh.renderingGroupId = 1;
  85607. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85608. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85609. scene.removeMesh(this._debugSphereMesh);
  85610. }
  85611. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85612. };
  85613. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85614. var mesh = null;
  85615. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85616. mesh = this._getDebugBoxMesh(scene);
  85617. impostor.getBoxSizeToRef(mesh.scaling);
  85618. }
  85619. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85620. mesh = this._getDebugSphereMesh(scene);
  85621. var radius = impostor.getRadius();
  85622. mesh.scaling.x = radius * 2;
  85623. mesh.scaling.y = radius * 2;
  85624. mesh.scaling.z = radius * 2;
  85625. }
  85626. return mesh;
  85627. };
  85628. PhysicsViewer.prototype.dispose = function () {
  85629. for (var i = 0; i < this._numMeshes; i++) {
  85630. this.hideImpostor(this._impostors[i]);
  85631. }
  85632. if (this._debugBoxMesh) {
  85633. this._debugBoxMesh.dispose();
  85634. }
  85635. if (this._debugSphereMesh) {
  85636. this._debugSphereMesh.dispose();
  85637. }
  85638. if (this._debugMaterial) {
  85639. this._debugMaterial.dispose();
  85640. }
  85641. this._impostors.length = 0;
  85642. this._scene = null;
  85643. this._physicsEnginePlugin = null;
  85644. };
  85645. return PhysicsViewer;
  85646. }());
  85647. Debug.PhysicsViewer = PhysicsViewer;
  85648. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85649. })(BABYLON || (BABYLON = {}));
  85650. //# sourceMappingURL=babylon.physicsViewer.js.map
  85651. var BABYLON;
  85652. (function (BABYLON) {
  85653. var BoundingBoxRenderer = /** @class */ (function () {
  85654. function BoundingBoxRenderer(scene) {
  85655. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85656. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85657. this.showBackLines = true;
  85658. this.renderList = new BABYLON.SmartArray(32);
  85659. this._vertexBuffers = {};
  85660. this._scene = scene;
  85661. }
  85662. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85663. if (this._colorShader) {
  85664. return;
  85665. }
  85666. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85667. attributes: [BABYLON.VertexBuffer.PositionKind],
  85668. uniforms: ["world", "viewProjection", "color"]
  85669. });
  85670. var engine = this._scene.getEngine();
  85671. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85672. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85673. this._createIndexBuffer();
  85674. };
  85675. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85676. var engine = this._scene.getEngine();
  85677. this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  85678. };
  85679. BoundingBoxRenderer.prototype._rebuild = function () {
  85680. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85681. if (vb) {
  85682. vb._rebuild();
  85683. }
  85684. this._createIndexBuffer();
  85685. };
  85686. BoundingBoxRenderer.prototype.reset = function () {
  85687. this.renderList.reset();
  85688. };
  85689. BoundingBoxRenderer.prototype.render = function () {
  85690. if (this.renderList.length === 0) {
  85691. return;
  85692. }
  85693. this._prepareRessources();
  85694. if (!this._colorShader.isReady()) {
  85695. return;
  85696. }
  85697. var engine = this._scene.getEngine();
  85698. engine.setDepthWrite(false);
  85699. this._colorShader._preBind();
  85700. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85701. var boundingBox = this.renderList.data[boundingBoxIndex];
  85702. var min = boundingBox.minimum;
  85703. var max = boundingBox.maximum;
  85704. var diff = max.subtract(min);
  85705. var median = min.add(diff.scale(0.5));
  85706. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85707. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85708. .multiply(boundingBox.getWorldMatrix());
  85709. // VBOs
  85710. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85711. if (this.showBackLines) {
  85712. // Back
  85713. engine.setDepthFunctionToGreaterOrEqual();
  85714. this._scene.resetCachedMaterial();
  85715. this._colorShader.setColor4("color", this.backColor.toColor4());
  85716. this._colorShader.bind(worldMatrix);
  85717. // Draw order
  85718. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85719. }
  85720. // Front
  85721. engine.setDepthFunctionToLess();
  85722. this._scene.resetCachedMaterial();
  85723. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85724. this._colorShader.bind(worldMatrix);
  85725. // Draw order
  85726. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85727. }
  85728. this._colorShader.unbind();
  85729. engine.setDepthFunctionToLessOrEqual();
  85730. engine.setDepthWrite(true);
  85731. };
  85732. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85733. this._prepareRessources();
  85734. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85735. return;
  85736. }
  85737. var engine = this._scene.getEngine();
  85738. engine.setDepthWrite(false);
  85739. engine.setColorWrite(false);
  85740. this._colorShader._preBind();
  85741. var boundingBox = mesh._boundingInfo.boundingBox;
  85742. var min = boundingBox.minimum;
  85743. var max = boundingBox.maximum;
  85744. var diff = max.subtract(min);
  85745. var median = min.add(diff.scale(0.5));
  85746. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85747. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85748. .multiply(boundingBox.getWorldMatrix());
  85749. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85750. engine.setDepthFunctionToLess();
  85751. this._scene.resetCachedMaterial();
  85752. this._colorShader.bind(worldMatrix);
  85753. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85754. this._colorShader.unbind();
  85755. engine.setDepthFunctionToLessOrEqual();
  85756. engine.setDepthWrite(true);
  85757. engine.setColorWrite(true);
  85758. };
  85759. BoundingBoxRenderer.prototype.dispose = function () {
  85760. if (!this._colorShader) {
  85761. return;
  85762. }
  85763. this.renderList.dispose();
  85764. this._colorShader.dispose();
  85765. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85766. if (buffer) {
  85767. buffer.dispose();
  85768. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85769. }
  85770. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85771. };
  85772. return BoundingBoxRenderer;
  85773. }());
  85774. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85775. })(BABYLON || (BABYLON = {}));
  85776. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85777. var BABYLON;
  85778. (function (BABYLON) {
  85779. /**
  85780. * Defines a target to use with MorphTargetManager
  85781. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85782. */
  85783. var MorphTarget = /** @class */ (function () {
  85784. /**
  85785. * Creates a new MorphTarget
  85786. * @param name defines the name of the target
  85787. * @param influence defines the influence to use
  85788. */
  85789. function MorphTarget(
  85790. /** defines the name of the target */
  85791. name, influence, scene) {
  85792. if (influence === void 0) { influence = 0; }
  85793. if (scene === void 0) { scene = null; }
  85794. this.name = name;
  85795. /**
  85796. * Gets or sets the list of animations
  85797. */
  85798. this.animations = new Array();
  85799. this._positions = null;
  85800. this._normals = null;
  85801. this._tangents = null;
  85802. /**
  85803. * Observable raised when the influence changes
  85804. */
  85805. this.onInfluenceChanged = new BABYLON.Observable();
  85806. this._animationPropertiesOverride = null;
  85807. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85808. this.influence = influence;
  85809. }
  85810. Object.defineProperty(MorphTarget.prototype, "influence", {
  85811. /**
  85812. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85813. */
  85814. get: function () {
  85815. return this._influence;
  85816. },
  85817. set: function (influence) {
  85818. if (this._influence === influence) {
  85819. return;
  85820. }
  85821. var previous = this._influence;
  85822. this._influence = influence;
  85823. if (this.onInfluenceChanged.hasObservers) {
  85824. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85825. }
  85826. },
  85827. enumerable: true,
  85828. configurable: true
  85829. });
  85830. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85831. /**
  85832. * Gets or sets the animation properties override
  85833. */
  85834. get: function () {
  85835. if (!this._animationPropertiesOverride && this._scene) {
  85836. return this._scene.animationPropertiesOverride;
  85837. }
  85838. return this._animationPropertiesOverride;
  85839. },
  85840. set: function (value) {
  85841. this._animationPropertiesOverride = value;
  85842. },
  85843. enumerable: true,
  85844. configurable: true
  85845. });
  85846. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85847. /**
  85848. * Gets a boolean defining if the target contains position data
  85849. */
  85850. get: function () {
  85851. return !!this._positions;
  85852. },
  85853. enumerable: true,
  85854. configurable: true
  85855. });
  85856. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85857. /**
  85858. * Gets a boolean defining if the target contains normal data
  85859. */
  85860. get: function () {
  85861. return !!this._normals;
  85862. },
  85863. enumerable: true,
  85864. configurable: true
  85865. });
  85866. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85867. /**
  85868. * Gets a boolean defining if the target contains tangent data
  85869. */
  85870. get: function () {
  85871. return !!this._tangents;
  85872. },
  85873. enumerable: true,
  85874. configurable: true
  85875. });
  85876. /**
  85877. * Affects position data to this target
  85878. * @param data defines the position data to use
  85879. */
  85880. MorphTarget.prototype.setPositions = function (data) {
  85881. this._positions = data;
  85882. };
  85883. /**
  85884. * Gets the position data stored in this target
  85885. * @returns a FloatArray containing the position data (or null if not present)
  85886. */
  85887. MorphTarget.prototype.getPositions = function () {
  85888. return this._positions;
  85889. };
  85890. /**
  85891. * Affects normal data to this target
  85892. * @param data defines the normal data to use
  85893. */
  85894. MorphTarget.prototype.setNormals = function (data) {
  85895. this._normals = data;
  85896. };
  85897. /**
  85898. * Gets the normal data stored in this target
  85899. * @returns a FloatArray containing the normal data (or null if not present)
  85900. */
  85901. MorphTarget.prototype.getNormals = function () {
  85902. return this._normals;
  85903. };
  85904. /**
  85905. * Affects tangent data to this target
  85906. * @param data defines the tangent data to use
  85907. */
  85908. MorphTarget.prototype.setTangents = function (data) {
  85909. this._tangents = data;
  85910. };
  85911. /**
  85912. * Gets the tangent data stored in this target
  85913. * @returns a FloatArray containing the tangent data (or null if not present)
  85914. */
  85915. MorphTarget.prototype.getTangents = function () {
  85916. return this._tangents;
  85917. };
  85918. /**
  85919. * Serializes the current target into a Serialization object
  85920. * @returns the serialized object
  85921. */
  85922. MorphTarget.prototype.serialize = function () {
  85923. var serializationObject = {};
  85924. serializationObject.name = this.name;
  85925. serializationObject.influence = this.influence;
  85926. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85927. if (this.hasNormals) {
  85928. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85929. }
  85930. if (this.hasTangents) {
  85931. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85932. }
  85933. // Animations
  85934. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85935. return serializationObject;
  85936. };
  85937. // Statics
  85938. /**
  85939. * Creates a new target from serialized data
  85940. * @param serializationObject defines the serialized data to use
  85941. * @returns a new MorphTarget
  85942. */
  85943. MorphTarget.Parse = function (serializationObject) {
  85944. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85945. result.setPositions(serializationObject.positions);
  85946. if (serializationObject.normals) {
  85947. result.setNormals(serializationObject.normals);
  85948. }
  85949. if (serializationObject.tangents) {
  85950. result.setTangents(serializationObject.tangents);
  85951. }
  85952. // Animations
  85953. if (serializationObject.animations) {
  85954. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85955. var parsedAnimation = serializationObject.animations[animationIndex];
  85956. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85957. }
  85958. }
  85959. return result;
  85960. };
  85961. /**
  85962. * Creates a MorphTarget from mesh data
  85963. * @param mesh defines the source mesh
  85964. * @param name defines the name to use for the new target
  85965. * @param influence defines the influence to attach to the target
  85966. * @returns a new MorphTarget
  85967. */
  85968. MorphTarget.FromMesh = function (mesh, name, influence) {
  85969. if (!name) {
  85970. name = mesh.name;
  85971. }
  85972. var result = new MorphTarget(name, influence, mesh.getScene());
  85973. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85975. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85976. }
  85977. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85978. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85979. }
  85980. return result;
  85981. };
  85982. return MorphTarget;
  85983. }());
  85984. BABYLON.MorphTarget = MorphTarget;
  85985. })(BABYLON || (BABYLON = {}));
  85986. //# sourceMappingURL=babylon.morphTarget.js.map
  85987. var BABYLON;
  85988. (function (BABYLON) {
  85989. /**
  85990. * This class is used to deform meshes using morphing between different targets
  85991. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85992. */
  85993. var MorphTargetManager = /** @class */ (function () {
  85994. /**
  85995. * Creates a new MorphTargetManager
  85996. * @param scene defines the current scene
  85997. */
  85998. function MorphTargetManager(scene) {
  85999. if (scene === void 0) { scene = null; }
  86000. this._targets = new Array();
  86001. this._targetObservable = new Array();
  86002. this._activeTargets = new BABYLON.SmartArray(16);
  86003. this._supportsNormals = false;
  86004. this._supportsTangents = false;
  86005. this._vertexCount = 0;
  86006. this._uniqueId = 0;
  86007. this._tempInfluences = new Array();
  86008. if (!scene) {
  86009. scene = BABYLON.Engine.LastCreatedScene;
  86010. }
  86011. this._scene = scene;
  86012. if (this._scene) {
  86013. this._scene.morphTargetManagers.push(this);
  86014. this._uniqueId = this._scene.getUniqueId();
  86015. }
  86016. }
  86017. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86018. /**
  86019. * Gets the unique ID of this manager
  86020. */
  86021. get: function () {
  86022. return this._uniqueId;
  86023. },
  86024. enumerable: true,
  86025. configurable: true
  86026. });
  86027. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86028. /**
  86029. * Gets the number of vertices handled by this manager
  86030. */
  86031. get: function () {
  86032. return this._vertexCount;
  86033. },
  86034. enumerable: true,
  86035. configurable: true
  86036. });
  86037. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86038. /**
  86039. * Gets a boolean indicating if this manager supports morphing of normals
  86040. */
  86041. get: function () {
  86042. return this._supportsNormals;
  86043. },
  86044. enumerable: true,
  86045. configurable: true
  86046. });
  86047. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86048. /**
  86049. * Gets a boolean indicating if this manager supports morphing of tangents
  86050. */
  86051. get: function () {
  86052. return this._supportsTangents;
  86053. },
  86054. enumerable: true,
  86055. configurable: true
  86056. });
  86057. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86058. /**
  86059. * Gets the number of targets stored in this manager
  86060. */
  86061. get: function () {
  86062. return this._targets.length;
  86063. },
  86064. enumerable: true,
  86065. configurable: true
  86066. });
  86067. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86068. /**
  86069. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86070. */
  86071. get: function () {
  86072. return this._activeTargets.length;
  86073. },
  86074. enumerable: true,
  86075. configurable: true
  86076. });
  86077. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86078. /**
  86079. * Gets the list of influences (one per target)
  86080. */
  86081. get: function () {
  86082. return this._influences;
  86083. },
  86084. enumerable: true,
  86085. configurable: true
  86086. });
  86087. /**
  86088. * Gets the active target at specified index. An active target is a target with an influence > 0
  86089. * @param index defines the index to check
  86090. * @returns the requested target
  86091. */
  86092. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86093. return this._activeTargets.data[index];
  86094. };
  86095. /**
  86096. * Gets the target at specified index
  86097. * @param index defines the index to check
  86098. * @returns the requested target
  86099. */
  86100. MorphTargetManager.prototype.getTarget = function (index) {
  86101. return this._targets[index];
  86102. };
  86103. /**
  86104. * Add a new target to this manager
  86105. * @param target defines the target to add
  86106. */
  86107. MorphTargetManager.prototype.addTarget = function (target) {
  86108. var _this = this;
  86109. this._targets.push(target);
  86110. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86111. _this._syncActiveTargets(needUpdate);
  86112. }));
  86113. this._syncActiveTargets(true);
  86114. };
  86115. /**
  86116. * Removes a target from the manager
  86117. * @param target defines the target to remove
  86118. */
  86119. MorphTargetManager.prototype.removeTarget = function (target) {
  86120. var index = this._targets.indexOf(target);
  86121. if (index >= 0) {
  86122. this._targets.splice(index, 1);
  86123. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86124. this._syncActiveTargets(true);
  86125. }
  86126. };
  86127. /**
  86128. * Serializes the current manager into a Serialization object
  86129. * @returns the serialized object
  86130. */
  86131. MorphTargetManager.prototype.serialize = function () {
  86132. var serializationObject = {};
  86133. serializationObject.id = this.uniqueId;
  86134. serializationObject.targets = [];
  86135. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86136. var target = _a[_i];
  86137. serializationObject.targets.push(target.serialize());
  86138. }
  86139. return serializationObject;
  86140. };
  86141. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86142. var influenceCount = 0;
  86143. this._activeTargets.reset();
  86144. this._supportsNormals = true;
  86145. this._supportsTangents = true;
  86146. this._vertexCount = 0;
  86147. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86148. var target = _a[_i];
  86149. this._activeTargets.push(target);
  86150. this._tempInfluences[influenceCount++] = target.influence;
  86151. var positions = target.getPositions();
  86152. if (positions) {
  86153. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86154. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86155. var vertexCount = positions.length / 3;
  86156. if (this._vertexCount === 0) {
  86157. this._vertexCount = vertexCount;
  86158. }
  86159. else if (this._vertexCount !== vertexCount) {
  86160. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86161. return;
  86162. }
  86163. }
  86164. }
  86165. if (!this._influences || this._influences.length !== influenceCount) {
  86166. this._influences = new Float32Array(influenceCount);
  86167. }
  86168. for (var index = 0; index < influenceCount; index++) {
  86169. this._influences[index] = this._tempInfluences[index];
  86170. }
  86171. if (needUpdate) {
  86172. this.synchronize();
  86173. }
  86174. };
  86175. /**
  86176. * Syncrhonize the targets with all the meshes using this morph target manager
  86177. */
  86178. MorphTargetManager.prototype.synchronize = function () {
  86179. if (!this._scene) {
  86180. return;
  86181. }
  86182. // Flag meshes as dirty to resync with the active targets
  86183. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86184. var mesh = _a[_i];
  86185. if (mesh.morphTargetManager === this) {
  86186. mesh._syncGeometryWithMorphTargetManager();
  86187. }
  86188. }
  86189. };
  86190. // Statics
  86191. /**
  86192. * Creates a new MorphTargetManager from serialized data
  86193. * @param serializationObject defines the serialized data
  86194. * @param scene defines the hosting scene
  86195. * @returns the new MorphTargetManager
  86196. */
  86197. MorphTargetManager.Parse = function (serializationObject, scene) {
  86198. var result = new MorphTargetManager(scene);
  86199. result._uniqueId = serializationObject.id;
  86200. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86201. var targetData = _a[_i];
  86202. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86203. }
  86204. return result;
  86205. };
  86206. return MorphTargetManager;
  86207. }());
  86208. BABYLON.MorphTargetManager = MorphTargetManager;
  86209. })(BABYLON || (BABYLON = {}));
  86210. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86211. var BABYLON;
  86212. (function (BABYLON) {
  86213. var Octree = /** @class */ (function () {
  86214. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86215. if (maxDepth === void 0) { maxDepth = 2; }
  86216. this.maxDepth = maxDepth;
  86217. this.dynamicContent = new Array();
  86218. this._maxBlockCapacity = maxBlockCapacity || 64;
  86219. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86220. this._creationFunc = creationFunc;
  86221. }
  86222. // Methods
  86223. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86224. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86225. };
  86226. Octree.prototype.addMesh = function (entry) {
  86227. for (var index = 0; index < this.blocks.length; index++) {
  86228. var block = this.blocks[index];
  86229. block.addEntry(entry);
  86230. }
  86231. };
  86232. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86233. this._selectionContent.reset();
  86234. for (var index = 0; index < this.blocks.length; index++) {
  86235. var block = this.blocks[index];
  86236. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86237. }
  86238. if (allowDuplicate) {
  86239. this._selectionContent.concat(this.dynamicContent);
  86240. }
  86241. else {
  86242. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86243. }
  86244. return this._selectionContent;
  86245. };
  86246. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86247. this._selectionContent.reset();
  86248. for (var index = 0; index < this.blocks.length; index++) {
  86249. var block = this.blocks[index];
  86250. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86251. }
  86252. if (allowDuplicate) {
  86253. this._selectionContent.concat(this.dynamicContent);
  86254. }
  86255. else {
  86256. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86257. }
  86258. return this._selectionContent;
  86259. };
  86260. Octree.prototype.intersectsRay = function (ray) {
  86261. this._selectionContent.reset();
  86262. for (var index = 0; index < this.blocks.length; index++) {
  86263. var block = this.blocks[index];
  86264. block.intersectsRay(ray, this._selectionContent);
  86265. }
  86266. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86267. return this._selectionContent;
  86268. };
  86269. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86270. target.blocks = new Array();
  86271. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86272. // Segmenting space
  86273. for (var x = 0; x < 2; x++) {
  86274. for (var y = 0; y < 2; y++) {
  86275. for (var z = 0; z < 2; z++) {
  86276. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86277. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86278. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86279. block.addEntries(entries);
  86280. target.blocks.push(block);
  86281. }
  86282. }
  86283. }
  86284. };
  86285. Octree.CreationFuncForMeshes = function (entry, block) {
  86286. var boundingInfo = entry.getBoundingInfo();
  86287. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86288. block.entries.push(entry);
  86289. }
  86290. };
  86291. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86292. var boundingInfo = entry.getBoundingInfo();
  86293. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86294. block.entries.push(entry);
  86295. }
  86296. };
  86297. return Octree;
  86298. }());
  86299. BABYLON.Octree = Octree;
  86300. })(BABYLON || (BABYLON = {}));
  86301. //# sourceMappingURL=babylon.octree.js.map
  86302. var BABYLON;
  86303. (function (BABYLON) {
  86304. var OctreeBlock = /** @class */ (function () {
  86305. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86306. this.entries = new Array();
  86307. this._boundingVectors = new Array();
  86308. this._capacity = capacity;
  86309. this._depth = depth;
  86310. this._maxDepth = maxDepth;
  86311. this._creationFunc = creationFunc;
  86312. this._minPoint = minPoint;
  86313. this._maxPoint = maxPoint;
  86314. this._boundingVectors.push(minPoint.clone());
  86315. this._boundingVectors.push(maxPoint.clone());
  86316. this._boundingVectors.push(minPoint.clone());
  86317. this._boundingVectors[2].x = maxPoint.x;
  86318. this._boundingVectors.push(minPoint.clone());
  86319. this._boundingVectors[3].y = maxPoint.y;
  86320. this._boundingVectors.push(minPoint.clone());
  86321. this._boundingVectors[4].z = maxPoint.z;
  86322. this._boundingVectors.push(maxPoint.clone());
  86323. this._boundingVectors[5].z = minPoint.z;
  86324. this._boundingVectors.push(maxPoint.clone());
  86325. this._boundingVectors[6].x = minPoint.x;
  86326. this._boundingVectors.push(maxPoint.clone());
  86327. this._boundingVectors[7].y = minPoint.y;
  86328. }
  86329. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86330. // Property
  86331. get: function () {
  86332. return this._capacity;
  86333. },
  86334. enumerable: true,
  86335. configurable: true
  86336. });
  86337. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86338. get: function () {
  86339. return this._minPoint;
  86340. },
  86341. enumerable: true,
  86342. configurable: true
  86343. });
  86344. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86345. get: function () {
  86346. return this._maxPoint;
  86347. },
  86348. enumerable: true,
  86349. configurable: true
  86350. });
  86351. // Methods
  86352. OctreeBlock.prototype.addEntry = function (entry) {
  86353. if (this.blocks) {
  86354. for (var index = 0; index < this.blocks.length; index++) {
  86355. var block = this.blocks[index];
  86356. block.addEntry(entry);
  86357. }
  86358. return;
  86359. }
  86360. this._creationFunc(entry, this);
  86361. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86362. this.createInnerBlocks();
  86363. }
  86364. };
  86365. OctreeBlock.prototype.addEntries = function (entries) {
  86366. for (var index = 0; index < entries.length; index++) {
  86367. var mesh = entries[index];
  86368. this.addEntry(mesh);
  86369. }
  86370. };
  86371. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86372. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86373. if (this.blocks) {
  86374. for (var index = 0; index < this.blocks.length; index++) {
  86375. var block = this.blocks[index];
  86376. block.select(frustumPlanes, selection, allowDuplicate);
  86377. }
  86378. return;
  86379. }
  86380. if (allowDuplicate) {
  86381. selection.concat(this.entries);
  86382. }
  86383. else {
  86384. selection.concatWithNoDuplicate(this.entries);
  86385. }
  86386. }
  86387. };
  86388. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86389. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86390. if (this.blocks) {
  86391. for (var index = 0; index < this.blocks.length; index++) {
  86392. var block = this.blocks[index];
  86393. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86394. }
  86395. return;
  86396. }
  86397. if (allowDuplicate) {
  86398. selection.concat(this.entries);
  86399. }
  86400. else {
  86401. selection.concatWithNoDuplicate(this.entries);
  86402. }
  86403. }
  86404. };
  86405. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86406. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86407. if (this.blocks) {
  86408. for (var index = 0; index < this.blocks.length; index++) {
  86409. var block = this.blocks[index];
  86410. block.intersectsRay(ray, selection);
  86411. }
  86412. return;
  86413. }
  86414. selection.concatWithNoDuplicate(this.entries);
  86415. }
  86416. };
  86417. OctreeBlock.prototype.createInnerBlocks = function () {
  86418. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86419. };
  86420. return OctreeBlock;
  86421. }());
  86422. BABYLON.OctreeBlock = OctreeBlock;
  86423. })(BABYLON || (BABYLON = {}));
  86424. //# sourceMappingURL=babylon.octreeBlock.js.map
  86425. var BABYLON;
  86426. (function (BABYLON) {
  86427. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86428. __extends(VRDistortionCorrectionPostProcess, _super);
  86429. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86430. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86431. 'LensCenter',
  86432. 'Scale',
  86433. 'ScaleIn',
  86434. 'HmdWarpParam'
  86435. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86436. _this._isRightEye = isRightEye;
  86437. _this._distortionFactors = vrMetrics.distortionK;
  86438. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86439. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86440. _this.adaptScaleToCurrentViewport = true;
  86441. _this.onSizeChangedObservable.add(function () {
  86442. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86443. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86444. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86445. });
  86446. _this.onApplyObservable.add(function (effect) {
  86447. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86448. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86449. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86450. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86451. });
  86452. return _this;
  86453. }
  86454. return VRDistortionCorrectionPostProcess;
  86455. }(BABYLON.PostProcess));
  86456. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86457. })(BABYLON || (BABYLON = {}));
  86458. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86459. var BABYLON;
  86460. (function (BABYLON) {
  86461. /**
  86462. * Postprocess used to generate anaglyphic rendering
  86463. */
  86464. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86465. __extends(AnaglyphPostProcess, _super);
  86466. /**
  86467. * Creates a new AnaglyphPostProcess
  86468. * @param name defines postprocess name
  86469. * @param options defines creation options or target ratio scale
  86470. * @param rigCameras defines cameras using this postprocess
  86471. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86472. * @param engine defines hosting engine
  86473. * @param reusable defines if the postprocess will be reused multiple times per frame
  86474. */
  86475. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86476. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86477. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86478. _this.onApplyObservable.add(function (effect) {
  86479. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86480. });
  86481. return _this;
  86482. }
  86483. return AnaglyphPostProcess;
  86484. }(BABYLON.PostProcess));
  86485. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86486. })(BABYLON || (BABYLON = {}));
  86487. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86488. var BABYLON;
  86489. (function (BABYLON) {
  86490. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86491. __extends(StereoscopicInterlacePostProcess, _super);
  86492. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86493. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86494. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86495. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86496. _this.onSizeChangedObservable.add(function () {
  86497. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86498. });
  86499. _this.onApplyObservable.add(function (effect) {
  86500. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86501. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86502. });
  86503. return _this;
  86504. }
  86505. return StereoscopicInterlacePostProcess;
  86506. }(BABYLON.PostProcess));
  86507. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86508. })(BABYLON || (BABYLON = {}));
  86509. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86510. var BABYLON;
  86511. (function (BABYLON) {
  86512. /**
  86513. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86514. * Screen rotation is taken into account.
  86515. */
  86516. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86517. function FreeCameraDeviceOrientationInput() {
  86518. var _this = this;
  86519. this._screenOrientationAngle = 0;
  86520. this._screenQuaternion = new BABYLON.Quaternion();
  86521. this._alpha = 0;
  86522. this._beta = 0;
  86523. this._gamma = 0;
  86524. this._orientationChanged = function () {
  86525. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86526. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86527. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86528. };
  86529. this._deviceOrientation = function (evt) {
  86530. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86531. _this._beta = evt.beta !== null ? evt.beta : 0;
  86532. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86533. };
  86534. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86535. this._orientationChanged();
  86536. }
  86537. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86538. get: function () {
  86539. return this._camera;
  86540. },
  86541. set: function (camera) {
  86542. this._camera = camera;
  86543. if (this._camera != null && !this._camera.rotationQuaternion) {
  86544. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86545. }
  86546. },
  86547. enumerable: true,
  86548. configurable: true
  86549. });
  86550. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86551. window.addEventListener("orientationchange", this._orientationChanged);
  86552. window.addEventListener("deviceorientation", this._deviceOrientation);
  86553. //In certain cases, the attach control is called AFTER orientation was changed,
  86554. //So this is needed.
  86555. this._orientationChanged();
  86556. };
  86557. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86558. window.removeEventListener("orientationchange", this._orientationChanged);
  86559. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86560. };
  86561. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86562. //if no device orientation provided, don't update the rotation.
  86563. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86564. if (!this._alpha)
  86565. return;
  86566. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86567. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86568. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86569. //Mirror on XY Plane
  86570. this._camera.rotationQuaternion.z *= -1;
  86571. this._camera.rotationQuaternion.w *= -1;
  86572. };
  86573. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86574. return "FreeCameraDeviceOrientationInput";
  86575. };
  86576. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86577. return "deviceOrientation";
  86578. };
  86579. return FreeCameraDeviceOrientationInput;
  86580. }());
  86581. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86582. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86583. })(BABYLON || (BABYLON = {}));
  86584. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86585. var BABYLON;
  86586. (function (BABYLON) {
  86587. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86588. function ArcRotateCameraVRDeviceOrientationInput() {
  86589. this.alphaCorrection = 1;
  86590. this.betaCorrection = 1;
  86591. this.gammaCorrection = 1;
  86592. this._alpha = 0;
  86593. this._gamma = 0;
  86594. this._dirty = false;
  86595. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86596. }
  86597. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86598. this.camera.attachControl(element, noPreventDefault);
  86599. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86600. };
  86601. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86602. if (evt.alpha !== null) {
  86603. this._alpha = +evt.alpha | 0;
  86604. }
  86605. if (evt.gamma !== null) {
  86606. this._gamma = +evt.gamma | 0;
  86607. }
  86608. this._dirty = true;
  86609. };
  86610. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86611. if (this._dirty) {
  86612. this._dirty = false;
  86613. if (this._gamma < 0) {
  86614. this._gamma = 180 + this._gamma;
  86615. }
  86616. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86617. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86618. }
  86619. };
  86620. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86621. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86622. };
  86623. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86624. return "ArcRotateCameraVRDeviceOrientationInput";
  86625. };
  86626. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86627. return "VRDeviceOrientation";
  86628. };
  86629. return ArcRotateCameraVRDeviceOrientationInput;
  86630. }());
  86631. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86632. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86633. })(BABYLON || (BABYLON = {}));
  86634. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86635. var BABYLON;
  86636. (function (BABYLON) {
  86637. var VRCameraMetrics = /** @class */ (function () {
  86638. function VRCameraMetrics() {
  86639. this.compensateDistortion = true;
  86640. }
  86641. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86642. get: function () {
  86643. return this.hResolution / (2 * this.vResolution);
  86644. },
  86645. enumerable: true,
  86646. configurable: true
  86647. });
  86648. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86649. get: function () {
  86650. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86651. },
  86652. enumerable: true,
  86653. configurable: true
  86654. });
  86655. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86656. get: function () {
  86657. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86658. var h = (4 * meters) / this.hScreenSize;
  86659. return BABYLON.Matrix.Translation(h, 0, 0);
  86660. },
  86661. enumerable: true,
  86662. configurable: true
  86663. });
  86664. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86665. get: function () {
  86666. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86667. var h = (4 * meters) / this.hScreenSize;
  86668. return BABYLON.Matrix.Translation(-h, 0, 0);
  86669. },
  86670. enumerable: true,
  86671. configurable: true
  86672. });
  86673. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86674. get: function () {
  86675. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86676. },
  86677. enumerable: true,
  86678. configurable: true
  86679. });
  86680. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86681. get: function () {
  86682. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86683. },
  86684. enumerable: true,
  86685. configurable: true
  86686. });
  86687. VRCameraMetrics.GetDefault = function () {
  86688. var result = new VRCameraMetrics();
  86689. result.hResolution = 1280;
  86690. result.vResolution = 800;
  86691. result.hScreenSize = 0.149759993;
  86692. result.vScreenSize = 0.0935999975;
  86693. result.vScreenCenter = 0.0467999987;
  86694. result.eyeToScreenDistance = 0.0410000011;
  86695. result.lensSeparationDistance = 0.0635000020;
  86696. result.interpupillaryDistance = 0.0640000030;
  86697. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86698. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86699. result.postProcessScaleFactor = 1.714605507808412;
  86700. result.lensCenterOffset = 0.151976421;
  86701. return result;
  86702. };
  86703. return VRCameraMetrics;
  86704. }());
  86705. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86706. })(BABYLON || (BABYLON = {}));
  86707. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86708. var BABYLON;
  86709. (function (BABYLON) {
  86710. /**
  86711. * This represents a WebVR camera.
  86712. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86713. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86714. */
  86715. var WebVRFreeCamera = /** @class */ (function (_super) {
  86716. __extends(WebVRFreeCamera, _super);
  86717. /**
  86718. * Instantiates a WebVRFreeCamera.
  86719. * @param name The name of the WebVRFreeCamera
  86720. * @param position The starting anchor position for the camera
  86721. * @param scene The scene the camera belongs to
  86722. * @param webVROptions a set of customizable options for the webVRCamera
  86723. */
  86724. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86725. if (webVROptions === void 0) { webVROptions = {}; }
  86726. var _this = _super.call(this, name, position, scene) || this;
  86727. _this.webVROptions = webVROptions;
  86728. /**
  86729. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86730. */
  86731. _this._vrDevice = null;
  86732. /**
  86733. * The rawPose of the vrDevice.
  86734. */
  86735. _this.rawPose = null;
  86736. _this._specsVersion = "1.1";
  86737. _this._attached = false;
  86738. _this._descendants = [];
  86739. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86740. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86741. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86742. _this._standingMatrix = null;
  86743. /**
  86744. * Represents device position in babylon space.
  86745. */
  86746. _this.devicePosition = BABYLON.Vector3.Zero();
  86747. /**
  86748. * Represents device rotation in babylon space.
  86749. */
  86750. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86751. /**
  86752. * The scale of the device to be used when translating from device space to babylon space.
  86753. */
  86754. _this.deviceScaleFactor = 1;
  86755. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86756. _this._worldToDevice = BABYLON.Matrix.Identity();
  86757. /**
  86758. * References to the webVR controllers for the vrDevice.
  86759. */
  86760. _this.controllers = [];
  86761. /**
  86762. * Emits an event when a controller is attached.
  86763. */
  86764. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86765. /**
  86766. * Emits an event when a controller's mesh has been loaded;
  86767. */
  86768. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86769. /**
  86770. * If the rig cameras be used as parent instead of this camera.
  86771. */
  86772. _this.rigParenting = true;
  86773. _this._defaultHeight = undefined;
  86774. _this._workingVector = BABYLON.Vector3.Zero();
  86775. _this._oneVector = BABYLON.Vector3.One();
  86776. _this._workingMatrix = BABYLON.Matrix.Identity();
  86777. _this._cache.position = BABYLON.Vector3.Zero();
  86778. if (webVROptions.defaultHeight) {
  86779. _this._defaultHeight = webVROptions.defaultHeight;
  86780. _this.position.y = _this._defaultHeight;
  86781. }
  86782. _this.minZ = 0.1;
  86783. //legacy support - the compensation boolean was removed.
  86784. if (arguments.length === 5) {
  86785. _this.webVROptions = arguments[4];
  86786. }
  86787. // default webVR options
  86788. if (_this.webVROptions.trackPosition == undefined) {
  86789. _this.webVROptions.trackPosition = true;
  86790. }
  86791. if (_this.webVROptions.controllerMeshes == undefined) {
  86792. _this.webVROptions.controllerMeshes = true;
  86793. }
  86794. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86795. _this.webVROptions.defaultLightingOnControllers = true;
  86796. }
  86797. _this.rotationQuaternion = new BABYLON.Quaternion();
  86798. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86799. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86800. }
  86801. //enable VR
  86802. var engine = _this.getEngine();
  86803. _this._onVREnabled = function (success) { if (success) {
  86804. _this.initControllers();
  86805. } };
  86806. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86807. engine.initWebVR().add(function (event) {
  86808. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86809. return;
  86810. }
  86811. _this._vrDevice = event.vrDisplay;
  86812. //reset the rig parameters.
  86813. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86814. if (_this._attached) {
  86815. _this.getEngine().enableVR();
  86816. }
  86817. });
  86818. if (typeof (VRFrameData) !== "undefined")
  86819. _this._frameData = new VRFrameData();
  86820. /**
  86821. * The idea behind the following lines:
  86822. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86823. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86824. * the second will not show it correctly.
  86825. *
  86826. * To solve this - each object that has the camera as parent will be added to a protected array.
  86827. * When the rig camera renders, it will take this array and set all of those to be its children.
  86828. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86829. * Amazing!
  86830. */
  86831. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86832. if (camera.parent === _this && _this.rigParenting) {
  86833. _this._descendants = _this.getDescendants(true, function (n) {
  86834. // don't take the cameras or the controllers!
  86835. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86836. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86837. return !isController && !isRigCamera;
  86838. });
  86839. _this._descendants.forEach(function (node) {
  86840. node.parent = camera;
  86841. });
  86842. }
  86843. });
  86844. scene.onAfterCameraRenderObservable.add(function (camera) {
  86845. if (camera.parent === _this && _this.rigParenting) {
  86846. _this._descendants.forEach(function (node) {
  86847. node.parent = _this;
  86848. });
  86849. }
  86850. });
  86851. return _this;
  86852. }
  86853. /**
  86854. * Gets the device distance from the ground in meters.
  86855. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  86856. */
  86857. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86858. if (this._standingMatrix) {
  86859. // Add standing matrix offset to get real offset from ground in room
  86860. this._standingMatrix.getTranslationToRef(this._workingVector);
  86861. return this._deviceRoomPosition.y + this._workingVector.y;
  86862. }
  86863. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86864. return this._defaultHeight || 0;
  86865. };
  86866. /**
  86867. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86868. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86869. */
  86870. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86871. var _this = this;
  86872. if (callback === void 0) { callback = function (bool) { }; }
  86873. // Use standing matrix if available
  86874. this.getEngine().initWebVRAsync().then(function (result) {
  86875. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86876. callback(false);
  86877. }
  86878. else {
  86879. _this._standingMatrix = new BABYLON.Matrix();
  86880. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86881. if (!_this.getScene().useRightHandedSystem) {
  86882. [2, 6, 8, 9, 14].forEach(function (num) {
  86883. if (_this._standingMatrix) {
  86884. _this._standingMatrix.m[num] *= -1;
  86885. }
  86886. });
  86887. }
  86888. callback(true);
  86889. }
  86890. });
  86891. };
  86892. /**
  86893. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86894. * @returns A promise with a boolean set to if the standing matrix is supported.
  86895. */
  86896. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86897. var _this = this;
  86898. return new Promise(function (res, rej) {
  86899. _this.useStandingMatrix(function (supported) {
  86900. res(supported);
  86901. });
  86902. });
  86903. };
  86904. /**
  86905. * Disposes the camera
  86906. */
  86907. WebVRFreeCamera.prototype.dispose = function () {
  86908. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86909. _super.prototype.dispose.call(this);
  86910. };
  86911. /**
  86912. * Gets a vrController by name.
  86913. * @param name The name of the controller to retreive
  86914. * @returns the controller matching the name specified or null if not found
  86915. */
  86916. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86917. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86918. var gp = _a[_i];
  86919. if (gp.hand === name) {
  86920. return gp;
  86921. }
  86922. }
  86923. return null;
  86924. };
  86925. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86926. /**
  86927. * The controller corrisponding to the users left hand.
  86928. */
  86929. get: function () {
  86930. if (!this._leftController) {
  86931. this._leftController = this.getControllerByName("left");
  86932. }
  86933. return this._leftController;
  86934. },
  86935. enumerable: true,
  86936. configurable: true
  86937. });
  86938. ;
  86939. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86940. /**
  86941. * The controller corrisponding to the users right hand.
  86942. */
  86943. get: function () {
  86944. if (!this._rightController) {
  86945. this._rightController = this.getControllerByName("right");
  86946. }
  86947. return this._rightController;
  86948. },
  86949. enumerable: true,
  86950. configurable: true
  86951. });
  86952. ;
  86953. /**
  86954. * Casts a ray forward from the vrCamera's gaze.
  86955. * @param length Length of the ray (default: 100)
  86956. * @returns the ray corrisponding to the gaze
  86957. */
  86958. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86959. if (length === void 0) { length = 100; }
  86960. if (this.leftCamera) {
  86961. // Use left eye to avoid computation to compute center on every call
  86962. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86963. }
  86964. else {
  86965. return _super.prototype.getForwardRay.call(this, length);
  86966. }
  86967. };
  86968. /**
  86969. * Updates the camera based on device's frame data
  86970. */
  86971. WebVRFreeCamera.prototype._checkInputs = function () {
  86972. if (this._vrDevice && this._vrDevice.isPresenting) {
  86973. this._vrDevice.getFrameData(this._frameData);
  86974. this.updateFromDevice(this._frameData.pose);
  86975. }
  86976. _super.prototype._checkInputs.call(this);
  86977. };
  86978. /**
  86979. * Updates the poseControlled values based on the input device pose.
  86980. * @param poseData Pose coming from the device
  86981. */
  86982. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86983. if (poseData && poseData.orientation) {
  86984. this.rawPose = poseData;
  86985. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86986. if (this.getScene().useRightHandedSystem) {
  86987. this._deviceRoomRotationQuaternion.z *= -1;
  86988. this._deviceRoomRotationQuaternion.w *= -1;
  86989. }
  86990. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86991. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86992. if (this.getScene().useRightHandedSystem) {
  86993. this._deviceRoomPosition.z *= -1;
  86994. }
  86995. }
  86996. }
  86997. };
  86998. /**
  86999. * WebVR's attach control will start broadcasting frames to the device.
  87000. * Note that in certain browsers (chrome for example) this function must be called
  87001. * within a user-interaction callback. Example:
  87002. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87003. *
  87004. * @param element html element to attach the vrDevice to
  87005. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87006. */
  87007. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87008. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87009. this._attached = true;
  87010. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87011. if (this._vrDevice) {
  87012. this.getEngine().enableVR();
  87013. }
  87014. };
  87015. /**
  87016. * Detaches the camera from the html element and disables VR
  87017. *
  87018. * @param element html element to detach from
  87019. */
  87020. WebVRFreeCamera.prototype.detachControl = function (element) {
  87021. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87022. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87023. _super.prototype.detachControl.call(this, element);
  87024. this._attached = false;
  87025. this.getEngine().disableVR();
  87026. };
  87027. /**
  87028. * @returns the name of this class
  87029. */
  87030. WebVRFreeCamera.prototype.getClassName = function () {
  87031. return "WebVRFreeCamera";
  87032. };
  87033. /**
  87034. * Calls resetPose on the vrDisplay
  87035. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87036. */
  87037. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87038. //uses the vrDisplay's "resetPose()".
  87039. //pitch and roll won't be affected.
  87040. this._vrDevice.resetPose();
  87041. };
  87042. /**
  87043. * Updates the rig cameras (left and right eye)
  87044. */
  87045. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87046. var camLeft = this._rigCameras[0];
  87047. var camRight = this._rigCameras[1];
  87048. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87049. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87050. camLeft.position.copyFrom(this._deviceRoomPosition);
  87051. camRight.position.copyFrom(this._deviceRoomPosition);
  87052. };
  87053. /**
  87054. * Updates the cached values of the camera
  87055. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87056. */
  87057. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87058. var _this = this;
  87059. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87060. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87061. if (!this.updateCacheCalled) {
  87062. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87063. this.updateCacheCalled = true;
  87064. this.update();
  87065. }
  87066. // Set working vector to the device position in room space rotated by the new rotation
  87067. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87068. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87069. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87070. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87071. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87072. // Add translation from anchor position
  87073. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87074. this._workingVector.addInPlace(this.position);
  87075. this._workingVector.subtractInPlace(this._cache.position);
  87076. this._deviceToWorld.setTranslation(this._workingVector);
  87077. // Set an inverted matrix to be used when updating the camera
  87078. this._deviceToWorld.invertToRef(this._worldToDevice);
  87079. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87080. this.controllers.forEach(function (controller) {
  87081. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87082. controller.update();
  87083. });
  87084. }
  87085. if (!ignoreParentClass) {
  87086. _super.prototype._updateCache.call(this);
  87087. }
  87088. this.updateCacheCalled = false;
  87089. };
  87090. /**
  87091. * Updates the current device position and rotation in the babylon world
  87092. */
  87093. WebVRFreeCamera.prototype.update = function () {
  87094. // Get current device position in babylon world
  87095. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87096. // Get current device rotation in babylon world
  87097. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87098. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87099. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87100. _super.prototype.update.call(this);
  87101. };
  87102. /**
  87103. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87104. * @returns an identity matrix
  87105. */
  87106. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87107. return BABYLON.Matrix.Identity();
  87108. };
  87109. /**
  87110. * This function is called by the two RIG cameras.
  87111. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87112. */
  87113. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87114. var _this = this;
  87115. // Update the parent camera prior to using a child camera to avoid desynchronization
  87116. var parentCamera = this._cameraRigParams["parentCamera"];
  87117. parentCamera._updateCache();
  87118. //WebVR 1.1
  87119. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87120. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87121. if (!this.getScene().useRightHandedSystem) {
  87122. [2, 6, 8, 9, 14].forEach(function (num) {
  87123. _this._webvrViewMatrix.m[num] *= -1;
  87124. });
  87125. }
  87126. // update the camera rotation matrix
  87127. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87128. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87129. // Computing target and final matrix
  87130. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87131. // should the view matrix be updated with scale and position offset?
  87132. if (parentCamera.deviceScaleFactor !== 1) {
  87133. this._webvrViewMatrix.invert();
  87134. // scale the position, if set
  87135. if (parentCamera.deviceScaleFactor) {
  87136. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87137. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87138. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87139. }
  87140. this._webvrViewMatrix.invert();
  87141. }
  87142. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87143. // Compute global position
  87144. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87145. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87146. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87147. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87148. this._markSyncedWithParent();
  87149. return this._webvrViewMatrix;
  87150. };
  87151. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87152. var _this = this;
  87153. var parentCamera = this.parent;
  87154. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87155. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87156. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87157. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87158. //babylon compatible matrix
  87159. if (!this.getScene().useRightHandedSystem) {
  87160. [8, 9, 10, 11].forEach(function (num) {
  87161. _this._projectionMatrix.m[num] *= -1;
  87162. });
  87163. }
  87164. return this._projectionMatrix;
  87165. };
  87166. /**
  87167. * Initializes the controllers and their meshes
  87168. */
  87169. WebVRFreeCamera.prototype.initControllers = function () {
  87170. var _this = this;
  87171. this.controllers = [];
  87172. var manager = this.getScene().gamepadManager;
  87173. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87174. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87175. var webVrController = gamepad;
  87176. if (webVrController.defaultModel) {
  87177. webVrController.defaultModel.setEnabled(false);
  87178. }
  87179. if (webVrController.hand === "right") {
  87180. _this._rightController = null;
  87181. }
  87182. if (webVrController.hand === "left") {
  87183. _this._leftController = null;
  87184. }
  87185. var controllerIndex = _this.controllers.indexOf(webVrController);
  87186. if (controllerIndex !== -1) {
  87187. _this.controllers.splice(controllerIndex, 1);
  87188. }
  87189. }
  87190. });
  87191. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87192. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87193. var webVrController_1 = gamepad;
  87194. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87195. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87196. if (_this.webVROptions.controllerMeshes) {
  87197. if (webVrController_1.defaultModel) {
  87198. webVrController_1.defaultModel.setEnabled(true);
  87199. }
  87200. else {
  87201. // Load the meshes
  87202. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87203. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87204. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87205. if (_this.webVROptions.defaultLightingOnControllers) {
  87206. if (!_this._lightOnControllers) {
  87207. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87208. }
  87209. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87210. var children = mesh.getChildren();
  87211. if (children.length !== 0) {
  87212. children.forEach(function (mesh) {
  87213. light.includedOnlyMeshes.push(mesh);
  87214. activateLightOnSubMeshes_1(mesh, light);
  87215. });
  87216. }
  87217. };
  87218. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87219. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87220. }
  87221. });
  87222. }
  87223. }
  87224. webVrController_1.attachToPoseControlledCamera(_this);
  87225. // since this is async - sanity check. Is the controller already stored?
  87226. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87227. //add to the controllers array
  87228. _this.controllers.push(webVrController_1);
  87229. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87230. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87231. // So we're overriding setting left & right manually to be sure
  87232. var firstViveWandDetected = false;
  87233. for (var i = 0; i < _this.controllers.length; i++) {
  87234. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87235. if (!firstViveWandDetected) {
  87236. firstViveWandDetected = true;
  87237. _this.controllers[i].hand = "left";
  87238. }
  87239. else {
  87240. _this.controllers[i].hand = "right";
  87241. }
  87242. }
  87243. }
  87244. //did we find enough controllers? Great! let the developer know.
  87245. if (_this.controllers.length >= 2) {
  87246. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87247. }
  87248. }
  87249. }
  87250. });
  87251. };
  87252. return WebVRFreeCamera;
  87253. }(BABYLON.FreeCamera));
  87254. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87255. })(BABYLON || (BABYLON = {}));
  87256. //# sourceMappingURL=babylon.webVRCamera.js.map
  87257. var BABYLON;
  87258. (function (BABYLON) {
  87259. // We're mainly based on the logic defined into the FreeCamera code
  87260. /**
  87261. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87262. * being tilted forward or back and left or right.
  87263. */
  87264. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87265. __extends(DeviceOrientationCamera, _super);
  87266. /**
  87267. * Creates a new device orientation camera
  87268. * @param name The name of the camera
  87269. * @param position The start position camera
  87270. * @param scene The scene the camera belongs to
  87271. */
  87272. function DeviceOrientationCamera(name, position, scene) {
  87273. var _this = _super.call(this, name, position, scene) || this;
  87274. _this._quaternionCache = new BABYLON.Quaternion();
  87275. _this.inputs.addDeviceOrientation();
  87276. return _this;
  87277. }
  87278. /**
  87279. * Gets the current instance class name ("DeviceOrientationCamera").
  87280. * This helps avoiding instanceof at run time.
  87281. * @returns the class name
  87282. */
  87283. DeviceOrientationCamera.prototype.getClassName = function () {
  87284. return "DeviceOrientationCamera";
  87285. };
  87286. /**
  87287. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87288. */
  87289. DeviceOrientationCamera.prototype._checkInputs = function () {
  87290. _super.prototype._checkInputs.call(this);
  87291. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87292. if (this._initialQuaternion) {
  87293. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87294. }
  87295. };
  87296. /**
  87297. * Reset the camera to its default orientation on the specified axis only.
  87298. * @param axis The axis to reset
  87299. */
  87300. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87301. var _this = this;
  87302. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87303. //can only work if this camera has a rotation quaternion already.
  87304. if (!this.rotationQuaternion)
  87305. return;
  87306. if (!this._initialQuaternion) {
  87307. this._initialQuaternion = new BABYLON.Quaternion();
  87308. }
  87309. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87310. ['x', 'y', 'z'].forEach(function (axisName) {
  87311. if (!axis[axisName]) {
  87312. _this._initialQuaternion[axisName] = 0;
  87313. }
  87314. else {
  87315. _this._initialQuaternion[axisName] *= -1;
  87316. }
  87317. });
  87318. this._initialQuaternion.normalize();
  87319. //force rotation update
  87320. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87321. };
  87322. return DeviceOrientationCamera;
  87323. }(BABYLON.FreeCamera));
  87324. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87325. })(BABYLON || (BABYLON = {}));
  87326. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87327. var BABYLON;
  87328. (function (BABYLON) {
  87329. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87330. __extends(VRDeviceOrientationFreeCamera, _super);
  87331. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87332. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87333. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87334. var _this = _super.call(this, name, position, scene) || this;
  87335. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87336. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87337. return _this;
  87338. }
  87339. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87340. return "VRDeviceOrientationFreeCamera";
  87341. };
  87342. return VRDeviceOrientationFreeCamera;
  87343. }(BABYLON.DeviceOrientationCamera));
  87344. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87345. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87346. __extends(VRDeviceOrientationGamepadCamera, _super);
  87347. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87348. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87349. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87350. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87351. _this.inputs.addGamepad();
  87352. return _this;
  87353. }
  87354. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87355. return "VRDeviceOrientationGamepadCamera";
  87356. };
  87357. return VRDeviceOrientationGamepadCamera;
  87358. }(VRDeviceOrientationFreeCamera));
  87359. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87360. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87361. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87362. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87363. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87364. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87365. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87366. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87367. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87368. _this.inputs.addVRDeviceOrientation();
  87369. return _this;
  87370. }
  87371. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87372. return "VRDeviceOrientationArcRotateCamera";
  87373. };
  87374. return VRDeviceOrientationArcRotateCamera;
  87375. }(BABYLON.ArcRotateCamera));
  87376. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87377. })(BABYLON || (BABYLON = {}));
  87378. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87379. var BABYLON;
  87380. (function (BABYLON) {
  87381. /**
  87382. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87383. */
  87384. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87385. __extends(AnaglyphFreeCamera, _super);
  87386. /**
  87387. * Creates a new AnaglyphFreeCamera
  87388. * @param name defines camera name
  87389. * @param position defines initial position
  87390. * @param interaxialDistance defines distance between each color axis
  87391. * @param scene defines the hosting scene
  87392. */
  87393. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87394. var _this = _super.call(this, name, position, scene) || this;
  87395. _this.interaxialDistance = interaxialDistance;
  87396. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87397. return _this;
  87398. }
  87399. /**
  87400. * Gets camera class name
  87401. * @returns AnaglyphFreeCamera
  87402. */
  87403. AnaglyphFreeCamera.prototype.getClassName = function () {
  87404. return "AnaglyphFreeCamera";
  87405. };
  87406. return AnaglyphFreeCamera;
  87407. }(BABYLON.FreeCamera));
  87408. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87409. /**
  87410. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87411. */
  87412. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87413. __extends(AnaglyphArcRotateCamera, _super);
  87414. /**
  87415. * Creates a new AnaglyphArcRotateCamera
  87416. * @param name defines camera name
  87417. * @param alpha defines alpha angle (in radians)
  87418. * @param beta defines beta angle (in radians)
  87419. * @param radius defines radius
  87420. * @param target defines camera target
  87421. * @param interaxialDistance defines distance between each color axis
  87422. * @param scene defines the hosting scene
  87423. */
  87424. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87425. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87426. _this.interaxialDistance = interaxialDistance;
  87427. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87428. return _this;
  87429. }
  87430. /**
  87431. * Gets camera class name
  87432. * @returns AnaglyphArcRotateCamera
  87433. */
  87434. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87435. return "AnaglyphArcRotateCamera";
  87436. };
  87437. return AnaglyphArcRotateCamera;
  87438. }(BABYLON.ArcRotateCamera));
  87439. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87440. /**
  87441. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87442. */
  87443. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87444. __extends(AnaglyphGamepadCamera, _super);
  87445. /**
  87446. * Creates a new AnaglyphGamepadCamera
  87447. * @param name defines camera name
  87448. * @param position defines initial position
  87449. * @param interaxialDistance defines distance between each color axis
  87450. * @param scene defines the hosting scene
  87451. */
  87452. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87453. var _this = _super.call(this, name, position, scene) || this;
  87454. _this.interaxialDistance = interaxialDistance;
  87455. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87456. return _this;
  87457. }
  87458. /**
  87459. * Gets camera class name
  87460. * @returns AnaglyphGamepadCamera
  87461. */
  87462. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87463. return "AnaglyphGamepadCamera";
  87464. };
  87465. return AnaglyphGamepadCamera;
  87466. }(BABYLON.GamepadCamera));
  87467. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87468. /**
  87469. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87470. */
  87471. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87472. __extends(AnaglyphUniversalCamera, _super);
  87473. /**
  87474. * Creates a new AnaglyphUniversalCamera
  87475. * @param name defines camera name
  87476. * @param position defines initial position
  87477. * @param interaxialDistance defines distance between each color axis
  87478. * @param scene defines the hosting scene
  87479. */
  87480. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87481. var _this = _super.call(this, name, position, scene) || this;
  87482. _this.interaxialDistance = interaxialDistance;
  87483. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87484. return _this;
  87485. }
  87486. /**
  87487. * Gets camera class name
  87488. * @returns AnaglyphUniversalCamera
  87489. */
  87490. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87491. return "AnaglyphUniversalCamera";
  87492. };
  87493. return AnaglyphUniversalCamera;
  87494. }(BABYLON.UniversalCamera));
  87495. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87496. /**
  87497. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87498. */
  87499. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87500. __extends(StereoscopicFreeCamera, _super);
  87501. /**
  87502. * Creates a new StereoscopicFreeCamera
  87503. * @param name defines camera name
  87504. * @param position defines initial position
  87505. * @param interaxialDistance defines distance between each color axis
  87506. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87507. * @param scene defines the hosting scene
  87508. */
  87509. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87510. var _this = _super.call(this, name, position, scene) || this;
  87511. _this.interaxialDistance = interaxialDistance;
  87512. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87513. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87514. return _this;
  87515. }
  87516. /**
  87517. * Gets camera class name
  87518. * @returns StereoscopicFreeCamera
  87519. */
  87520. StereoscopicFreeCamera.prototype.getClassName = function () {
  87521. return "StereoscopicFreeCamera";
  87522. };
  87523. return StereoscopicFreeCamera;
  87524. }(BABYLON.FreeCamera));
  87525. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87526. /**
  87527. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87528. */
  87529. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87530. __extends(StereoscopicArcRotateCamera, _super);
  87531. /**
  87532. * Creates a new StereoscopicArcRotateCamera
  87533. * @param name defines camera name
  87534. * @param alpha defines alpha angle (in radians)
  87535. * @param beta defines beta angle (in radians)
  87536. * @param radius defines radius
  87537. * @param target defines camera target
  87538. * @param interaxialDistance defines distance between each color axis
  87539. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87540. * @param scene defines the hosting scene
  87541. */
  87542. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87543. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87544. _this.interaxialDistance = interaxialDistance;
  87545. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87546. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87547. return _this;
  87548. }
  87549. /**
  87550. * Gets camera class name
  87551. * @returns StereoscopicArcRotateCamera
  87552. */
  87553. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87554. return "StereoscopicArcRotateCamera";
  87555. };
  87556. return StereoscopicArcRotateCamera;
  87557. }(BABYLON.ArcRotateCamera));
  87558. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87559. /**
  87560. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87561. */
  87562. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87563. __extends(StereoscopicGamepadCamera, _super);
  87564. /**
  87565. * Creates a new StereoscopicGamepadCamera
  87566. * @param name defines camera name
  87567. * @param position defines initial position
  87568. * @param interaxialDistance defines distance between each color axis
  87569. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87570. * @param scene defines the hosting scene
  87571. */
  87572. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87573. var _this = _super.call(this, name, position, scene) || this;
  87574. _this.interaxialDistance = interaxialDistance;
  87575. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87576. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87577. return _this;
  87578. }
  87579. /**
  87580. * Gets camera class name
  87581. * @returns StereoscopicGamepadCamera
  87582. */
  87583. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87584. return "StereoscopicGamepadCamera";
  87585. };
  87586. return StereoscopicGamepadCamera;
  87587. }(BABYLON.GamepadCamera));
  87588. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87589. /**
  87590. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87591. */
  87592. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87593. __extends(StereoscopicUniversalCamera, _super);
  87594. /**
  87595. * Creates a new StereoscopicUniversalCamera
  87596. * @param name defines camera name
  87597. * @param position defines initial position
  87598. * @param interaxialDistance defines distance between each color axis
  87599. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87600. * @param scene defines the hosting scene
  87601. */
  87602. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87603. var _this = _super.call(this, name, position, scene) || this;
  87604. _this.interaxialDistance = interaxialDistance;
  87605. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87606. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87607. return _this;
  87608. }
  87609. /**
  87610. * Gets camera class name
  87611. * @returns StereoscopicUniversalCamera
  87612. */
  87613. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87614. return "StereoscopicUniversalCamera";
  87615. };
  87616. return StereoscopicUniversalCamera;
  87617. }(BABYLON.UniversalCamera));
  87618. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87619. })(BABYLON || (BABYLON = {}));
  87620. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87621. var BABYLON;
  87622. (function (BABYLON) {
  87623. var VRExperienceHelperGazer = /** @class */ (function () {
  87624. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87625. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87626. this.scene = scene;
  87627. this._pointerDownOnMeshAsked = false;
  87628. this._isActionableMesh = false;
  87629. this._teleportationRequestInitiated = false;
  87630. this._teleportationBackRequestInitiated = false;
  87631. this._rotationRightAsked = false;
  87632. this._rotationLeftAsked = false;
  87633. this._dpadPressed = true;
  87634. this._activePointer = false;
  87635. this._id = VRExperienceHelperGazer._idCounter++;
  87636. // Gaze tracker
  87637. if (!gazeTrackerToClone) {
  87638. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87639. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87640. this._gazeTracker.isPickable = false;
  87641. this._gazeTracker.isVisible = false;
  87642. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87643. targetMat.specularColor = BABYLON.Color3.Black();
  87644. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87645. targetMat.backFaceCulling = false;
  87646. this._gazeTracker.material = targetMat;
  87647. }
  87648. else {
  87649. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87650. }
  87651. }
  87652. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87653. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87654. };
  87655. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87656. this._pointerDownOnMeshAsked = true;
  87657. if (this._currentMeshSelected && this._currentHit) {
  87658. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87659. }
  87660. };
  87661. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87662. if (this._currentMeshSelected && this._currentHit) {
  87663. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87664. }
  87665. this._pointerDownOnMeshAsked = false;
  87666. };
  87667. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87668. this._activePointer = true;
  87669. };
  87670. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87671. this._activePointer = false;
  87672. };
  87673. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87674. if (distance === void 0) { distance = 100; }
  87675. };
  87676. VRExperienceHelperGazer.prototype.dispose = function () {
  87677. this._interactionsEnabled = false;
  87678. this._teleportationEnabled = false;
  87679. if (this._gazeTracker) {
  87680. this._gazeTracker.dispose();
  87681. }
  87682. };
  87683. VRExperienceHelperGazer._idCounter = 0;
  87684. return VRExperienceHelperGazer;
  87685. }());
  87686. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87687. __extends(VRExperienceHelperControllerGazer, _super);
  87688. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87689. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87690. _this.webVRController = webVRController;
  87691. // Laser pointer
  87692. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87693. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87694. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87695. laserPointerMaterial.alpha = 0.6;
  87696. _this._laserPointer.material = laserPointerMaterial;
  87697. _this._laserPointer.rotation.x = Math.PI / 2;
  87698. _this._laserPointer.position.z = -0.5;
  87699. _this._laserPointer.isVisible = false;
  87700. if (!webVRController.mesh) {
  87701. // Create an empty mesh that is used prior to loading the high quality model
  87702. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87703. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87704. preloadPointerPose.rotation.x = -0.7;
  87705. preloadMesh.addChild(preloadPointerPose);
  87706. webVRController.attachToMesh(preloadMesh);
  87707. }
  87708. _this._setLaserPointerParent(webVRController.mesh);
  87709. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87710. _this._setLaserPointerParent(mesh);
  87711. });
  87712. return _this;
  87713. }
  87714. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87715. return this.webVRController.getForwardRay(length);
  87716. };
  87717. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87718. _super.prototype._activatePointer.call(this);
  87719. this._laserPointer.isVisible = true;
  87720. };
  87721. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87722. _super.prototype._deactivatePointer.call(this);
  87723. this._laserPointer.isVisible = false;
  87724. };
  87725. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87726. this._laserPointer.material.emissiveColor = color;
  87727. };
  87728. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87729. var makeNotPick = function (root) {
  87730. root.name += " laserPointer";
  87731. root.getChildMeshes().forEach(function (c) {
  87732. makeNotPick(c);
  87733. });
  87734. };
  87735. makeNotPick(mesh);
  87736. var childMeshes = mesh.getChildMeshes();
  87737. this.webVRController._pointingPoseNode = null;
  87738. for (var i = 0; i < childMeshes.length; i++) {
  87739. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87740. mesh = childMeshes[i];
  87741. this.webVRController._pointingPoseNode = mesh;
  87742. break;
  87743. }
  87744. }
  87745. this._laserPointer.parent = mesh;
  87746. };
  87747. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87748. if (distance === void 0) { distance = 100; }
  87749. this._laserPointer.scaling.y = distance;
  87750. this._laserPointer.position.z = -distance / 2;
  87751. };
  87752. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87753. _super.prototype.dispose.call(this);
  87754. this._laserPointer.dispose();
  87755. if (this._meshAttachedObserver) {
  87756. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87757. }
  87758. };
  87759. return VRExperienceHelperControllerGazer;
  87760. }(VRExperienceHelperGazer));
  87761. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87762. __extends(VRExperienceHelperCameraGazer, _super);
  87763. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87764. var _this = _super.call(this, scene) || this;
  87765. _this.getCamera = getCamera;
  87766. return _this;
  87767. }
  87768. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87769. var camera = this.getCamera();
  87770. if (camera) {
  87771. return camera.getForwardRay(length);
  87772. }
  87773. else {
  87774. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87775. }
  87776. };
  87777. return VRExperienceHelperCameraGazer;
  87778. }(VRExperienceHelperGazer));
  87779. /**
  87780. * Helps to quickly add VR support to an existing scene.
  87781. * See http://doc.babylonjs.com/how_to/webvr_helper
  87782. */
  87783. var VRExperienceHelper = /** @class */ (function () {
  87784. /**
  87785. * Instantiates a VRExperienceHelper.
  87786. * Helps to quickly add VR support to an existing scene.
  87787. * @param scene The scene the VRExperienceHelper belongs to.
  87788. * @param webVROptions Options to modify the vr experience helper's behavior.
  87789. */
  87790. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87791. if (webVROptions === void 0) { webVROptions = {}; }
  87792. var _this = this;
  87793. this.webVROptions = webVROptions;
  87794. // Can the system support WebVR, even if a headset isn't plugged in?
  87795. this._webVRsupported = false;
  87796. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87797. this._webVRready = false;
  87798. // Are we waiting for the requestPresent callback to complete?
  87799. this._webVRrequesting = false;
  87800. // Are we presenting to the headset right now?
  87801. this._webVRpresenting = false;
  87802. // Are we presenting in the fullscreen fallback?
  87803. this._fullscreenVRpresenting = false;
  87804. /**
  87805. * Observable raised when entering VR.
  87806. */
  87807. this.onEnteringVRObservable = new BABYLON.Observable();
  87808. /**
  87809. * Observable raised when exiting VR.
  87810. */
  87811. this.onExitingVRObservable = new BABYLON.Observable();
  87812. /**
  87813. * Observable raised when controller mesh is loaded.
  87814. */
  87815. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87816. this._useCustomVRButton = false;
  87817. this._teleportationRequested = false;
  87818. this._teleportActive = false;
  87819. this._floorMeshesCollection = [];
  87820. this._rotationAllowed = true;
  87821. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87822. this._isDefaultTeleportationTarget = true;
  87823. this._teleportationFillColor = "#444444";
  87824. this._teleportationBorderColor = "#FFFFFF";
  87825. this._rotationAngle = 0;
  87826. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87827. this._padSensibilityUp = 0.65;
  87828. this._padSensibilityDown = 0.35;
  87829. this.leftController = null;
  87830. this.rightController = null;
  87831. /**
  87832. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87833. */
  87834. this.onNewMeshSelected = new BABYLON.Observable();
  87835. /**
  87836. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87837. */
  87838. this.onNewMeshPicked = new BABYLON.Observable();
  87839. /**
  87840. * Observable raised before camera teleportation
  87841. */
  87842. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87843. /**
  87844. * Observable raised after camera teleportation
  87845. */
  87846. this.onAfterCameraTeleport = new BABYLON.Observable();
  87847. /**
  87848. * Observable raised when current selected mesh gets unselected
  87849. */
  87850. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87851. /**
  87852. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87853. */
  87854. this.teleportationEnabled = true;
  87855. this._teleportationInitialized = false;
  87856. this._interactionsEnabled = false;
  87857. this._interactionsRequested = false;
  87858. this._displayGaze = true;
  87859. this._displayLaserPointer = true;
  87860. this._onResize = function () {
  87861. _this.moveButtonToBottomRight();
  87862. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87863. _this.exitVR();
  87864. }
  87865. };
  87866. this._onFullscreenChange = function () {
  87867. if (document.fullscreen !== undefined) {
  87868. _this._fullscreenVRpresenting = document.fullscreen;
  87869. }
  87870. else if (document.mozFullScreen !== undefined) {
  87871. _this._fullscreenVRpresenting = document.mozFullScreen;
  87872. }
  87873. else if (document.webkitIsFullScreen !== undefined) {
  87874. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87875. }
  87876. else if (document.msIsFullScreen !== undefined) {
  87877. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87878. }
  87879. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87880. _this.exitVR();
  87881. if (!_this._useCustomVRButton) {
  87882. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87883. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87884. }
  87885. }
  87886. };
  87887. this.beforeRender = function () {
  87888. if (_this.leftController && _this.leftController._activePointer) {
  87889. _this._castRayAndSelectObject(_this.leftController);
  87890. }
  87891. if (_this.rightController && _this.rightController._activePointer) {
  87892. _this._castRayAndSelectObject(_this.rightController);
  87893. }
  87894. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87895. _this._castRayAndSelectObject(_this._cameraGazer);
  87896. }
  87897. else {
  87898. _this._cameraGazer._gazeTracker.isVisible = false;
  87899. }
  87900. };
  87901. this._onNewGamepadConnected = function (gamepad) {
  87902. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87903. if (gamepad.leftStick) {
  87904. gamepad.onleftstickchanged(function (stickValues) {
  87905. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87906. // Listening to classic/xbox gamepad only if no VR controller is active
  87907. if ((!_this.leftController && !_this.rightController) ||
  87908. ((_this.leftController && !_this.leftController._activePointer) &&
  87909. (_this.rightController && !_this.rightController._activePointer))) {
  87910. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87911. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87912. }
  87913. }
  87914. });
  87915. }
  87916. if (gamepad.rightStick) {
  87917. gamepad.onrightstickchanged(function (stickValues) {
  87918. if (_this._teleportationInitialized) {
  87919. _this._checkRotate(stickValues, _this._cameraGazer);
  87920. }
  87921. });
  87922. }
  87923. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87924. gamepad.onbuttondown(function (buttonPressed) {
  87925. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87926. _this._cameraGazer._selectionPointerDown();
  87927. }
  87928. });
  87929. gamepad.onbuttonup(function (buttonPressed) {
  87930. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87931. _this._cameraGazer._selectionPointerUp();
  87932. }
  87933. });
  87934. }
  87935. }
  87936. else {
  87937. var webVRController = gamepad;
  87938. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87939. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87940. _this.rightController = controller;
  87941. }
  87942. else {
  87943. _this.leftController = controller;
  87944. }
  87945. _this._tryEnableInteractionOnController(controller);
  87946. }
  87947. };
  87948. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  87949. this._tryEnableInteractionOnController = function (controller) {
  87950. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87951. _this._enableInteractionOnController(controller);
  87952. }
  87953. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87954. _this._enableTeleportationOnController(controller);
  87955. }
  87956. };
  87957. this._onNewGamepadDisconnected = function (gamepad) {
  87958. if (gamepad instanceof BABYLON.WebVRController) {
  87959. if (gamepad.hand === "left" && _this.leftController != null) {
  87960. _this.leftController.dispose();
  87961. _this.leftController = null;
  87962. }
  87963. if (gamepad.hand === "right" && _this.rightController != null) {
  87964. _this.rightController.dispose();
  87965. _this.rightController = null;
  87966. }
  87967. }
  87968. };
  87969. this._workingVector = BABYLON.Vector3.Zero();
  87970. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87971. this._workingMatrix = BABYLON.Matrix.Identity();
  87972. this._scene = scene;
  87973. this._canvas = scene.getEngine().getRenderingCanvas();
  87974. // Parse options
  87975. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87976. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87977. }
  87978. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87979. webVROptions.createDeviceOrientationCamera = true;
  87980. }
  87981. if (webVROptions.defaultHeight === undefined) {
  87982. webVROptions.defaultHeight = 1.7;
  87983. }
  87984. if (webVROptions.useCustomVRButton) {
  87985. this._useCustomVRButton = true;
  87986. if (webVROptions.customVRButton) {
  87987. this._btnVR = webVROptions.customVRButton;
  87988. }
  87989. }
  87990. if (webVROptions.rayLength) {
  87991. this._rayLength = webVROptions.rayLength;
  87992. }
  87993. this._defaultHeight = webVROptions.defaultHeight;
  87994. if (webVROptions.positionScale) {
  87995. this._rayLength *= webVROptions.positionScale;
  87996. this._defaultHeight *= webVROptions.positionScale;
  87997. }
  87998. // Set position
  87999. if (this._scene.activeCamera) {
  88000. this._position = this._scene.activeCamera.position.clone();
  88001. }
  88002. else {
  88003. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88004. }
  88005. // Set non-vr camera
  88006. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88007. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88008. // Copy data from existing camera
  88009. if (this._scene.activeCamera) {
  88010. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88011. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88012. // Set rotation from previous camera
  88013. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88014. var targetCamera = this._scene.activeCamera;
  88015. if (targetCamera.rotationQuaternion) {
  88016. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88017. }
  88018. else {
  88019. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88020. }
  88021. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88022. }
  88023. }
  88024. this._scene.activeCamera = this._deviceOrientationCamera;
  88025. if (this._canvas) {
  88026. this._scene.activeCamera.attachControl(this._canvas);
  88027. }
  88028. }
  88029. else {
  88030. this._existingCamera = this._scene.activeCamera;
  88031. }
  88032. // Create VR cameras
  88033. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88034. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88035. }
  88036. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88037. this._webVRCamera.useStandingMatrix();
  88038. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88039. // Create default button
  88040. if (!this._useCustomVRButton) {
  88041. this._btnVR = document.createElement("BUTTON");
  88042. this._btnVR.className = "babylonVRicon";
  88043. this._btnVR.id = "babylonVRiconbtn";
  88044. this._btnVR.title = "Click to switch to VR";
  88045. var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
  88046. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88047. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88048. // css += ".babylonVRicon.vrdisplaysupported { }";
  88049. // css += ".babylonVRicon.vrdisplayready { }";
  88050. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88051. var style = document.createElement('style');
  88052. style.appendChild(document.createTextNode(css));
  88053. document.getElementsByTagName('head')[0].appendChild(style);
  88054. this.moveButtonToBottomRight();
  88055. }
  88056. // VR button click event
  88057. if (this._btnVR) {
  88058. this._btnVR.addEventListener("click", function () {
  88059. if (!_this.isInVRMode) {
  88060. _this.enterVR();
  88061. }
  88062. else {
  88063. _this.exitVR();
  88064. }
  88065. });
  88066. }
  88067. // Window events
  88068. window.addEventListener("resize", this._onResize);
  88069. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88070. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88071. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88072. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88073. // Display vr button when headset is connected
  88074. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88075. this.displayVRButton();
  88076. }
  88077. else {
  88078. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88079. if (e.vrDisplay) {
  88080. _this.displayVRButton();
  88081. }
  88082. });
  88083. }
  88084. // Exiting VR mode using 'ESC' key on desktop
  88085. this._onKeyDown = function (event) {
  88086. if (event.keyCode === 27 && _this.isInVRMode) {
  88087. _this.exitVR();
  88088. }
  88089. };
  88090. document.addEventListener("keydown", this._onKeyDown);
  88091. // Exiting VR mode double tapping the touch screen
  88092. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88093. if (_this.isInVRMode) {
  88094. _this.exitVR();
  88095. if (_this._fullscreenVRpresenting) {
  88096. _this._scene.getEngine().switchFullscreen(true);
  88097. }
  88098. }
  88099. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88100. // Listen for WebVR display changes
  88101. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88102. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88103. this._onVRRequestPresentStart = function () {
  88104. _this._webVRrequesting = true;
  88105. _this.updateButtonVisibility();
  88106. };
  88107. this._onVRRequestPresentComplete = function (success) {
  88108. _this._webVRrequesting = false;
  88109. _this.updateButtonVisibility();
  88110. };
  88111. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88112. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88113. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88114. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88115. scene.onDisposeObservable.add(function () {
  88116. _this.dispose();
  88117. });
  88118. // Gamepad connection events
  88119. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88120. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88121. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88122. this.updateButtonVisibility();
  88123. //create easing functions
  88124. this._circleEase = new BABYLON.CircleEase();
  88125. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88126. }
  88127. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88128. /** Return this.onEnteringVRObservable
  88129. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88130. */
  88131. get: function () {
  88132. return this.onEnteringVRObservable;
  88133. },
  88134. enumerable: true,
  88135. configurable: true
  88136. });
  88137. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88138. /** Return this.onExitingVRObservable
  88139. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88140. */
  88141. get: function () {
  88142. return this.onExitingVRObservable;
  88143. },
  88144. enumerable: true,
  88145. configurable: true
  88146. });
  88147. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88148. /** Return this.onControllerMeshLoadedObservable
  88149. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88150. */
  88151. get: function () {
  88152. return this.onControllerMeshLoadedObservable;
  88153. },
  88154. enumerable: true,
  88155. configurable: true
  88156. });
  88157. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88158. /**
  88159. * The mesh used to display where the user is going to teleport.
  88160. */
  88161. get: function () {
  88162. return this._teleportationTarget;
  88163. },
  88164. /**
  88165. * Sets the mesh to be used to display where the user is going to teleport.
  88166. */
  88167. set: function (value) {
  88168. if (value) {
  88169. value.name = "teleportationTarget";
  88170. this._isDefaultTeleportationTarget = false;
  88171. this._teleportationTarget = value;
  88172. }
  88173. },
  88174. enumerable: true,
  88175. configurable: true
  88176. });
  88177. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88178. /**
  88179. * The mesh used to display where the user is selecting,
  88180. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88181. * See http://doc.babylonjs.com/resources/baking_transformations
  88182. */
  88183. get: function () {
  88184. return this._cameraGazer._gazeTracker;
  88185. },
  88186. set: function (value) {
  88187. if (value) {
  88188. this._cameraGazer._gazeTracker = value;
  88189. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88190. this._cameraGazer._gazeTracker.isPickable = false;
  88191. this._cameraGazer._gazeTracker.isVisible = false;
  88192. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88193. if (this.leftController) {
  88194. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88195. }
  88196. if (this.rightController) {
  88197. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88198. }
  88199. }
  88200. },
  88201. enumerable: true,
  88202. configurable: true
  88203. });
  88204. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88205. /**
  88206. * If the ray of the gaze should be displayed.
  88207. */
  88208. get: function () {
  88209. return this._displayGaze;
  88210. },
  88211. /**
  88212. * Sets if the ray of the gaze should be displayed.
  88213. */
  88214. set: function (value) {
  88215. this._displayGaze = value;
  88216. if (!value) {
  88217. this._cameraGazer._gazeTracker.isVisible = false;
  88218. if (this.leftController) {
  88219. this.leftController._gazeTracker.isVisible = false;
  88220. }
  88221. if (this.rightController) {
  88222. this.rightController._gazeTracker.isVisible = false;
  88223. }
  88224. }
  88225. },
  88226. enumerable: true,
  88227. configurable: true
  88228. });
  88229. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88230. /**
  88231. * If the ray of the LaserPointer should be displayed.
  88232. */
  88233. get: function () {
  88234. return this._displayLaserPointer;
  88235. },
  88236. /**
  88237. * Sets if the ray of the LaserPointer should be displayed.
  88238. */
  88239. set: function (value) {
  88240. this._displayLaserPointer = value;
  88241. if (!value) {
  88242. if (this.rightController) {
  88243. this.rightController._deactivatePointer();
  88244. this.rightController._gazeTracker.isVisible = false;
  88245. }
  88246. if (this.leftController) {
  88247. this.leftController._deactivatePointer();
  88248. this.leftController._gazeTracker.isVisible = false;
  88249. }
  88250. }
  88251. else {
  88252. if (this.rightController) {
  88253. this.rightController._activatePointer();
  88254. }
  88255. if (this.leftController) {
  88256. this.leftController._activatePointer();
  88257. }
  88258. }
  88259. },
  88260. enumerable: true,
  88261. configurable: true
  88262. });
  88263. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88264. /**
  88265. * The deviceOrientationCamera used as the camera when not in VR.
  88266. */
  88267. get: function () {
  88268. return this._deviceOrientationCamera;
  88269. },
  88270. enumerable: true,
  88271. configurable: true
  88272. });
  88273. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88274. /**
  88275. * Based on the current WebVR support, returns the current VR camera used.
  88276. */
  88277. get: function () {
  88278. if (this._webVRready) {
  88279. return this._webVRCamera;
  88280. }
  88281. else {
  88282. return this._scene.activeCamera;
  88283. }
  88284. },
  88285. enumerable: true,
  88286. configurable: true
  88287. });
  88288. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88289. /**
  88290. * The webVRCamera which is used when in VR.
  88291. */
  88292. get: function () {
  88293. return this._webVRCamera;
  88294. },
  88295. enumerable: true,
  88296. configurable: true
  88297. });
  88298. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88299. /**
  88300. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88301. */
  88302. get: function () {
  88303. return this._vrDeviceOrientationCamera;
  88304. },
  88305. enumerable: true,
  88306. configurable: true
  88307. });
  88308. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88309. get: function () {
  88310. var result = this._cameraGazer._teleportationRequestInitiated
  88311. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88312. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88313. return result;
  88314. },
  88315. enumerable: true,
  88316. configurable: true
  88317. });
  88318. // Raised when one of the controller has loaded successfully its associated default mesh
  88319. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88320. if (this.leftController && this.leftController.webVRController == webVRController) {
  88321. if (webVRController.mesh) {
  88322. this.leftController._setLaserPointerParent(webVRController.mesh);
  88323. }
  88324. }
  88325. if (this.rightController && this.rightController.webVRController == webVRController) {
  88326. if (webVRController.mesh) {
  88327. this.rightController._setLaserPointerParent(webVRController.mesh);
  88328. }
  88329. }
  88330. try {
  88331. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88332. }
  88333. catch (err) {
  88334. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88335. }
  88336. };
  88337. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88338. /**
  88339. * Gets a value indicating if we are currently in VR mode.
  88340. */
  88341. get: function () {
  88342. return this._webVRpresenting || this._fullscreenVRpresenting;
  88343. },
  88344. enumerable: true,
  88345. configurable: true
  88346. });
  88347. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88348. var vrDisplay = this._scene.getEngine().getVRDevice();
  88349. if (vrDisplay) {
  88350. var wasPresenting = this._webVRpresenting;
  88351. // A VR display is connected
  88352. this._webVRpresenting = vrDisplay.isPresenting;
  88353. if (wasPresenting && !this._webVRpresenting)
  88354. this.exitVR();
  88355. }
  88356. else {
  88357. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88358. }
  88359. this.updateButtonVisibility();
  88360. };
  88361. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88362. this._webVRsupported = eventArgs.vrSupported;
  88363. this._webVRready = !!eventArgs.vrDisplay;
  88364. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88365. this.updateButtonVisibility();
  88366. };
  88367. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88368. if (this._canvas && !this._useCustomVRButton) {
  88369. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88370. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88371. }
  88372. };
  88373. VRExperienceHelper.prototype.displayVRButton = function () {
  88374. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88375. document.body.appendChild(this._btnVR);
  88376. this._btnVRDisplayed = true;
  88377. }
  88378. };
  88379. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88380. if (!this._btnVR || this._useCustomVRButton) {
  88381. return;
  88382. }
  88383. this._btnVR.className = "babylonVRicon";
  88384. if (this.isInVRMode) {
  88385. this._btnVR.className += " vrdisplaypresenting";
  88386. }
  88387. else {
  88388. if (this._webVRready)
  88389. this._btnVR.className += " vrdisplayready";
  88390. if (this._webVRsupported)
  88391. this._btnVR.className += " vrdisplaysupported";
  88392. if (this._webVRrequesting)
  88393. this._btnVR.className += " vrdisplayrequesting";
  88394. }
  88395. };
  88396. /**
  88397. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88398. * Otherwise, will use the fullscreen API.
  88399. */
  88400. VRExperienceHelper.prototype.enterVR = function () {
  88401. if (this.onEnteringVRObservable) {
  88402. try {
  88403. this.onEnteringVRObservable.notifyObservers(this);
  88404. }
  88405. catch (err) {
  88406. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88407. }
  88408. }
  88409. if (this._scene.activeCamera) {
  88410. this._position = this._scene.activeCamera.position.clone();
  88411. // make sure that we return to the last active camera
  88412. this._existingCamera = this._scene.activeCamera;
  88413. }
  88414. if (this._webVRrequesting)
  88415. return;
  88416. // If WebVR is supported and a headset is connected
  88417. if (this._webVRready) {
  88418. if (!this._webVRpresenting) {
  88419. this._webVRCamera.position = this._position;
  88420. this._scene.activeCamera = this._webVRCamera;
  88421. }
  88422. }
  88423. else if (this._vrDeviceOrientationCamera) {
  88424. this._vrDeviceOrientationCamera.position = this._position;
  88425. if (this._scene.activeCamera) {
  88426. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88427. }
  88428. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88429. this._scene.getEngine().switchFullscreen(true);
  88430. this.updateButtonVisibility();
  88431. }
  88432. if (this._scene.activeCamera && this._canvas) {
  88433. this._scene.activeCamera.attachControl(this._canvas);
  88434. }
  88435. if (this._interactionsEnabled) {
  88436. this._scene.registerBeforeRender(this.beforeRender);
  88437. }
  88438. };
  88439. /**
  88440. * Attempt to exit VR, or fullscreen.
  88441. */
  88442. VRExperienceHelper.prototype.exitVR = function () {
  88443. if (this.onExitingVRObservable) {
  88444. try {
  88445. this.onExitingVRObservable.notifyObservers(this);
  88446. }
  88447. catch (err) {
  88448. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88449. }
  88450. }
  88451. if (this._webVRpresenting) {
  88452. this._scene.getEngine().disableVR();
  88453. }
  88454. if (this._scene.activeCamera) {
  88455. this._position = this._scene.activeCamera.position.clone();
  88456. }
  88457. if (this._deviceOrientationCamera) {
  88458. this._deviceOrientationCamera.position = this._position;
  88459. this._scene.activeCamera = this._deviceOrientationCamera;
  88460. if (this._canvas) {
  88461. this._scene.activeCamera.attachControl(this._canvas);
  88462. }
  88463. }
  88464. else if (this._existingCamera) {
  88465. this._existingCamera.position = this._position;
  88466. this._scene.activeCamera = this._existingCamera;
  88467. }
  88468. this.updateButtonVisibility();
  88469. if (this._interactionsEnabled) {
  88470. this._scene.unregisterBeforeRender(this.beforeRender);
  88471. }
  88472. // resize to update width and height when exiting vr exits fullscreen
  88473. this._scene.getEngine().resize();
  88474. };
  88475. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88476. /**
  88477. * The position of the vr experience helper.
  88478. */
  88479. get: function () {
  88480. return this._position;
  88481. },
  88482. /**
  88483. * Sets the position of the vr experience helper.
  88484. */
  88485. set: function (value) {
  88486. this._position = value;
  88487. if (this._scene.activeCamera) {
  88488. this._scene.activeCamera.position = value;
  88489. }
  88490. },
  88491. enumerable: true,
  88492. configurable: true
  88493. });
  88494. /**
  88495. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88496. */
  88497. VRExperienceHelper.prototype.enableInteractions = function () {
  88498. var _this = this;
  88499. if (!this._interactionsEnabled) {
  88500. this._interactionsRequested = true;
  88501. if (this.leftController) {
  88502. this._enableInteractionOnController(this.leftController);
  88503. }
  88504. if (this.rightController) {
  88505. this._enableInteractionOnController(this.rightController);
  88506. }
  88507. this.raySelectionPredicate = function (mesh) {
  88508. return mesh.isVisible;
  88509. };
  88510. this.meshSelectionPredicate = function (mesh) {
  88511. return true;
  88512. };
  88513. this._raySelectionPredicate = function (mesh) {
  88514. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88515. && mesh.name.indexOf("teleportationTarget") === -1
  88516. && mesh.name.indexOf("torusTeleportation") === -1
  88517. && mesh.name.indexOf("laserPointer") === -1)) {
  88518. return _this.raySelectionPredicate(mesh);
  88519. }
  88520. return false;
  88521. };
  88522. this._interactionsEnabled = true;
  88523. }
  88524. };
  88525. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88526. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88527. if (this._floorMeshesCollection[i].id === mesh.id) {
  88528. return true;
  88529. }
  88530. }
  88531. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88532. return true;
  88533. }
  88534. return false;
  88535. };
  88536. /**
  88537. * Adds a floor mesh to be used for teleportation.
  88538. * @param floorMesh the mesh to be used for teleportation.
  88539. */
  88540. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88541. if (!this._floorMeshesCollection) {
  88542. return;
  88543. }
  88544. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88545. return;
  88546. }
  88547. this._floorMeshesCollection.push(floorMesh);
  88548. };
  88549. /**
  88550. * Removes a floor mesh from being used for teleportation.
  88551. * @param floorMesh the mesh to be removed.
  88552. */
  88553. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88554. if (!this._floorMeshesCollection) {
  88555. return;
  88556. }
  88557. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88558. if (meshIndex !== -1) {
  88559. this._floorMeshesCollection.splice(meshIndex, 1);
  88560. }
  88561. };
  88562. /**
  88563. * Enables interactions and teleportation using the VR controllers and gaze.
  88564. * @param vrTeleportationOptions options to modify teleportation behavior.
  88565. */
  88566. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88567. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88568. if (!this._teleportationInitialized) {
  88569. this._teleportationRequested = true;
  88570. this.enableInteractions();
  88571. if (vrTeleportationOptions.floorMeshName) {
  88572. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88573. }
  88574. if (vrTeleportationOptions.floorMeshes) {
  88575. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88576. }
  88577. if (this.leftController != null) {
  88578. this._enableTeleportationOnController(this.leftController);
  88579. }
  88580. if (this.rightController != null) {
  88581. this._enableTeleportationOnController(this.rightController);
  88582. }
  88583. // Creates an image processing post process for the vignette not relying
  88584. // on the main scene configuration for image processing to reduce setup and spaces
  88585. // (gamma/linear) conflicts.
  88586. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88587. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88588. imageProcessingConfiguration.vignetteEnabled = true;
  88589. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88590. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88591. this._teleportationInitialized = true;
  88592. if (this._isDefaultTeleportationTarget) {
  88593. this._createTeleportationCircles();
  88594. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88595. }
  88596. }
  88597. };
  88598. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88599. var _this = this;
  88600. var controllerMesh = controller.webVRController.mesh;
  88601. if (controllerMesh) {
  88602. controller._interactionsEnabled = true;
  88603. controller._activatePointer();
  88604. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88605. // Enabling / disabling laserPointer
  88606. if (_this._displayLaserPointer && stateObject.value === 1) {
  88607. if (controller._activePointer) {
  88608. controller._deactivatePointer();
  88609. }
  88610. else {
  88611. controller._activatePointer();
  88612. }
  88613. if (_this.displayGaze) {
  88614. controller._gazeTracker.isVisible = controller._activePointer;
  88615. }
  88616. }
  88617. });
  88618. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88619. if (!controller._pointerDownOnMeshAsked) {
  88620. if (stateObject.value > _this._padSensibilityUp) {
  88621. controller._selectionPointerDown();
  88622. }
  88623. }
  88624. else if (stateObject.value < _this._padSensibilityDown) {
  88625. controller._selectionPointerUp();
  88626. }
  88627. });
  88628. }
  88629. };
  88630. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88631. // Dont teleport if another gaze already requested teleportation
  88632. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88633. return;
  88634. }
  88635. if (!gazer._teleportationRequestInitiated) {
  88636. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88637. gazer._activatePointer();
  88638. gazer._teleportationRequestInitiated = true;
  88639. }
  88640. }
  88641. else {
  88642. // Listening to the proper controller values changes to confirm teleportation
  88643. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88644. if (this._teleportActive) {
  88645. this._teleportCamera(this._haloCenter);
  88646. }
  88647. gazer._teleportationRequestInitiated = false;
  88648. }
  88649. }
  88650. };
  88651. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88652. // Only rotate when user is not currently selecting a teleportation location
  88653. if (gazer._teleportationRequestInitiated) {
  88654. return;
  88655. }
  88656. if (!gazer._rotationLeftAsked) {
  88657. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88658. gazer._rotationLeftAsked = true;
  88659. if (this._rotationAllowed) {
  88660. this._rotateCamera(false);
  88661. }
  88662. }
  88663. }
  88664. else {
  88665. if (stateObject.x > -this._padSensibilityDown) {
  88666. gazer._rotationLeftAsked = false;
  88667. }
  88668. }
  88669. if (!gazer._rotationRightAsked) {
  88670. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88671. gazer._rotationRightAsked = true;
  88672. if (this._rotationAllowed) {
  88673. this._rotateCamera(true);
  88674. }
  88675. }
  88676. }
  88677. else {
  88678. if (stateObject.x < this._padSensibilityDown) {
  88679. gazer._rotationRightAsked = false;
  88680. }
  88681. }
  88682. };
  88683. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88684. // Only teleport backwards when user is not currently selecting a teleportation location
  88685. if (gazer._teleportationRequestInitiated) {
  88686. return;
  88687. }
  88688. // Teleport backwards
  88689. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88690. if (!gazer._teleportationBackRequestInitiated) {
  88691. if (!this.currentVRCamera) {
  88692. return;
  88693. }
  88694. // Get rotation and position of the current camera
  88695. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88696. var position = this.currentVRCamera.position;
  88697. // If the camera has device position, use that instead
  88698. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88699. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88700. position = this.currentVRCamera.devicePosition;
  88701. }
  88702. // Get matrix with only the y rotation of the device rotation
  88703. rotation.toEulerAnglesToRef(this._workingVector);
  88704. this._workingVector.z = 0;
  88705. this._workingVector.x = 0;
  88706. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88707. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88708. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88709. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88710. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88711. var ray = new BABYLON.Ray(position, this._workingVector);
  88712. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88713. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88714. this._teleportCamera(hit.pickedPoint);
  88715. }
  88716. gazer._teleportationBackRequestInitiated = true;
  88717. }
  88718. }
  88719. else {
  88720. gazer._teleportationBackRequestInitiated = false;
  88721. }
  88722. };
  88723. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88724. var _this = this;
  88725. var controllerMesh = controller.webVRController.mesh;
  88726. if (controllerMesh) {
  88727. if (!controller._interactionsEnabled) {
  88728. this._enableInteractionOnController(controller);
  88729. }
  88730. controller._interactionsEnabled = true;
  88731. controller._teleportationEnabled = true;
  88732. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88733. controller._dpadPressed = false;
  88734. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88735. controller._dpadPressed = stateObject.pressed;
  88736. if (!controller._dpadPressed) {
  88737. controller._rotationLeftAsked = false;
  88738. controller._rotationRightAsked = false;
  88739. controller._teleportationBackRequestInitiated = false;
  88740. }
  88741. });
  88742. }
  88743. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88744. if (_this.teleportationEnabled) {
  88745. _this._checkTeleportBackwards(stateObject, controller);
  88746. _this._checkTeleportWithRay(stateObject, controller);
  88747. }
  88748. _this._checkRotate(stateObject, controller);
  88749. });
  88750. }
  88751. };
  88752. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88753. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88754. this._teleportationTarget.isPickable = false;
  88755. var length = 512;
  88756. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88757. dynamicTexture.hasAlpha = true;
  88758. var context = dynamicTexture.getContext();
  88759. var centerX = length / 2;
  88760. var centerY = length / 2;
  88761. var radius = 200;
  88762. context.beginPath();
  88763. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88764. context.fillStyle = this._teleportationFillColor;
  88765. context.fill();
  88766. context.lineWidth = 10;
  88767. context.strokeStyle = this._teleportationBorderColor;
  88768. context.stroke();
  88769. context.closePath();
  88770. dynamicTexture.update();
  88771. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88772. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88773. this._teleportationTarget.material = teleportationCircleMaterial;
  88774. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88775. torus.isPickable = false;
  88776. torus.parent = this._teleportationTarget;
  88777. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88778. var keys = [];
  88779. keys.push({
  88780. frame: 0,
  88781. value: 0
  88782. });
  88783. keys.push({
  88784. frame: 30,
  88785. value: 0.4
  88786. });
  88787. keys.push({
  88788. frame: 60,
  88789. value: 0
  88790. });
  88791. animationInnerCircle.setKeys(keys);
  88792. var easingFunction = new BABYLON.SineEase();
  88793. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88794. animationInnerCircle.setEasingFunction(easingFunction);
  88795. torus.animations = [];
  88796. torus.animations.push(animationInnerCircle);
  88797. this._scene.beginAnimation(torus, 0, 60, true);
  88798. this._hideTeleportationTarget();
  88799. };
  88800. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88801. this._teleportActive = true;
  88802. if (this._teleportationInitialized) {
  88803. this._teleportationTarget.isVisible = true;
  88804. if (this._isDefaultTeleportationTarget) {
  88805. this._teleportationTarget.getChildren()[0].isVisible = true;
  88806. }
  88807. }
  88808. };
  88809. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88810. this._teleportActive = false;
  88811. if (this._teleportationInitialized) {
  88812. this._teleportationTarget.isVisible = false;
  88813. if (this._isDefaultTeleportationTarget) {
  88814. this._teleportationTarget.getChildren()[0].isVisible = false;
  88815. }
  88816. }
  88817. };
  88818. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88819. var _this = this;
  88820. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88821. return;
  88822. }
  88823. if (right) {
  88824. this._rotationAngle++;
  88825. }
  88826. else {
  88827. this._rotationAngle--;
  88828. }
  88829. this.currentVRCamera.animations = [];
  88830. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88831. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88832. var animationRotationKeys = [];
  88833. animationRotationKeys.push({
  88834. frame: 0,
  88835. value: this.currentVRCamera.rotationQuaternion
  88836. });
  88837. animationRotationKeys.push({
  88838. frame: 6,
  88839. value: target
  88840. });
  88841. animationRotation.setKeys(animationRotationKeys);
  88842. animationRotation.setEasingFunction(this._circleEase);
  88843. this.currentVRCamera.animations.push(animationRotation);
  88844. this._postProcessMove.animations = [];
  88845. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88846. var vignetteWeightKeys = [];
  88847. vignetteWeightKeys.push({
  88848. frame: 0,
  88849. value: 0
  88850. });
  88851. vignetteWeightKeys.push({
  88852. frame: 3,
  88853. value: 4
  88854. });
  88855. vignetteWeightKeys.push({
  88856. frame: 6,
  88857. value: 0
  88858. });
  88859. animationPP.setKeys(vignetteWeightKeys);
  88860. animationPP.setEasingFunction(this._circleEase);
  88861. this._postProcessMove.animations.push(animationPP);
  88862. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88863. var vignetteStretchKeys = [];
  88864. vignetteStretchKeys.push({
  88865. frame: 0,
  88866. value: 0
  88867. });
  88868. vignetteStretchKeys.push({
  88869. frame: 3,
  88870. value: 10
  88871. });
  88872. vignetteStretchKeys.push({
  88873. frame: 6,
  88874. value: 0
  88875. });
  88876. animationPP2.setKeys(vignetteStretchKeys);
  88877. animationPP2.setEasingFunction(this._circleEase);
  88878. this._postProcessMove.animations.push(animationPP2);
  88879. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88880. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88881. this._postProcessMove.samples = 4;
  88882. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88883. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88884. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88885. });
  88886. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88887. };
  88888. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88889. if (hit.pickedPoint) {
  88890. if (gazer._teleportationRequestInitiated) {
  88891. this._displayTeleportationTarget();
  88892. this._haloCenter.copyFrom(hit.pickedPoint);
  88893. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88894. }
  88895. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88896. if (pickNormal) {
  88897. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88898. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88899. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88900. }
  88901. this._teleportationTarget.position.y += 0.1;
  88902. }
  88903. };
  88904. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88905. var _this = this;
  88906. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88907. return;
  88908. }
  88909. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88910. // offset of the headset from the anchor.
  88911. if (this.webVRCamera.leftCamera) {
  88912. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88913. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88914. location.subtractToRef(this._workingVector, this._workingVector);
  88915. }
  88916. else {
  88917. this._workingVector.copyFrom(location);
  88918. }
  88919. // Add height to account for user's height offset
  88920. if (this.isInVRMode) {
  88921. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88922. }
  88923. else {
  88924. this._workingVector.y += this._defaultHeight;
  88925. }
  88926. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88927. // Create animation from the camera's position to the new location
  88928. this.currentVRCamera.animations = [];
  88929. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88930. var animationCameraTeleportationKeys = [{
  88931. frame: 0,
  88932. value: this.currentVRCamera.position
  88933. },
  88934. {
  88935. frame: 11,
  88936. value: this._workingVector
  88937. }
  88938. ];
  88939. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88940. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88941. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88942. this._postProcessMove.animations = [];
  88943. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88944. var vignetteWeightKeys = [];
  88945. vignetteWeightKeys.push({
  88946. frame: 0,
  88947. value: 0
  88948. });
  88949. vignetteWeightKeys.push({
  88950. frame: 5,
  88951. value: 8
  88952. });
  88953. vignetteWeightKeys.push({
  88954. frame: 11,
  88955. value: 0
  88956. });
  88957. animationPP.setKeys(vignetteWeightKeys);
  88958. this._postProcessMove.animations.push(animationPP);
  88959. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88960. var vignetteStretchKeys = [];
  88961. vignetteStretchKeys.push({
  88962. frame: 0,
  88963. value: 0
  88964. });
  88965. vignetteStretchKeys.push({
  88966. frame: 5,
  88967. value: 10
  88968. });
  88969. vignetteStretchKeys.push({
  88970. frame: 11,
  88971. value: 0
  88972. });
  88973. animationPP2.setKeys(vignetteStretchKeys);
  88974. this._postProcessMove.animations.push(animationPP2);
  88975. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88976. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88977. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88978. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88979. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88980. });
  88981. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88982. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88983. });
  88984. this._hideTeleportationTarget();
  88985. };
  88986. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88987. if (normal) {
  88988. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88989. if (angle < Math.PI / 2) {
  88990. normal.scaleInPlace(-1);
  88991. }
  88992. }
  88993. return normal;
  88994. };
  88995. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88996. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88997. return;
  88998. }
  88999. var ray = gazer._getForwardRay(this._rayLength);
  89000. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89001. // Moving the gazeTracker on the mesh face targetted
  89002. if (hit && hit.pickedPoint) {
  89003. if (this._displayGaze) {
  89004. var multiplier = 1;
  89005. gazer._gazeTracker.isVisible = true;
  89006. if (gazer._isActionableMesh) {
  89007. multiplier = 3;
  89008. }
  89009. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89010. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89011. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89012. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89013. // To avoid z-fighting
  89014. var deltaFighting = 0.002;
  89015. if (pickNormal) {
  89016. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89017. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89018. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89019. }
  89020. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89021. if (gazer._gazeTracker.position.x < 0) {
  89022. gazer._gazeTracker.position.x += deltaFighting;
  89023. }
  89024. else {
  89025. gazer._gazeTracker.position.x -= deltaFighting;
  89026. }
  89027. if (gazer._gazeTracker.position.y < 0) {
  89028. gazer._gazeTracker.position.y += deltaFighting;
  89029. }
  89030. else {
  89031. gazer._gazeTracker.position.y -= deltaFighting;
  89032. }
  89033. if (gazer._gazeTracker.position.z < 0) {
  89034. gazer._gazeTracker.position.z += deltaFighting;
  89035. }
  89036. else {
  89037. gazer._gazeTracker.position.z -= deltaFighting;
  89038. }
  89039. }
  89040. // Changing the size of the laser pointer based on the distance from the targetted point
  89041. gazer._updatePointerDistance(hit.distance);
  89042. }
  89043. else {
  89044. gazer._updatePointerDistance();
  89045. gazer._gazeTracker.isVisible = false;
  89046. }
  89047. if (hit && hit.pickedMesh) {
  89048. gazer._currentHit = hit;
  89049. if (gazer._pointerDownOnMeshAsked) {
  89050. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  89051. }
  89052. // The object selected is the floor, we're in a teleportation scenario
  89053. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89054. // Moving the teleportation area to this targetted point
  89055. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89056. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89057. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89058. }
  89059. gazer._currentMeshSelected = null;
  89060. if (gazer._teleportationRequestInitiated) {
  89061. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89062. }
  89063. return;
  89064. }
  89065. // If not, we're in a selection scenario
  89066. //this._teleportationAllowed = false;
  89067. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89068. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89069. this.onNewMeshPicked.notifyObservers(hit);
  89070. gazer._currentMeshSelected = hit.pickedMesh;
  89071. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89072. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89073. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89074. gazer._isActionableMesh = true;
  89075. }
  89076. else {
  89077. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89078. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89079. gazer._isActionableMesh = false;
  89080. }
  89081. try {
  89082. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89083. }
  89084. catch (err) {
  89085. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89086. }
  89087. }
  89088. else {
  89089. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89090. gazer._currentMeshSelected = null;
  89091. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89092. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89093. }
  89094. }
  89095. }
  89096. else {
  89097. gazer._currentHit = null;
  89098. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89099. gazer._currentMeshSelected = null;
  89100. //this._teleportationAllowed = false;
  89101. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89102. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89103. }
  89104. };
  89105. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89106. if (mesh) {
  89107. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89108. }
  89109. };
  89110. /**
  89111. * Sets the color of the laser ray from the vr controllers.
  89112. * @param color new color for the ray.
  89113. */
  89114. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89115. if (this.leftController) {
  89116. this.leftController._setLaserPointerColor(color);
  89117. }
  89118. if (this.rightController) {
  89119. this.rightController._setLaserPointerColor(color);
  89120. }
  89121. };
  89122. /**
  89123. * Sets the color of the ray from the vr headsets gaze.
  89124. * @param color new color for the ray.
  89125. */
  89126. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89127. if (!this._cameraGazer._gazeTracker.material) {
  89128. return;
  89129. }
  89130. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89131. if (this.leftController) {
  89132. this.leftController._gazeTracker.material.emissiveColor = color;
  89133. }
  89134. if (this.rightController) {
  89135. this.rightController._gazeTracker.material.emissiveColor = color;
  89136. }
  89137. };
  89138. /**
  89139. * Exits VR and disposes of the vr experience helper
  89140. */
  89141. VRExperienceHelper.prototype.dispose = function () {
  89142. if (this.isInVRMode) {
  89143. this.exitVR();
  89144. }
  89145. if (this._postProcessMove) {
  89146. this._postProcessMove.dispose();
  89147. }
  89148. if (this._webVRCamera) {
  89149. this._webVRCamera.dispose();
  89150. }
  89151. if (this._vrDeviceOrientationCamera) {
  89152. this._vrDeviceOrientationCamera.dispose();
  89153. }
  89154. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89155. document.body.removeChild(this._btnVR);
  89156. }
  89157. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89158. this._deviceOrientationCamera.dispose();
  89159. }
  89160. if (this._cameraGazer) {
  89161. this._cameraGazer.dispose();
  89162. }
  89163. if (this.leftController) {
  89164. this.leftController.dispose();
  89165. }
  89166. if (this.rightController) {
  89167. this.rightController.dispose();
  89168. }
  89169. if (this._teleportationTarget) {
  89170. this._teleportationTarget.dispose();
  89171. }
  89172. this._floorMeshesCollection = [];
  89173. document.removeEventListener("keydown", this._onKeyDown);
  89174. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89175. window.removeEventListener("resize", this._onResize);
  89176. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89177. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89178. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89179. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89180. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89181. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89182. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89183. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89184. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89185. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89186. this._scene.unregisterBeforeRender(this.beforeRender);
  89187. };
  89188. /**
  89189. * Gets the name of the VRExperienceHelper class
  89190. * @returns "VRExperienceHelper"
  89191. */
  89192. VRExperienceHelper.prototype.getClassName = function () {
  89193. return "VRExperienceHelper";
  89194. };
  89195. return VRExperienceHelper;
  89196. }());
  89197. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89198. })(BABYLON || (BABYLON = {}));
  89199. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89200. // Mainly based on these 2 articles :
  89201. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  89202. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89203. var BABYLON;
  89204. (function (BABYLON) {
  89205. /**
  89206. * Defines the potential axis of a Joystick
  89207. */
  89208. var JoystickAxis;
  89209. (function (JoystickAxis) {
  89210. /** X axis */
  89211. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89212. /** Y axis */
  89213. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89214. /** Z axis */
  89215. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89216. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89217. /**
  89218. * Class used to define virtual joystick (used in touch mode)
  89219. */
  89220. var VirtualJoystick = /** @class */ (function () {
  89221. /**
  89222. * Creates a new virtual joystick
  89223. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89224. */
  89225. function VirtualJoystick(leftJoystick) {
  89226. var _this = this;
  89227. if (leftJoystick) {
  89228. this._leftJoystick = true;
  89229. }
  89230. else {
  89231. this._leftJoystick = false;
  89232. }
  89233. VirtualJoystick._globalJoystickIndex++;
  89234. // By default left & right arrow keys are moving the X
  89235. // and up & down keys are moving the Y
  89236. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89237. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89238. this.reverseLeftRight = false;
  89239. this.reverseUpDown = false;
  89240. // collections of pointers
  89241. this._touches = new BABYLON.StringDictionary();
  89242. this.deltaPosition = BABYLON.Vector3.Zero();
  89243. this._joystickSensibility = 25;
  89244. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89245. this._onResize = function (evt) {
  89246. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89247. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89248. if (VirtualJoystick.vjCanvas) {
  89249. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89250. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89251. }
  89252. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89253. };
  89254. // injecting a canvas element on top of the canvas 3D game
  89255. if (!VirtualJoystick.vjCanvas) {
  89256. window.addEventListener("resize", this._onResize, false);
  89257. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89258. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89259. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89260. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89261. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89262. VirtualJoystick.vjCanvas.style.width = "100%";
  89263. VirtualJoystick.vjCanvas.style.height = "100%";
  89264. VirtualJoystick.vjCanvas.style.position = "absolute";
  89265. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89266. VirtualJoystick.vjCanvas.style.top = "0px";
  89267. VirtualJoystick.vjCanvas.style.left = "0px";
  89268. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89269. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89270. // Support for jQuery PEP polyfill
  89271. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89272. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89273. if (!context) {
  89274. throw new Error("Unable to create canvas for virtual joystick");
  89275. }
  89276. VirtualJoystick.vjCanvasContext = context;
  89277. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89278. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89279. document.body.appendChild(VirtualJoystick.vjCanvas);
  89280. }
  89281. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89282. this.pressed = false;
  89283. // default joystick color
  89284. this._joystickColor = "cyan";
  89285. this._joystickPointerID = -1;
  89286. // current joystick position
  89287. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89288. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89289. // origin joystick position
  89290. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89291. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89292. this._onPointerDownHandlerRef = function (evt) {
  89293. _this._onPointerDown(evt);
  89294. };
  89295. this._onPointerMoveHandlerRef = function (evt) {
  89296. _this._onPointerMove(evt);
  89297. };
  89298. this._onPointerUpHandlerRef = function (evt) {
  89299. _this._onPointerUp(evt);
  89300. };
  89301. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89302. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89303. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89304. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89305. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89306. evt.preventDefault(); // Disables system menu
  89307. }, false);
  89308. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89309. }
  89310. /**
  89311. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89312. * @param newJoystickSensibility defines the new sensibility
  89313. */
  89314. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89315. this._joystickSensibility = newJoystickSensibility;
  89316. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89317. };
  89318. VirtualJoystick.prototype._onPointerDown = function (e) {
  89319. var positionOnScreenCondition;
  89320. e.preventDefault();
  89321. if (this._leftJoystick === true) {
  89322. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89323. }
  89324. else {
  89325. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89326. }
  89327. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89328. // First contact will be dedicated to the virtual joystick
  89329. this._joystickPointerID = e.pointerId;
  89330. this._joystickPointerStartPos.x = e.clientX;
  89331. this._joystickPointerStartPos.y = e.clientY;
  89332. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89333. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89334. this._deltaJoystickVector.x = 0;
  89335. this._deltaJoystickVector.y = 0;
  89336. this.pressed = true;
  89337. this._touches.add(e.pointerId.toString(), e);
  89338. }
  89339. else {
  89340. // You can only trigger the action buttons with a joystick declared
  89341. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89342. this._action();
  89343. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89344. }
  89345. }
  89346. };
  89347. VirtualJoystick.prototype._onPointerMove = function (e) {
  89348. // If the current pointer is the one associated to the joystick (first touch contact)
  89349. if (this._joystickPointerID == e.pointerId) {
  89350. this._joystickPointerPos.x = e.clientX;
  89351. this._joystickPointerPos.y = e.clientY;
  89352. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89353. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89354. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89355. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89356. switch (this._axisTargetedByLeftAndRight) {
  89357. case JoystickAxis.X:
  89358. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89359. break;
  89360. case JoystickAxis.Y:
  89361. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89362. break;
  89363. case JoystickAxis.Z:
  89364. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89365. break;
  89366. }
  89367. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89368. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89369. switch (this._axisTargetedByUpAndDown) {
  89370. case JoystickAxis.X:
  89371. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89372. break;
  89373. case JoystickAxis.Y:
  89374. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89375. break;
  89376. case JoystickAxis.Z:
  89377. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89378. break;
  89379. }
  89380. }
  89381. else {
  89382. var data = this._touches.get(e.pointerId.toString());
  89383. if (data) {
  89384. data.x = e.clientX;
  89385. data.y = e.clientY;
  89386. }
  89387. }
  89388. };
  89389. VirtualJoystick.prototype._onPointerUp = function (e) {
  89390. if (this._joystickPointerID == e.pointerId) {
  89391. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89392. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89393. this._joystickPointerID = -1;
  89394. this.pressed = false;
  89395. }
  89396. else {
  89397. var touch = this._touches.get(e.pointerId.toString());
  89398. if (touch) {
  89399. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89400. }
  89401. }
  89402. this._deltaJoystickVector.x = 0;
  89403. this._deltaJoystickVector.y = 0;
  89404. this._touches.remove(e.pointerId.toString());
  89405. };
  89406. /**
  89407. * Change the color of the virtual joystick
  89408. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89409. */
  89410. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89411. this._joystickColor = newColor;
  89412. };
  89413. /**
  89414. * Defines a callback to call when the joystick is touched
  89415. * @param action defines the callback
  89416. */
  89417. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89418. this._action = action;
  89419. };
  89420. /**
  89421. * Defines which axis you'd like to control for left & right
  89422. * @param axis defines the axis to use
  89423. */
  89424. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89425. switch (axis) {
  89426. case JoystickAxis.X:
  89427. case JoystickAxis.Y:
  89428. case JoystickAxis.Z:
  89429. this._axisTargetedByLeftAndRight = axis;
  89430. break;
  89431. default:
  89432. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89433. break;
  89434. }
  89435. };
  89436. /**
  89437. * Defines which axis you'd like to control for up & down
  89438. * @param axis defines the axis to use
  89439. */
  89440. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89441. switch (axis) {
  89442. case JoystickAxis.X:
  89443. case JoystickAxis.Y:
  89444. case JoystickAxis.Z:
  89445. this._axisTargetedByUpAndDown = axis;
  89446. break;
  89447. default:
  89448. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89449. break;
  89450. }
  89451. };
  89452. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89453. var _this = this;
  89454. if (this.pressed) {
  89455. this._touches.forEach(function (key, touch) {
  89456. if (touch.pointerId === _this._joystickPointerID) {
  89457. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89458. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89459. VirtualJoystick.vjCanvasContext.beginPath();
  89460. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89461. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89462. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89463. VirtualJoystick.vjCanvasContext.stroke();
  89464. VirtualJoystick.vjCanvasContext.closePath();
  89465. VirtualJoystick.vjCanvasContext.beginPath();
  89466. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89467. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89468. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89469. VirtualJoystick.vjCanvasContext.stroke();
  89470. VirtualJoystick.vjCanvasContext.closePath();
  89471. VirtualJoystick.vjCanvasContext.beginPath();
  89472. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89473. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89474. VirtualJoystick.vjCanvasContext.stroke();
  89475. VirtualJoystick.vjCanvasContext.closePath();
  89476. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89477. }
  89478. else {
  89479. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89480. VirtualJoystick.vjCanvasContext.beginPath();
  89481. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89482. VirtualJoystick.vjCanvasContext.beginPath();
  89483. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89484. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89485. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89486. VirtualJoystick.vjCanvasContext.stroke();
  89487. VirtualJoystick.vjCanvasContext.closePath();
  89488. touch.prevX = touch.x;
  89489. touch.prevY = touch.y;
  89490. }
  89491. ;
  89492. });
  89493. }
  89494. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89495. };
  89496. /**
  89497. * Release internal HTML canvas
  89498. */
  89499. VirtualJoystick.prototype.releaseCanvas = function () {
  89500. if (VirtualJoystick.vjCanvas) {
  89501. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89502. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89503. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89504. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89505. window.removeEventListener("resize", this._onResize);
  89506. document.body.removeChild(VirtualJoystick.vjCanvas);
  89507. VirtualJoystick.vjCanvas = null;
  89508. }
  89509. };
  89510. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89511. VirtualJoystick._globalJoystickIndex = 0;
  89512. return VirtualJoystick;
  89513. }());
  89514. BABYLON.VirtualJoystick = VirtualJoystick;
  89515. })(BABYLON || (BABYLON = {}));
  89516. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89517. var BABYLON;
  89518. (function (BABYLON) {
  89519. // We're mainly based on the logic defined into the FreeCamera code
  89520. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89521. __extends(VirtualJoysticksCamera, _super);
  89522. function VirtualJoysticksCamera(name, position, scene) {
  89523. var _this = _super.call(this, name, position, scene) || this;
  89524. _this.inputs.addVirtualJoystick();
  89525. return _this;
  89526. }
  89527. VirtualJoysticksCamera.prototype.getClassName = function () {
  89528. return "VirtualJoysticksCamera";
  89529. };
  89530. return VirtualJoysticksCamera;
  89531. }(BABYLON.FreeCamera));
  89532. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89533. })(BABYLON || (BABYLON = {}));
  89534. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89535. var BABYLON;
  89536. (function (BABYLON) {
  89537. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89538. function FreeCameraVirtualJoystickInput() {
  89539. }
  89540. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89541. return this._leftjoystick;
  89542. };
  89543. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89544. return this._rightjoystick;
  89545. };
  89546. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89547. if (this._leftjoystick) {
  89548. var camera = this.camera;
  89549. var speed = camera._computeLocalCameraSpeed() * 50;
  89550. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89551. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89552. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89553. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89554. if (!this._leftjoystick.pressed) {
  89555. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89556. }
  89557. if (!this._rightjoystick.pressed) {
  89558. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89559. }
  89560. }
  89561. };
  89562. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89563. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89564. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89565. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89566. this._leftjoystick.setJoystickSensibility(0.15);
  89567. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89568. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89569. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89570. this._rightjoystick.reverseUpDown = true;
  89571. this._rightjoystick.setJoystickSensibility(0.05);
  89572. this._rightjoystick.setJoystickColor("yellow");
  89573. };
  89574. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89575. this._leftjoystick.releaseCanvas();
  89576. this._rightjoystick.releaseCanvas();
  89577. };
  89578. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89579. return "FreeCameraVirtualJoystickInput";
  89580. };
  89581. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89582. return "virtualJoystick";
  89583. };
  89584. return FreeCameraVirtualJoystickInput;
  89585. }());
  89586. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89587. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89588. })(BABYLON || (BABYLON = {}));
  89589. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89590. var BABYLON;
  89591. (function (BABYLON) {
  89592. var SimplificationSettings = /** @class */ (function () {
  89593. function SimplificationSettings(quality, distance, optimizeMesh) {
  89594. this.quality = quality;
  89595. this.distance = distance;
  89596. this.optimizeMesh = optimizeMesh;
  89597. }
  89598. return SimplificationSettings;
  89599. }());
  89600. BABYLON.SimplificationSettings = SimplificationSettings;
  89601. var SimplificationQueue = /** @class */ (function () {
  89602. function SimplificationQueue() {
  89603. this.running = false;
  89604. this._simplificationArray = [];
  89605. }
  89606. SimplificationQueue.prototype.addTask = function (task) {
  89607. this._simplificationArray.push(task);
  89608. };
  89609. SimplificationQueue.prototype.executeNext = function () {
  89610. var task = this._simplificationArray.pop();
  89611. if (task) {
  89612. this.running = true;
  89613. this.runSimplification(task);
  89614. }
  89615. else {
  89616. this.running = false;
  89617. }
  89618. };
  89619. SimplificationQueue.prototype.runSimplification = function (task) {
  89620. var _this = this;
  89621. if (task.parallelProcessing) {
  89622. //parallel simplifier
  89623. task.settings.forEach(function (setting) {
  89624. var simplifier = _this.getSimplifier(task);
  89625. simplifier.simplify(setting, function (newMesh) {
  89626. task.mesh.addLODLevel(setting.distance, newMesh);
  89627. newMesh.isVisible = true;
  89628. //check if it is the last
  89629. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89630. //all done, run the success callback.
  89631. task.successCallback();
  89632. }
  89633. _this.executeNext();
  89634. });
  89635. });
  89636. }
  89637. else {
  89638. //single simplifier.
  89639. var simplifier = this.getSimplifier(task);
  89640. var runDecimation = function (setting, callback) {
  89641. simplifier.simplify(setting, function (newMesh) {
  89642. task.mesh.addLODLevel(setting.distance, newMesh);
  89643. newMesh.isVisible = true;
  89644. //run the next quality level
  89645. callback();
  89646. });
  89647. };
  89648. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89649. runDecimation(task.settings[loop.index], function () {
  89650. loop.executeNext();
  89651. });
  89652. }, function () {
  89653. //execution ended, run the success callback.
  89654. if (task.successCallback) {
  89655. task.successCallback();
  89656. }
  89657. _this.executeNext();
  89658. });
  89659. }
  89660. };
  89661. SimplificationQueue.prototype.getSimplifier = function (task) {
  89662. switch (task.simplificationType) {
  89663. case SimplificationType.QUADRATIC:
  89664. default:
  89665. return new QuadraticErrorSimplification(task.mesh);
  89666. }
  89667. };
  89668. return SimplificationQueue;
  89669. }());
  89670. BABYLON.SimplificationQueue = SimplificationQueue;
  89671. /**
  89672. * The implemented types of simplification
  89673. * At the moment only Quadratic Error Decimation is implemented
  89674. */
  89675. var SimplificationType;
  89676. (function (SimplificationType) {
  89677. /** Quadratic error decimation */
  89678. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89679. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89680. var DecimationTriangle = /** @class */ (function () {
  89681. function DecimationTriangle(vertices) {
  89682. this.vertices = vertices;
  89683. this.error = new Array(4);
  89684. this.deleted = false;
  89685. this.isDirty = false;
  89686. this.deletePending = false;
  89687. this.borderFactor = 0;
  89688. }
  89689. return DecimationTriangle;
  89690. }());
  89691. BABYLON.DecimationTriangle = DecimationTriangle;
  89692. var DecimationVertex = /** @class */ (function () {
  89693. function DecimationVertex(position, id) {
  89694. this.position = position;
  89695. this.id = id;
  89696. this.isBorder = true;
  89697. this.q = new QuadraticMatrix();
  89698. this.triangleCount = 0;
  89699. this.triangleStart = 0;
  89700. this.originalOffsets = [];
  89701. }
  89702. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89703. this.position.copyFrom(newPosition);
  89704. };
  89705. return DecimationVertex;
  89706. }());
  89707. BABYLON.DecimationVertex = DecimationVertex;
  89708. var QuadraticMatrix = /** @class */ (function () {
  89709. function QuadraticMatrix(data) {
  89710. this.data = new Array(10);
  89711. for (var i = 0; i < 10; ++i) {
  89712. if (data && data[i]) {
  89713. this.data[i] = data[i];
  89714. }
  89715. else {
  89716. this.data[i] = 0;
  89717. }
  89718. }
  89719. }
  89720. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89721. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89722. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89723. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89724. return det;
  89725. };
  89726. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89727. for (var i = 0; i < 10; ++i) {
  89728. this.data[i] += matrix.data[i];
  89729. }
  89730. };
  89731. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89732. for (var i = 0; i < 10; ++i) {
  89733. this.data[i] += data[i];
  89734. }
  89735. };
  89736. QuadraticMatrix.prototype.add = function (matrix) {
  89737. var m = new QuadraticMatrix();
  89738. for (var i = 0; i < 10; ++i) {
  89739. m.data[i] = this.data[i] + matrix.data[i];
  89740. }
  89741. return m;
  89742. };
  89743. QuadraticMatrix.FromData = function (a, b, c, d) {
  89744. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89745. };
  89746. //returning an array to avoid garbage collection
  89747. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89748. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89749. };
  89750. return QuadraticMatrix;
  89751. }());
  89752. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89753. var Reference = /** @class */ (function () {
  89754. function Reference(vertexId, triangleId) {
  89755. this.vertexId = vertexId;
  89756. this.triangleId = triangleId;
  89757. }
  89758. return Reference;
  89759. }());
  89760. BABYLON.Reference = Reference;
  89761. /**
  89762. * An implementation of the Quadratic Error simplification algorithm.
  89763. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89764. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89765. * @author RaananW
  89766. */
  89767. var QuadraticErrorSimplification = /** @class */ (function () {
  89768. function QuadraticErrorSimplification(_mesh) {
  89769. this._mesh = _mesh;
  89770. this.syncIterations = 5000;
  89771. this.aggressiveness = 7;
  89772. this.decimationIterations = 100;
  89773. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89774. }
  89775. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89776. var _this = this;
  89777. this.initDecimatedMesh();
  89778. //iterating through the submeshes array, one after the other.
  89779. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89780. _this.initWithMesh(loop.index, function () {
  89781. _this.runDecimation(settings, loop.index, function () {
  89782. loop.executeNext();
  89783. });
  89784. }, settings.optimizeMesh);
  89785. }, function () {
  89786. setTimeout(function () {
  89787. successCallback(_this._reconstructedMesh);
  89788. }, 0);
  89789. });
  89790. };
  89791. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89792. var _this = this;
  89793. var targetCount = ~~(this.triangles.length * settings.quality);
  89794. var deletedTriangles = 0;
  89795. var triangleCount = this.triangles.length;
  89796. var iterationFunction = function (iteration, callback) {
  89797. setTimeout(function () {
  89798. if (iteration % 5 === 0) {
  89799. _this.updateMesh(iteration === 0);
  89800. }
  89801. for (var i = 0; i < _this.triangles.length; ++i) {
  89802. _this.triangles[i].isDirty = false;
  89803. }
  89804. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89805. var trianglesIterator = function (i) {
  89806. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89807. var t = _this.triangles[tIdx];
  89808. if (!t)
  89809. return;
  89810. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89811. return;
  89812. }
  89813. for (var j = 0; j < 3; ++j) {
  89814. if (t.error[j] < threshold) {
  89815. var deleted0 = [];
  89816. var deleted1 = [];
  89817. var v0 = t.vertices[j];
  89818. var v1 = t.vertices[(j + 1) % 3];
  89819. if (v0.isBorder || v1.isBorder)
  89820. continue;
  89821. var p = BABYLON.Vector3.Zero();
  89822. var n = BABYLON.Vector3.Zero();
  89823. var uv = BABYLON.Vector2.Zero();
  89824. var color = new BABYLON.Color4(0, 0, 0, 1);
  89825. _this.calculateError(v0, v1, p, n, uv, color);
  89826. var delTr = new Array();
  89827. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89828. continue;
  89829. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89830. continue;
  89831. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89832. continue;
  89833. var uniqueArray = new Array();
  89834. delTr.forEach(function (deletedT) {
  89835. if (uniqueArray.indexOf(deletedT) === -1) {
  89836. deletedT.deletePending = true;
  89837. uniqueArray.push(deletedT);
  89838. }
  89839. });
  89840. if (uniqueArray.length % 2 !== 0) {
  89841. continue;
  89842. }
  89843. v0.q = v1.q.add(v0.q);
  89844. v0.updatePosition(p);
  89845. var tStart = _this.references.length;
  89846. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89847. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89848. var tCount = _this.references.length - tStart;
  89849. if (tCount <= v0.triangleCount) {
  89850. if (tCount) {
  89851. for (var c = 0; c < tCount; c++) {
  89852. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89853. }
  89854. }
  89855. }
  89856. else {
  89857. v0.triangleStart = tStart;
  89858. }
  89859. v0.triangleCount = tCount;
  89860. break;
  89861. }
  89862. }
  89863. };
  89864. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89865. }, 0);
  89866. };
  89867. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89868. if (triangleCount - deletedTriangles <= targetCount)
  89869. loop.breakLoop();
  89870. else {
  89871. iterationFunction(loop.index, function () {
  89872. loop.executeNext();
  89873. });
  89874. }
  89875. }, function () {
  89876. setTimeout(function () {
  89877. //reconstruct this part of the mesh
  89878. _this.reconstructMesh(submeshIndex);
  89879. successCallback();
  89880. }, 0);
  89881. });
  89882. };
  89883. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89884. var _this = this;
  89885. this.vertices = [];
  89886. this.triangles = [];
  89887. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89888. var indices = this._mesh.getIndices();
  89889. var submesh = this._mesh.subMeshes[submeshIndex];
  89890. var findInVertices = function (positionToSearch) {
  89891. if (optimizeMesh) {
  89892. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89893. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89894. return _this.vertices[ii];
  89895. }
  89896. }
  89897. }
  89898. return null;
  89899. };
  89900. var vertexReferences = [];
  89901. var vertexInit = function (i) {
  89902. if (!positionData) {
  89903. return;
  89904. }
  89905. var offset = i + submesh.verticesStart;
  89906. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89907. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89908. vertex.originalOffsets.push(offset);
  89909. if (vertex.id === _this.vertices.length) {
  89910. _this.vertices.push(vertex);
  89911. }
  89912. vertexReferences.push(vertex.id);
  89913. };
  89914. //var totalVertices = mesh.getTotalVertices();
  89915. var totalVertices = submesh.verticesCount;
  89916. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89917. var indicesInit = function (i) {
  89918. if (!indices) {
  89919. return;
  89920. }
  89921. var offset = (submesh.indexStart / 3) + i;
  89922. var pos = (offset * 3);
  89923. var i0 = indices[pos + 0];
  89924. var i1 = indices[pos + 1];
  89925. var i2 = indices[pos + 2];
  89926. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89927. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89928. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89929. var triangle = new DecimationTriangle([v0, v1, v2]);
  89930. triangle.originalOffset = pos;
  89931. _this.triangles.push(triangle);
  89932. };
  89933. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89934. _this.init(callback);
  89935. });
  89936. });
  89937. };
  89938. QuadraticErrorSimplification.prototype.init = function (callback) {
  89939. var _this = this;
  89940. var triangleInit1 = function (i) {
  89941. var t = _this.triangles[i];
  89942. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89943. for (var j = 0; j < 3; j++) {
  89944. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  89945. }
  89946. };
  89947. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89948. var triangleInit2 = function (i) {
  89949. var t = _this.triangles[i];
  89950. for (var j = 0; j < 3; ++j) {
  89951. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89952. }
  89953. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89954. };
  89955. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89956. callback();
  89957. });
  89958. });
  89959. };
  89960. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89961. var newTriangles = [];
  89962. var i;
  89963. for (i = 0; i < this.vertices.length; ++i) {
  89964. this.vertices[i].triangleCount = 0;
  89965. }
  89966. var t;
  89967. var j;
  89968. for (i = 0; i < this.triangles.length; ++i) {
  89969. if (!this.triangles[i].deleted) {
  89970. t = this.triangles[i];
  89971. for (j = 0; j < 3; ++j) {
  89972. t.vertices[j].triangleCount = 1;
  89973. }
  89974. newTriangles.push(t);
  89975. }
  89976. }
  89977. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89978. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89979. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89980. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89981. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89982. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89983. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89984. var vertexCount = 0;
  89985. for (i = 0; i < this.vertices.length; ++i) {
  89986. var vertex = this.vertices[i];
  89987. vertex.id = vertexCount;
  89988. if (vertex.triangleCount) {
  89989. vertex.originalOffsets.forEach(function (originalOffset) {
  89990. if (!normalData) {
  89991. return;
  89992. }
  89993. newPositionData.push(vertex.position.x);
  89994. newPositionData.push(vertex.position.y);
  89995. newPositionData.push(vertex.position.z);
  89996. newNormalData.push(normalData[originalOffset * 3]);
  89997. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89998. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89999. if (uvs && uvs.length) {
  90000. newUVsData.push(uvs[(originalOffset * 2)]);
  90001. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90002. }
  90003. else if (colorsData && colorsData.length) {
  90004. newColorsData.push(colorsData[(originalOffset * 4)]);
  90005. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90006. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90007. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90008. }
  90009. ++vertexCount;
  90010. });
  90011. }
  90012. }
  90013. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90014. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90015. var submeshesArray = this._reconstructedMesh.subMeshes;
  90016. this._reconstructedMesh.subMeshes = [];
  90017. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90018. var originalIndices = this._mesh.getIndices();
  90019. for (i = 0; i < newTriangles.length; ++i) {
  90020. t = newTriangles[i]; //now get the new referencing point for each vertex
  90021. [0, 1, 2].forEach(function (idx) {
  90022. var id = originalIndices[t.originalOffset + idx];
  90023. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90024. if (offset < 0)
  90025. offset = 0;
  90026. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90027. });
  90028. }
  90029. //overwriting the old vertex buffers and indices.
  90030. this._reconstructedMesh.setIndices(newIndicesArray);
  90031. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90032. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90033. if (newUVsData.length > 0)
  90034. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90035. if (newColorsData.length > 0)
  90036. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90037. //create submesh
  90038. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90039. if (submeshIndex > 0) {
  90040. this._reconstructedMesh.subMeshes = [];
  90041. submeshesArray.forEach(function (submesh) {
  90042. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90043. });
  90044. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90045. }
  90046. };
  90047. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90048. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90049. this._reconstructedMesh.material = this._mesh.material;
  90050. this._reconstructedMesh.parent = this._mesh.parent;
  90051. this._reconstructedMesh.isVisible = false;
  90052. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90053. };
  90054. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90055. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90056. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90057. if (t.deleted)
  90058. continue;
  90059. var s = this.references[vertex1.triangleStart + i].vertexId;
  90060. var v1 = t.vertices[(s + 1) % 3];
  90061. var v2 = t.vertices[(s + 2) % 3];
  90062. if ((v1 === vertex2 || v2 === vertex2)) {
  90063. deletedArray[i] = true;
  90064. delTr.push(t);
  90065. continue;
  90066. }
  90067. var d1 = v1.position.subtract(point);
  90068. d1 = d1.normalize();
  90069. var d2 = v2.position.subtract(point);
  90070. d2 = d2.normalize();
  90071. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90072. return true;
  90073. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90074. deletedArray[i] = false;
  90075. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90076. return true;
  90077. }
  90078. return false;
  90079. };
  90080. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90081. var newDeleted = deletedTriangles;
  90082. for (var i = 0; i < vertex.triangleCount; ++i) {
  90083. var ref = this.references[vertex.triangleStart + i];
  90084. var t = this.triangles[ref.triangleId];
  90085. if (t.deleted)
  90086. continue;
  90087. if (deletedArray[i] && t.deletePending) {
  90088. t.deleted = true;
  90089. newDeleted++;
  90090. continue;
  90091. }
  90092. t.vertices[ref.vertexId] = origVertex;
  90093. t.isDirty = true;
  90094. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90095. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90096. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90097. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90098. this.references.push(ref);
  90099. }
  90100. return newDeleted;
  90101. };
  90102. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90103. for (var i = 0; i < this.vertices.length; ++i) {
  90104. var vCount = [];
  90105. var vId = [];
  90106. var v = this.vertices[i];
  90107. var j;
  90108. for (j = 0; j < v.triangleCount; ++j) {
  90109. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90110. for (var ii = 0; ii < 3; ii++) {
  90111. var ofs = 0;
  90112. var vv = triangle.vertices[ii];
  90113. while (ofs < vCount.length) {
  90114. if (vId[ofs] === vv.id)
  90115. break;
  90116. ++ofs;
  90117. }
  90118. if (ofs === vCount.length) {
  90119. vCount.push(1);
  90120. vId.push(vv.id);
  90121. }
  90122. else {
  90123. vCount[ofs]++;
  90124. }
  90125. }
  90126. }
  90127. for (j = 0; j < vCount.length; ++j) {
  90128. if (vCount[j] === 1) {
  90129. this.vertices[vId[j]].isBorder = true;
  90130. }
  90131. else {
  90132. this.vertices[vId[j]].isBorder = false;
  90133. }
  90134. }
  90135. }
  90136. };
  90137. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90138. if (identifyBorders === void 0) { identifyBorders = false; }
  90139. var i;
  90140. if (!identifyBorders) {
  90141. var newTrianglesVector = [];
  90142. for (i = 0; i < this.triangles.length; ++i) {
  90143. if (!this.triangles[i].deleted) {
  90144. newTrianglesVector.push(this.triangles[i]);
  90145. }
  90146. }
  90147. this.triangles = newTrianglesVector;
  90148. }
  90149. for (i = 0; i < this.vertices.length; ++i) {
  90150. this.vertices[i].triangleCount = 0;
  90151. this.vertices[i].triangleStart = 0;
  90152. }
  90153. var t;
  90154. var j;
  90155. var v;
  90156. for (i = 0; i < this.triangles.length; ++i) {
  90157. t = this.triangles[i];
  90158. for (j = 0; j < 3; ++j) {
  90159. v = t.vertices[j];
  90160. v.triangleCount++;
  90161. }
  90162. }
  90163. var tStart = 0;
  90164. for (i = 0; i < this.vertices.length; ++i) {
  90165. this.vertices[i].triangleStart = tStart;
  90166. tStart += this.vertices[i].triangleCount;
  90167. this.vertices[i].triangleCount = 0;
  90168. }
  90169. var newReferences = new Array(this.triangles.length * 3);
  90170. for (i = 0; i < this.triangles.length; ++i) {
  90171. t = this.triangles[i];
  90172. for (j = 0; j < 3; ++j) {
  90173. v = t.vertices[j];
  90174. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90175. v.triangleCount++;
  90176. }
  90177. }
  90178. this.references = newReferences;
  90179. if (identifyBorders) {
  90180. this.identifyBorder();
  90181. }
  90182. };
  90183. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90184. var x = point.x;
  90185. var y = point.y;
  90186. var z = point.z;
  90187. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  90188. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90189. };
  90190. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90191. var q = vertex1.q.add(vertex2.q);
  90192. var border = vertex1.isBorder && vertex2.isBorder;
  90193. var error = 0;
  90194. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90195. if (qDet !== 0 && !border) {
  90196. if (!pointResult) {
  90197. pointResult = BABYLON.Vector3.Zero();
  90198. }
  90199. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90200. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90201. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90202. error = this.vertexError(q, pointResult);
  90203. }
  90204. else {
  90205. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90206. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90207. var error1 = this.vertexError(q, vertex1.position);
  90208. var error2 = this.vertexError(q, vertex2.position);
  90209. var error3 = this.vertexError(q, p3);
  90210. error = Math.min(error1, error2, error3);
  90211. if (error === error1) {
  90212. if (pointResult) {
  90213. pointResult.copyFrom(vertex1.position);
  90214. }
  90215. }
  90216. else if (error === error2) {
  90217. if (pointResult) {
  90218. pointResult.copyFrom(vertex2.position);
  90219. }
  90220. }
  90221. else {
  90222. if (pointResult) {
  90223. pointResult.copyFrom(p3);
  90224. }
  90225. }
  90226. }
  90227. return error;
  90228. };
  90229. return QuadraticErrorSimplification;
  90230. }());
  90231. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90232. })(BABYLON || (BABYLON = {}));
  90233. //# sourceMappingURL=babylon.meshSimplification.js.map
  90234. var BABYLON;
  90235. (function (BABYLON) {
  90236. var MeshLODLevel = /** @class */ (function () {
  90237. function MeshLODLevel(distance, mesh) {
  90238. this.distance = distance;
  90239. this.mesh = mesh;
  90240. }
  90241. return MeshLODLevel;
  90242. }());
  90243. BABYLON.MeshLODLevel = MeshLODLevel;
  90244. })(BABYLON || (BABYLON = {}));
  90245. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90246. var BABYLON;
  90247. (function (BABYLON) {
  90248. /**
  90249. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90250. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90251. */
  90252. var SceneOptimization = /** @class */ (function () {
  90253. /**
  90254. * Creates the SceneOptimization object
  90255. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90256. * @param desc defines the description associated with the optimization
  90257. */
  90258. function SceneOptimization(
  90259. /**
  90260. * Defines the priority of this optimization (0 by default which means first in the list)
  90261. */
  90262. priority) {
  90263. if (priority === void 0) { priority = 0; }
  90264. this.priority = priority;
  90265. }
  90266. /**
  90267. * Gets a string describing the action executed by the current optimization
  90268. * @returns description string
  90269. */
  90270. SceneOptimization.prototype.getDescription = function () {
  90271. return "";
  90272. };
  90273. /**
  90274. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90275. * @param scene defines the current scene where to apply this optimization
  90276. * @param optimizer defines the current optimizer
  90277. * @returns true if everything that can be done was applied
  90278. */
  90279. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90280. return true;
  90281. };
  90282. ;
  90283. return SceneOptimization;
  90284. }());
  90285. BABYLON.SceneOptimization = SceneOptimization;
  90286. /**
  90287. * Defines an optimization used to reduce the size of render target textures
  90288. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90289. */
  90290. var TextureOptimization = /** @class */ (function (_super) {
  90291. __extends(TextureOptimization, _super);
  90292. /**
  90293. * Creates the TextureOptimization object
  90294. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90295. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  90296. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90297. */
  90298. function TextureOptimization(
  90299. /**
  90300. * Defines the priority of this optimization (0 by default which means first in the list)
  90301. */
  90302. priority,
  90303. /**
  90304. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  90305. */
  90306. maximumSize,
  90307. /**
  90308. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90309. */
  90310. step) {
  90311. if (priority === void 0) { priority = 0; }
  90312. if (maximumSize === void 0) { maximumSize = 1024; }
  90313. if (step === void 0) { step = 0.5; }
  90314. var _this = _super.call(this, priority) || this;
  90315. _this.priority = priority;
  90316. _this.maximumSize = maximumSize;
  90317. _this.step = step;
  90318. return _this;
  90319. }
  90320. /**
  90321. * Gets a string describing the action executed by the current optimization
  90322. * @returns description string
  90323. */
  90324. TextureOptimization.prototype.getDescription = function () {
  90325. return "Reducing render target texture size to " + this.maximumSize;
  90326. };
  90327. /**
  90328. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90329. * @param scene defines the current scene where to apply this optimization
  90330. * @param optimizer defines the current optimizer
  90331. * @returns true if everything that can be done was applied
  90332. */
  90333. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90334. var allDone = true;
  90335. for (var index = 0; index < scene.textures.length; index++) {
  90336. var texture = scene.textures[index];
  90337. if (!texture.canRescale || texture.getContext) {
  90338. continue;
  90339. }
  90340. var currentSize = texture.getSize();
  90341. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90342. if (maxDimension > this.maximumSize) {
  90343. texture.scale(this.step);
  90344. allDone = false;
  90345. }
  90346. }
  90347. return allDone;
  90348. };
  90349. return TextureOptimization;
  90350. }(SceneOptimization));
  90351. BABYLON.TextureOptimization = TextureOptimization;
  90352. /**
  90353. * Defines an optimization used to increase or decrease the rendering resolution
  90354. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90355. */
  90356. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90357. __extends(HardwareScalingOptimization, _super);
  90358. /**
  90359. * Creates the HardwareScalingOptimization object
  90360. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90361. * @param maximumScale defines the maximum scale to use (2 by default)
  90362. * @param step defines the step to use between two passes (0.5 by default)
  90363. */
  90364. function HardwareScalingOptimization(
  90365. /**
  90366. * Defines the priority of this optimization (0 by default which means first in the list)
  90367. */
  90368. priority,
  90369. /**
  90370. * Defines the maximum scale to use (2 by default)
  90371. */
  90372. maximumScale,
  90373. /**
  90374. * Defines the step to use between two passes (0.5 by default)
  90375. */
  90376. step) {
  90377. if (priority === void 0) { priority = 0; }
  90378. if (maximumScale === void 0) { maximumScale = 2; }
  90379. if (step === void 0) { step = 0.25; }
  90380. var _this = _super.call(this, priority) || this;
  90381. _this.priority = priority;
  90382. _this.maximumScale = maximumScale;
  90383. _this.step = step;
  90384. _this._currentScale = -1;
  90385. _this._directionOffset = 1;
  90386. return _this;
  90387. }
  90388. /**
  90389. * Gets a string describing the action executed by the current optimization
  90390. * @return description string
  90391. */
  90392. HardwareScalingOptimization.prototype.getDescription = function () {
  90393. return "Setting hardware scaling level to " + this._currentScale;
  90394. };
  90395. /**
  90396. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90397. * @param scene defines the current scene where to apply this optimization
  90398. * @param optimizer defines the current optimizer
  90399. * @returns true if everything that can be done was applied
  90400. */
  90401. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90402. if (this._currentScale === -1) {
  90403. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90404. if (this._currentScale > this.maximumScale) {
  90405. this._directionOffset = -1;
  90406. }
  90407. }
  90408. this._currentScale += this._directionOffset * this.step;
  90409. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90410. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90411. };
  90412. ;
  90413. return HardwareScalingOptimization;
  90414. }(SceneOptimization));
  90415. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90416. /**
  90417. * Defines an optimization used to remove shadows
  90418. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90419. */
  90420. var ShadowsOptimization = /** @class */ (function (_super) {
  90421. __extends(ShadowsOptimization, _super);
  90422. function ShadowsOptimization() {
  90423. return _super !== null && _super.apply(this, arguments) || this;
  90424. }
  90425. /**
  90426. * Gets a string describing the action executed by the current optimization
  90427. * @return description string
  90428. */
  90429. ShadowsOptimization.prototype.getDescription = function () {
  90430. return "Turning shadows on/off";
  90431. };
  90432. /**
  90433. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90434. * @param scene defines the current scene where to apply this optimization
  90435. * @param optimizer defines the current optimizer
  90436. * @returns true if everything that can be done was applied
  90437. */
  90438. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90439. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90440. return true;
  90441. };
  90442. ;
  90443. return ShadowsOptimization;
  90444. }(SceneOptimization));
  90445. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90446. /**
  90447. * Defines an optimization used to turn post-processes off
  90448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90449. */
  90450. var PostProcessesOptimization = /** @class */ (function (_super) {
  90451. __extends(PostProcessesOptimization, _super);
  90452. function PostProcessesOptimization() {
  90453. return _super !== null && _super.apply(this, arguments) || this;
  90454. }
  90455. /**
  90456. * Gets a string describing the action executed by the current optimization
  90457. * @return description string
  90458. */
  90459. PostProcessesOptimization.prototype.getDescription = function () {
  90460. return "Turning post-processes on/off";
  90461. };
  90462. /**
  90463. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90464. * @param scene defines the current scene where to apply this optimization
  90465. * @param optimizer defines the current optimizer
  90466. * @returns true if everything that can be done was applied
  90467. */
  90468. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90469. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90470. return true;
  90471. };
  90472. ;
  90473. return PostProcessesOptimization;
  90474. }(SceneOptimization));
  90475. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90476. /**
  90477. * Defines an optimization used to turn lens flares off
  90478. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90479. */
  90480. var LensFlaresOptimization = /** @class */ (function (_super) {
  90481. __extends(LensFlaresOptimization, _super);
  90482. function LensFlaresOptimization() {
  90483. return _super !== null && _super.apply(this, arguments) || this;
  90484. }
  90485. /**
  90486. * Gets a string describing the action executed by the current optimization
  90487. * @return description string
  90488. */
  90489. LensFlaresOptimization.prototype.getDescription = function () {
  90490. return "Turning lens flares on/off";
  90491. };
  90492. /**
  90493. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90494. * @param scene defines the current scene where to apply this optimization
  90495. * @param optimizer defines the current optimizer
  90496. * @returns true if everything that can be done was applied
  90497. */
  90498. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90499. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90500. return true;
  90501. };
  90502. ;
  90503. return LensFlaresOptimization;
  90504. }(SceneOptimization));
  90505. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90506. /**
  90507. * Defines an optimization based on user defined callback.
  90508. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90509. */
  90510. var CustomOptimization = /** @class */ (function (_super) {
  90511. __extends(CustomOptimization, _super);
  90512. function CustomOptimization() {
  90513. return _super !== null && _super.apply(this, arguments) || this;
  90514. }
  90515. /**
  90516. * Gets a string describing the action executed by the current optimization
  90517. * @returns description string
  90518. */
  90519. CustomOptimization.prototype.getDescription = function () {
  90520. if (this.onGetDescription) {
  90521. return this.onGetDescription();
  90522. }
  90523. return "Running user defined callback";
  90524. };
  90525. /**
  90526. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90527. * @param scene defines the current scene where to apply this optimization
  90528. * @param optimizer defines the current optimizer
  90529. * @returns true if everything that can be done was applied
  90530. */
  90531. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90532. if (this.onApply) {
  90533. return this.onApply(scene, optimizer);
  90534. }
  90535. return true;
  90536. };
  90537. ;
  90538. return CustomOptimization;
  90539. }(SceneOptimization));
  90540. BABYLON.CustomOptimization = CustomOptimization;
  90541. /**
  90542. * Defines an optimization used to turn particles off
  90543. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90544. */
  90545. var ParticlesOptimization = /** @class */ (function (_super) {
  90546. __extends(ParticlesOptimization, _super);
  90547. function ParticlesOptimization() {
  90548. return _super !== null && _super.apply(this, arguments) || this;
  90549. }
  90550. /**
  90551. * Gets a string describing the action executed by the current optimization
  90552. * @return description string
  90553. */
  90554. ParticlesOptimization.prototype.getDescription = function () {
  90555. return "Turning particles on/off";
  90556. };
  90557. /**
  90558. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90559. * @param scene defines the current scene where to apply this optimization
  90560. * @param optimizer defines the current optimizer
  90561. * @returns true if everything that can be done was applied
  90562. */
  90563. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90564. scene.particlesEnabled = optimizer.isInImprovementMode;
  90565. return true;
  90566. };
  90567. ;
  90568. return ParticlesOptimization;
  90569. }(SceneOptimization));
  90570. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90571. /**
  90572. * Defines an optimization used to turn render targets off
  90573. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90574. */
  90575. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90576. __extends(RenderTargetsOptimization, _super);
  90577. function RenderTargetsOptimization() {
  90578. return _super !== null && _super.apply(this, arguments) || this;
  90579. }
  90580. /**
  90581. * Gets a string describing the action executed by the current optimization
  90582. * @return description string
  90583. */
  90584. RenderTargetsOptimization.prototype.getDescription = function () {
  90585. return "Turning render targets off";
  90586. };
  90587. /**
  90588. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90589. * @param scene defines the current scene where to apply this optimization
  90590. * @param optimizer defines the current optimizer
  90591. * @returns true if everything that can be done was applied
  90592. */
  90593. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90594. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90595. return true;
  90596. };
  90597. ;
  90598. return RenderTargetsOptimization;
  90599. }(SceneOptimization));
  90600. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90601. /**
  90602. * Defines an optimization used to merge meshes with compatible materials
  90603. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90604. */
  90605. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90606. __extends(MergeMeshesOptimization, _super);
  90607. function MergeMeshesOptimization() {
  90608. var _this = _super !== null && _super.apply(this, arguments) || this;
  90609. _this._canBeMerged = function (abstractMesh) {
  90610. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90611. return false;
  90612. }
  90613. var mesh = abstractMesh;
  90614. if (!mesh.isVisible || !mesh.isEnabled()) {
  90615. return false;
  90616. }
  90617. if (mesh.instances.length > 0) {
  90618. return false;
  90619. }
  90620. if (mesh.skeleton || mesh.hasLODLevels) {
  90621. return false;
  90622. }
  90623. if (mesh.parent) {
  90624. return false;
  90625. }
  90626. return true;
  90627. };
  90628. return _this;
  90629. }
  90630. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90631. /**
  90632. * Gets or sets a boolean which defines if optimization octree has to be updated
  90633. */
  90634. get: function () {
  90635. return MergeMeshesOptimization._UpdateSelectionTree;
  90636. },
  90637. /**
  90638. * Gets or sets a boolean which defines if optimization octree has to be updated
  90639. */
  90640. set: function (value) {
  90641. MergeMeshesOptimization._UpdateSelectionTree = value;
  90642. },
  90643. enumerable: true,
  90644. configurable: true
  90645. });
  90646. /**
  90647. * Gets a string describing the action executed by the current optimization
  90648. * @return description string
  90649. */
  90650. MergeMeshesOptimization.prototype.getDescription = function () {
  90651. return "Merging similar meshes together";
  90652. };
  90653. /**
  90654. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90655. * @param scene defines the current scene where to apply this optimization
  90656. * @param optimizer defines the current optimizer
  90657. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90658. * @returns true if everything that can be done was applied
  90659. */
  90660. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90661. var globalPool = scene.meshes.slice(0);
  90662. var globalLength = globalPool.length;
  90663. for (var index = 0; index < globalLength; index++) {
  90664. var currentPool = new Array();
  90665. var current = globalPool[index];
  90666. // Checks
  90667. if (!this._canBeMerged(current)) {
  90668. continue;
  90669. }
  90670. currentPool.push(current);
  90671. // Find compatible meshes
  90672. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90673. var otherMesh = globalPool[subIndex];
  90674. if (!this._canBeMerged(otherMesh)) {
  90675. continue;
  90676. }
  90677. if (otherMesh.material !== current.material) {
  90678. continue;
  90679. }
  90680. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90681. continue;
  90682. }
  90683. currentPool.push(otherMesh);
  90684. globalLength--;
  90685. globalPool.splice(subIndex, 1);
  90686. subIndex--;
  90687. }
  90688. if (currentPool.length < 2) {
  90689. continue;
  90690. }
  90691. // Merge meshes
  90692. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90693. }
  90694. if (updateSelectionTree != undefined) {
  90695. if (updateSelectionTree) {
  90696. scene.createOrUpdateSelectionOctree();
  90697. }
  90698. }
  90699. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90700. scene.createOrUpdateSelectionOctree();
  90701. }
  90702. return true;
  90703. };
  90704. ;
  90705. MergeMeshesOptimization._UpdateSelectionTree = false;
  90706. return MergeMeshesOptimization;
  90707. }(SceneOptimization));
  90708. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90709. /**
  90710. * Defines a list of options used by SceneOptimizer
  90711. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90712. */
  90713. var SceneOptimizerOptions = /** @class */ (function () {
  90714. /**
  90715. * Creates a new list of options used by SceneOptimizer
  90716. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90717. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90718. */
  90719. function SceneOptimizerOptions(
  90720. /**
  90721. * Defines the target frame rate to reach (60 by default)
  90722. */
  90723. targetFrameRate,
  90724. /**
  90725. * Defines the interval between two checkes (2000ms by default)
  90726. */
  90727. trackerDuration) {
  90728. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90729. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90730. this.targetFrameRate = targetFrameRate;
  90731. this.trackerDuration = trackerDuration;
  90732. /**
  90733. * Gets the list of optimizations to apply
  90734. */
  90735. this.optimizations = new Array();
  90736. }
  90737. /**
  90738. * Add a new optimization
  90739. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90740. * @returns the current SceneOptimizerOptions
  90741. */
  90742. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90743. this.optimizations.push(optimization);
  90744. return this;
  90745. };
  90746. /**
  90747. * Add a new custom optimization
  90748. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90749. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90750. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90751. * @returns the current SceneOptimizerOptions
  90752. */
  90753. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90754. if (priority === void 0) { priority = 0; }
  90755. var optimization = new CustomOptimization(priority);
  90756. optimization.onApply = onApply;
  90757. optimization.onGetDescription = onGetDescription;
  90758. this.optimizations.push(optimization);
  90759. return this;
  90760. };
  90761. /**
  90762. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90763. * @param targetFrameRate defines the target frame rate (60 by default)
  90764. * @returns a SceneOptimizerOptions object
  90765. */
  90766. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90767. var result = new SceneOptimizerOptions(targetFrameRate);
  90768. var priority = 0;
  90769. result.addOptimization(new MergeMeshesOptimization(priority));
  90770. result.addOptimization(new ShadowsOptimization(priority));
  90771. result.addOptimization(new LensFlaresOptimization(priority));
  90772. // Next priority
  90773. priority++;
  90774. result.addOptimization(new PostProcessesOptimization(priority));
  90775. result.addOptimization(new ParticlesOptimization(priority));
  90776. // Next priority
  90777. priority++;
  90778. result.addOptimization(new TextureOptimization(priority, 1024));
  90779. return result;
  90780. };
  90781. /**
  90782. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90783. * @param targetFrameRate defines the target frame rate (60 by default)
  90784. * @returns a SceneOptimizerOptions object
  90785. */
  90786. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90787. var result = new SceneOptimizerOptions(targetFrameRate);
  90788. var priority = 0;
  90789. result.addOptimization(new MergeMeshesOptimization(priority));
  90790. result.addOptimization(new ShadowsOptimization(priority));
  90791. result.addOptimization(new LensFlaresOptimization(priority));
  90792. // Next priority
  90793. priority++;
  90794. result.addOptimization(new PostProcessesOptimization(priority));
  90795. result.addOptimization(new ParticlesOptimization(priority));
  90796. // Next priority
  90797. priority++;
  90798. result.addOptimization(new TextureOptimization(priority, 512));
  90799. // Next priority
  90800. priority++;
  90801. result.addOptimization(new RenderTargetsOptimization(priority));
  90802. // Next priority
  90803. priority++;
  90804. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90805. return result;
  90806. };
  90807. /**
  90808. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90809. * @param targetFrameRate defines the target frame rate (60 by default)
  90810. * @returns a SceneOptimizerOptions object
  90811. */
  90812. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90813. var result = new SceneOptimizerOptions(targetFrameRate);
  90814. var priority = 0;
  90815. result.addOptimization(new MergeMeshesOptimization(priority));
  90816. result.addOptimization(new ShadowsOptimization(priority));
  90817. result.addOptimization(new LensFlaresOptimization(priority));
  90818. // Next priority
  90819. priority++;
  90820. result.addOptimization(new PostProcessesOptimization(priority));
  90821. result.addOptimization(new ParticlesOptimization(priority));
  90822. // Next priority
  90823. priority++;
  90824. result.addOptimization(new TextureOptimization(priority, 256));
  90825. // Next priority
  90826. priority++;
  90827. result.addOptimization(new RenderTargetsOptimization(priority));
  90828. // Next priority
  90829. priority++;
  90830. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90831. return result;
  90832. };
  90833. return SceneOptimizerOptions;
  90834. }());
  90835. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90836. /**
  90837. * Class used to run optimizations in order to reach a target frame rate
  90838. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90839. */
  90840. var SceneOptimizer = /** @class */ (function () {
  90841. /**
  90842. * Creates a new SceneOptimizer
  90843. * @param scene defines the scene to work on
  90844. * @param options defines the options to use with the SceneOptimizer
  90845. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90846. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  90847. */
  90848. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90849. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90850. if (improvementMode === void 0) { improvementMode = false; }
  90851. var _this = this;
  90852. this._isRunning = false;
  90853. this._currentPriorityLevel = 0;
  90854. this._targetFrameRate = 60;
  90855. this._trackerDuration = 2000;
  90856. this._currentFrameRate = 0;
  90857. this._improvementMode = false;
  90858. /**
  90859. * Defines an observable called when the optimizer reaches the target frame rate
  90860. */
  90861. this.onSuccessObservable = new BABYLON.Observable();
  90862. /**
  90863. * Defines an observable called when the optimizer enables an optimization
  90864. */
  90865. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90866. /**
  90867. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90868. */
  90869. this.onFailureObservable = new BABYLON.Observable();
  90870. if (!options) {
  90871. this._options = new SceneOptimizerOptions();
  90872. }
  90873. else {
  90874. this._options = options;
  90875. }
  90876. if (this._options.targetFrameRate) {
  90877. this._targetFrameRate = this._options.targetFrameRate;
  90878. }
  90879. if (this._options.trackerDuration) {
  90880. this._trackerDuration = this._options.trackerDuration;
  90881. }
  90882. if (autoGeneratePriorities) {
  90883. var priority = 0;
  90884. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90885. var optim = _a[_i];
  90886. optim.priority = priority++;
  90887. }
  90888. }
  90889. this._improvementMode = improvementMode;
  90890. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90891. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90892. _this._sceneDisposeObserver = null;
  90893. _this.dispose();
  90894. });
  90895. }
  90896. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90897. /**
  90898. * Gets a boolean indicating if the optimizer is in improvement mode
  90899. */
  90900. get: function () {
  90901. return this._improvementMode;
  90902. },
  90903. enumerable: true,
  90904. configurable: true
  90905. });
  90906. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90907. /**
  90908. * Gets the current priority level (0 at start)
  90909. */
  90910. get: function () {
  90911. return this._currentPriorityLevel;
  90912. },
  90913. enumerable: true,
  90914. configurable: true
  90915. });
  90916. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90917. /**
  90918. * Gets the current frame rate checked by the SceneOptimizer
  90919. */
  90920. get: function () {
  90921. return this._currentFrameRate;
  90922. },
  90923. enumerable: true,
  90924. configurable: true
  90925. });
  90926. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90927. /**
  90928. * Gets or sets the current target frame rate (60 by default)
  90929. */
  90930. get: function () {
  90931. return this._targetFrameRate;
  90932. },
  90933. /**
  90934. * Gets or sets the current target frame rate (60 by default)
  90935. */
  90936. set: function (value) {
  90937. this._targetFrameRate = value;
  90938. },
  90939. enumerable: true,
  90940. configurable: true
  90941. });
  90942. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90943. /**
  90944. * Gets or sets the current interval between two checks (every 2000ms by default)
  90945. */
  90946. get: function () {
  90947. return this._trackerDuration;
  90948. },
  90949. /**
  90950. * Gets or sets the current interval between two checks (every 2000ms by default)
  90951. */
  90952. set: function (value) {
  90953. this._trackerDuration = value;
  90954. },
  90955. enumerable: true,
  90956. configurable: true
  90957. });
  90958. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90959. /**
  90960. * Gets the list of active optimizations
  90961. */
  90962. get: function () {
  90963. return this._options.optimizations;
  90964. },
  90965. enumerable: true,
  90966. configurable: true
  90967. });
  90968. /**
  90969. * Stops the current optimizer
  90970. */
  90971. SceneOptimizer.prototype.stop = function () {
  90972. this._isRunning = false;
  90973. };
  90974. /**
  90975. * Reset the optimizer to initial step (current priority level = 0)
  90976. */
  90977. SceneOptimizer.prototype.reset = function () {
  90978. this._currentPriorityLevel = 0;
  90979. };
  90980. /**
  90981. * Start the optimizer. By default it will try to reach a specific framerate
  90982. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90983. */
  90984. SceneOptimizer.prototype.start = function () {
  90985. var _this = this;
  90986. if (this._isRunning) {
  90987. return;
  90988. }
  90989. this._isRunning = true;
  90990. // Let's wait for the scene to be ready before running our check
  90991. this._scene.executeWhenReady(function () {
  90992. setTimeout(function () {
  90993. _this._checkCurrentState();
  90994. }, _this._trackerDuration);
  90995. });
  90996. };
  90997. SceneOptimizer.prototype._checkCurrentState = function () {
  90998. var _this = this;
  90999. if (!this._isRunning) {
  91000. return;
  91001. }
  91002. var scene = this._scene;
  91003. var options = this._options;
  91004. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91005. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91006. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91007. this._isRunning = false;
  91008. this.onSuccessObservable.notifyObservers(this);
  91009. return;
  91010. }
  91011. // Apply current level of optimizations
  91012. var allDone = true;
  91013. var noOptimizationApplied = true;
  91014. for (var index = 0; index < options.optimizations.length; index++) {
  91015. var optimization = options.optimizations[index];
  91016. if (optimization.priority === this._currentPriorityLevel) {
  91017. noOptimizationApplied = false;
  91018. allDone = allDone && optimization.apply(scene, this);
  91019. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91020. }
  91021. }
  91022. // If no optimization was applied, this is a failure :(
  91023. if (noOptimizationApplied) {
  91024. this._isRunning = false;
  91025. this.onFailureObservable.notifyObservers(this);
  91026. return;
  91027. }
  91028. // If all optimizations were done, move to next level
  91029. if (allDone) {
  91030. this._currentPriorityLevel++;
  91031. }
  91032. // Let's the system running for a specific amount of time before checking FPS
  91033. scene.executeWhenReady(function () {
  91034. setTimeout(function () {
  91035. _this._checkCurrentState();
  91036. }, _this._trackerDuration);
  91037. });
  91038. };
  91039. /**
  91040. * Release all resources
  91041. */
  91042. SceneOptimizer.prototype.dispose = function () {
  91043. this.stop();
  91044. this.onSuccessObservable.clear();
  91045. this.onFailureObservable.clear();
  91046. this.onNewOptimizationAppliedObservable.clear();
  91047. if (this._sceneDisposeObserver) {
  91048. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91049. }
  91050. };
  91051. /**
  91052. * Helper function to create a SceneOptimizer with one single line of code
  91053. * @param scene defines the scene to work on
  91054. * @param options defines the options to use with the SceneOptimizer
  91055. * @param onSuccess defines a callback to call on success
  91056. * @param onFailure defines a callback to call on failure
  91057. * @returns the new SceneOptimizer object
  91058. */
  91059. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91060. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91061. if (onSuccess) {
  91062. optimizer.onSuccessObservable.add(function () {
  91063. onSuccess();
  91064. });
  91065. }
  91066. if (onFailure) {
  91067. optimizer.onFailureObservable.add(function () {
  91068. onFailure();
  91069. });
  91070. }
  91071. optimizer.start();
  91072. return optimizer;
  91073. };
  91074. return SceneOptimizer;
  91075. }());
  91076. BABYLON.SceneOptimizer = SceneOptimizer;
  91077. })(BABYLON || (BABYLON = {}));
  91078. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91079. var BABYLON;
  91080. (function (BABYLON) {
  91081. var OutlineRenderer = /** @class */ (function () {
  91082. function OutlineRenderer(scene) {
  91083. this.zOffset = 1;
  91084. this._scene = scene;
  91085. }
  91086. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91087. var _this = this;
  91088. if (useOverlay === void 0) { useOverlay = false; }
  91089. var scene = this._scene;
  91090. var engine = this._scene.getEngine();
  91091. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91092. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91093. return;
  91094. }
  91095. var mesh = subMesh.getRenderingMesh();
  91096. var material = subMesh.getMaterial();
  91097. if (!material || !scene.activeCamera) {
  91098. return;
  91099. }
  91100. engine.enableEffect(this._effect);
  91101. // Logarithmic depth
  91102. if (material.useLogarithmicDepth) {
  91103. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91104. }
  91105. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91106. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91107. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91108. // Bones
  91109. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91110. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91111. }
  91112. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91113. // Alpha test
  91114. if (material && material.needAlphaTesting()) {
  91115. var alphaTexture = material.getAlphaTestTexture();
  91116. if (alphaTexture) {
  91117. this._effect.setTexture("diffuseSampler", alphaTexture);
  91118. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91119. }
  91120. }
  91121. engine.setZOffset(-this.zOffset);
  91122. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91123. engine.setZOffset(0);
  91124. };
  91125. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91126. var defines = [];
  91127. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91128. var mesh = subMesh.getMesh();
  91129. var material = subMesh.getMaterial();
  91130. if (material) {
  91131. // Alpha test
  91132. if (material.needAlphaTesting()) {
  91133. defines.push("#define ALPHATEST");
  91134. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91135. attribs.push(BABYLON.VertexBuffer.UVKind);
  91136. defines.push("#define UV1");
  91137. }
  91138. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91139. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91140. defines.push("#define UV2");
  91141. }
  91142. }
  91143. //Logarithmic depth
  91144. if (material.useLogarithmicDepth) {
  91145. defines.push("#define LOGARITHMICDEPTH");
  91146. }
  91147. }
  91148. // Bones
  91149. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91150. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91151. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91152. if (mesh.numBoneInfluencers > 4) {
  91153. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91154. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91155. }
  91156. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91157. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91158. }
  91159. else {
  91160. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91161. }
  91162. // Instances
  91163. if (useInstances) {
  91164. defines.push("#define INSTANCES");
  91165. attribs.push("world0");
  91166. attribs.push("world1");
  91167. attribs.push("world2");
  91168. attribs.push("world3");
  91169. }
  91170. // Get correct effect
  91171. var join = defines.join("\n");
  91172. if (this._cachedDefines !== join) {
  91173. this._cachedDefines = join;
  91174. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91175. }
  91176. return this._effect.isReady();
  91177. };
  91178. return OutlineRenderer;
  91179. }());
  91180. BABYLON.OutlineRenderer = OutlineRenderer;
  91181. })(BABYLON || (BABYLON = {}));
  91182. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91183. var BABYLON;
  91184. (function (BABYLON) {
  91185. var FaceAdjacencies = /** @class */ (function () {
  91186. function FaceAdjacencies() {
  91187. this.edges = new Array();
  91188. this.edgesConnectedCount = 0;
  91189. }
  91190. return FaceAdjacencies;
  91191. }());
  91192. var EdgesRenderer = /** @class */ (function () {
  91193. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91194. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91195. if (epsilon === void 0) { epsilon = 0.95; }
  91196. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91197. this.edgesWidthScalerForOrthographic = 1000.0;
  91198. this.edgesWidthScalerForPerspective = 50.0;
  91199. this._linesPositions = new Array();
  91200. this._linesNormals = new Array();
  91201. this._linesIndices = new Array();
  91202. this._buffers = {};
  91203. this._checkVerticesInsteadOfIndices = false;
  91204. this._source = source;
  91205. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91206. this._epsilon = epsilon;
  91207. this._prepareRessources();
  91208. this._generateEdgesLines();
  91209. }
  91210. EdgesRenderer.prototype._prepareRessources = function () {
  91211. if (this._lineShader) {
  91212. return;
  91213. }
  91214. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91215. attributes: ["position", "normal"],
  91216. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91217. });
  91218. this._lineShader.disableDepthWrite = true;
  91219. this._lineShader.backFaceCulling = false;
  91220. };
  91221. EdgesRenderer.prototype._rebuild = function () {
  91222. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91223. if (buffer) {
  91224. buffer._rebuild();
  91225. }
  91226. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91227. if (buffer) {
  91228. buffer._rebuild();
  91229. }
  91230. var scene = this._source.getScene();
  91231. var engine = scene.getEngine();
  91232. this._ib = engine.createIndexBuffer(this._linesIndices);
  91233. };
  91234. EdgesRenderer.prototype.dispose = function () {
  91235. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91236. if (buffer) {
  91237. buffer.dispose();
  91238. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91239. }
  91240. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91241. if (buffer) {
  91242. buffer.dispose();
  91243. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91244. }
  91245. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91246. this._lineShader.dispose();
  91247. };
  91248. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91249. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91250. return 0;
  91251. }
  91252. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91253. return 1;
  91254. }
  91255. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91256. return 2;
  91257. }
  91258. return -1;
  91259. };
  91260. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91261. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91262. return 0;
  91263. }
  91264. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91265. return 1;
  91266. }
  91267. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91268. return 2;
  91269. }
  91270. return -1;
  91271. };
  91272. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91273. var needToCreateLine;
  91274. if (edge === undefined) {
  91275. needToCreateLine = true;
  91276. }
  91277. else {
  91278. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91279. needToCreateLine = dotProduct < this._epsilon;
  91280. }
  91281. if (needToCreateLine) {
  91282. var offset = this._linesPositions.length / 3;
  91283. var normal = p0.subtract(p1);
  91284. normal.normalize();
  91285. // Positions
  91286. this._linesPositions.push(p0.x);
  91287. this._linesPositions.push(p0.y);
  91288. this._linesPositions.push(p0.z);
  91289. this._linesPositions.push(p0.x);
  91290. this._linesPositions.push(p0.y);
  91291. this._linesPositions.push(p0.z);
  91292. this._linesPositions.push(p1.x);
  91293. this._linesPositions.push(p1.y);
  91294. this._linesPositions.push(p1.z);
  91295. this._linesPositions.push(p1.x);
  91296. this._linesPositions.push(p1.y);
  91297. this._linesPositions.push(p1.z);
  91298. // Normals
  91299. this._linesNormals.push(p1.x);
  91300. this._linesNormals.push(p1.y);
  91301. this._linesNormals.push(p1.z);
  91302. this._linesNormals.push(-1);
  91303. this._linesNormals.push(p1.x);
  91304. this._linesNormals.push(p1.y);
  91305. this._linesNormals.push(p1.z);
  91306. this._linesNormals.push(1);
  91307. this._linesNormals.push(p0.x);
  91308. this._linesNormals.push(p0.y);
  91309. this._linesNormals.push(p0.z);
  91310. this._linesNormals.push(-1);
  91311. this._linesNormals.push(p0.x);
  91312. this._linesNormals.push(p0.y);
  91313. this._linesNormals.push(p0.z);
  91314. this._linesNormals.push(1);
  91315. // Indices
  91316. this._linesIndices.push(offset);
  91317. this._linesIndices.push(offset + 1);
  91318. this._linesIndices.push(offset + 2);
  91319. this._linesIndices.push(offset);
  91320. this._linesIndices.push(offset + 2);
  91321. this._linesIndices.push(offset + 3);
  91322. }
  91323. };
  91324. EdgesRenderer.prototype._generateEdgesLines = function () {
  91325. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91326. var indices = this._source.getIndices();
  91327. if (!indices || !positions) {
  91328. return;
  91329. }
  91330. // First let's find adjacencies
  91331. var adjacencies = new Array();
  91332. var faceNormals = new Array();
  91333. var index;
  91334. var faceAdjacencies;
  91335. // Prepare faces
  91336. for (index = 0; index < indices.length; index += 3) {
  91337. faceAdjacencies = new FaceAdjacencies();
  91338. var p0Index = indices[index];
  91339. var p1Index = indices[index + 1];
  91340. var p2Index = indices[index + 2];
  91341. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91342. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91343. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91344. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91345. faceNormal.normalize();
  91346. faceNormals.push(faceNormal);
  91347. adjacencies.push(faceAdjacencies);
  91348. }
  91349. // Scan
  91350. for (index = 0; index < adjacencies.length; index++) {
  91351. faceAdjacencies = adjacencies[index];
  91352. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91353. var otherFaceAdjacencies = adjacencies[otherIndex];
  91354. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91355. break;
  91356. }
  91357. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91358. continue;
  91359. }
  91360. var otherP0 = indices[otherIndex * 3];
  91361. var otherP1 = indices[otherIndex * 3 + 1];
  91362. var otherP2 = indices[otherIndex * 3 + 2];
  91363. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91364. var otherEdgeIndex = 0;
  91365. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91366. continue;
  91367. }
  91368. switch (edgeIndex) {
  91369. case 0:
  91370. if (this._checkVerticesInsteadOfIndices) {
  91371. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91372. }
  91373. else {
  91374. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91375. }
  91376. break;
  91377. case 1:
  91378. if (this._checkVerticesInsteadOfIndices) {
  91379. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91380. }
  91381. else {
  91382. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91383. }
  91384. break;
  91385. case 2:
  91386. if (this._checkVerticesInsteadOfIndices) {
  91387. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91388. }
  91389. else {
  91390. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91391. }
  91392. break;
  91393. }
  91394. if (otherEdgeIndex === -1) {
  91395. continue;
  91396. }
  91397. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91398. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91399. faceAdjacencies.edgesConnectedCount++;
  91400. otherFaceAdjacencies.edgesConnectedCount++;
  91401. if (faceAdjacencies.edgesConnectedCount === 3) {
  91402. break;
  91403. }
  91404. }
  91405. }
  91406. }
  91407. // Create lines
  91408. for (index = 0; index < adjacencies.length; index++) {
  91409. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  91410. var current = adjacencies[index];
  91411. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91412. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91413. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91414. }
  91415. // Merge into a single mesh
  91416. var engine = this._source.getScene().getEngine();
  91417. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91418. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91419. this._ib = engine.createIndexBuffer(this._linesIndices);
  91420. this._indicesCount = this._linesIndices.length;
  91421. };
  91422. EdgesRenderer.prototype.render = function () {
  91423. var scene = this._source.getScene();
  91424. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91425. return;
  91426. }
  91427. var engine = scene.getEngine();
  91428. this._lineShader._preBind();
  91429. // VBOs
  91430. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91431. scene.resetCachedMaterial();
  91432. this._lineShader.setColor4("color", this._source.edgesColor);
  91433. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91434. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91435. }
  91436. else {
  91437. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91438. }
  91439. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91440. this._lineShader.bind(this._source.getWorldMatrix());
  91441. // Draw order
  91442. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91443. this._lineShader.unbind();
  91444. engine.setDepthWrite(true);
  91445. };
  91446. return EdgesRenderer;
  91447. }());
  91448. BABYLON.EdgesRenderer = EdgesRenderer;
  91449. })(BABYLON || (BABYLON = {}));
  91450. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91451. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91452. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91453. s = arguments[i];
  91454. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91455. t[p] = s[p];
  91456. }
  91457. return t;
  91458. };
  91459. var BABYLON;
  91460. (function (BABYLON) {
  91461. /**
  91462. * The effect layer Helps adding post process effect blended with the main pass.
  91463. *
  91464. * This can be for instance use to generate glow or higlight effects on the scene.
  91465. *
  91466. * The effect layer class can not be used directly and is intented to inherited from to be
  91467. * customized per effects.
  91468. */
  91469. var EffectLayer = /** @class */ (function () {
  91470. /**
  91471. * Instantiates a new effect Layer and references it in the scene.
  91472. * @param name The name of the layer
  91473. * @param scene The scene to use the layer in
  91474. */
  91475. function EffectLayer(
  91476. /** The Friendly of the effect in the scene */
  91477. name, scene) {
  91478. this._vertexBuffers = {};
  91479. this._maxSize = 0;
  91480. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91481. this._shouldRender = true;
  91482. this._postProcesses = [];
  91483. this._textures = [];
  91484. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91485. /**
  91486. * The clear color of the texture used to generate the glow map.
  91487. */
  91488. this.neutralColor = new BABYLON.Color4();
  91489. /**
  91490. * Specifies wether the highlight layer is enabled or not.
  91491. */
  91492. this.isEnabled = true;
  91493. /**
  91494. * An event triggered when the effect layer has been disposed.
  91495. */
  91496. this.onDisposeObservable = new BABYLON.Observable();
  91497. /**
  91498. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91499. */
  91500. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91501. /**
  91502. * An event triggered when the generated texture is being merged in the scene.
  91503. */
  91504. this.onBeforeComposeObservable = new BABYLON.Observable();
  91505. /**
  91506. * An event triggered when the generated texture has been merged in the scene.
  91507. */
  91508. this.onAfterComposeObservable = new BABYLON.Observable();
  91509. /**
  91510. * An event triggered when the efffect layer changes its size.
  91511. */
  91512. this.onSizeChangedObservable = new BABYLON.Observable();
  91513. this.name = name;
  91514. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91515. this._engine = scene.getEngine();
  91516. this._maxSize = this._engine.getCaps().maxTextureSize;
  91517. this._scene.effectLayers.push(this);
  91518. // Generate Buffers
  91519. this._generateIndexBuffer();
  91520. this._genrateVertexBuffer();
  91521. }
  91522. Object.defineProperty(EffectLayer.prototype, "camera", {
  91523. /**
  91524. * Gets the camera attached to the layer.
  91525. */
  91526. get: function () {
  91527. return this._effectLayerOptions.camera;
  91528. },
  91529. enumerable: true,
  91530. configurable: true
  91531. });
  91532. /**
  91533. * Initializes the effect layer with the required options.
  91534. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91535. */
  91536. EffectLayer.prototype._init = function (options) {
  91537. // Adapt options
  91538. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91539. this._setMainTextureSize();
  91540. this._createMainTexture();
  91541. this._createTextureAndPostProcesses();
  91542. this._mergeEffect = this._createMergeEffect();
  91543. };
  91544. /**
  91545. * Generates the index buffer of the full screen quad blending to the main canvas.
  91546. */
  91547. EffectLayer.prototype._generateIndexBuffer = function () {
  91548. // Indices
  91549. var indices = [];
  91550. indices.push(0);
  91551. indices.push(1);
  91552. indices.push(2);
  91553. indices.push(0);
  91554. indices.push(2);
  91555. indices.push(3);
  91556. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91557. };
  91558. /**
  91559. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91560. */
  91561. EffectLayer.prototype._genrateVertexBuffer = function () {
  91562. // VBO
  91563. var vertices = [];
  91564. vertices.push(1, 1);
  91565. vertices.push(-1, 1);
  91566. vertices.push(-1, -1);
  91567. vertices.push(1, -1);
  91568. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91569. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91570. };
  91571. /**
  91572. * Sets the main texture desired size which is the closest power of two
  91573. * of the engine canvas size.
  91574. */
  91575. EffectLayer.prototype._setMainTextureSize = function () {
  91576. if (this._effectLayerOptions.mainTextureFixedSize) {
  91577. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91578. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91579. }
  91580. else {
  91581. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91582. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91583. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91584. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91585. }
  91586. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91587. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91588. };
  91589. /**
  91590. * Creates the main texture for the effect layer.
  91591. */
  91592. EffectLayer.prototype._createMainTexture = function () {
  91593. var _this = this;
  91594. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91595. width: this._mainTextureDesiredSize.width,
  91596. height: this._mainTextureDesiredSize.height
  91597. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91598. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91599. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91600. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91601. this._mainTexture.anisotropicFilteringLevel = 1;
  91602. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91603. this._mainTexture.renderParticles = false;
  91604. this._mainTexture.renderList = null;
  91605. this._mainTexture.ignoreCameraViewport = true;
  91606. // Custom render function
  91607. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91608. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91609. var index;
  91610. var engine = _this._scene.getEngine();
  91611. if (depthOnlySubMeshes.length) {
  91612. engine.setColorWrite(false);
  91613. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91614. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91615. }
  91616. engine.setColorWrite(true);
  91617. }
  91618. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91619. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91620. }
  91621. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91622. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91623. }
  91624. for (index = 0; index < transparentSubMeshes.length; index++) {
  91625. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91626. }
  91627. };
  91628. this._mainTexture.onClearObservable.add(function (engine) {
  91629. engine.clear(_this.neutralColor, true, true, true);
  91630. });
  91631. };
  91632. /**
  91633. * Checks for the readiness of the element composing the layer.
  91634. * @param subMesh the mesh to check for
  91635. * @param useInstances specify wether or not to use instances to render the mesh
  91636. * @param emissiveTexture the associated emissive texture used to generate the glow
  91637. * @return true if ready otherwise, false
  91638. */
  91639. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91640. var material = subMesh.getMaterial();
  91641. if (!material) {
  91642. return false;
  91643. }
  91644. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91645. return false;
  91646. }
  91647. var defines = [];
  91648. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91649. var mesh = subMesh.getMesh();
  91650. var uv1 = false;
  91651. var uv2 = false;
  91652. // Alpha test
  91653. if (material && material.needAlphaTesting()) {
  91654. var alphaTexture = material.getAlphaTestTexture();
  91655. if (alphaTexture) {
  91656. defines.push("#define ALPHATEST");
  91657. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91658. alphaTexture.coordinatesIndex === 1) {
  91659. defines.push("#define DIFFUSEUV2");
  91660. uv2 = true;
  91661. }
  91662. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91663. defines.push("#define DIFFUSEUV1");
  91664. uv1 = true;
  91665. }
  91666. }
  91667. }
  91668. // Emissive
  91669. if (emissiveTexture) {
  91670. defines.push("#define EMISSIVE");
  91671. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91672. emissiveTexture.coordinatesIndex === 1) {
  91673. defines.push("#define EMISSIVEUV2");
  91674. uv2 = true;
  91675. }
  91676. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91677. defines.push("#define EMISSIVEUV1");
  91678. uv1 = true;
  91679. }
  91680. }
  91681. if (uv1) {
  91682. attribs.push(BABYLON.VertexBuffer.UVKind);
  91683. defines.push("#define UV1");
  91684. }
  91685. if (uv2) {
  91686. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91687. defines.push("#define UV2");
  91688. }
  91689. // Bones
  91690. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91691. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91692. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91693. if (mesh.numBoneInfluencers > 4) {
  91694. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91695. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91696. }
  91697. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91698. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91699. }
  91700. else {
  91701. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91702. }
  91703. // Morph targets
  91704. var manager = mesh.morphTargetManager;
  91705. var morphInfluencers = 0;
  91706. if (manager) {
  91707. if (manager.numInfluencers > 0) {
  91708. defines.push("#define MORPHTARGETS");
  91709. morphInfluencers = manager.numInfluencers;
  91710. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91711. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91712. }
  91713. }
  91714. // Instances
  91715. if (useInstances) {
  91716. defines.push("#define INSTANCES");
  91717. attribs.push("world0");
  91718. attribs.push("world1");
  91719. attribs.push("world2");
  91720. attribs.push("world3");
  91721. }
  91722. // Get correct effect
  91723. var join = defines.join("\n");
  91724. if (this._cachedDefines !== join) {
  91725. this._cachedDefines = join;
  91726. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91727. }
  91728. return this._effectLayerMapGenerationEffect.isReady();
  91729. };
  91730. /**
  91731. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91732. */
  91733. EffectLayer.prototype.render = function () {
  91734. var currentEffect = this._mergeEffect;
  91735. // Check
  91736. if (!currentEffect.isReady())
  91737. return;
  91738. for (var i = 0; i < this._postProcesses.length; i++) {
  91739. if (!this._postProcesses[i].isReady()) {
  91740. return;
  91741. }
  91742. }
  91743. var engine = this._scene.getEngine();
  91744. this.onBeforeComposeObservable.notifyObservers(this);
  91745. // Render
  91746. engine.enableEffect(currentEffect);
  91747. engine.setState(false);
  91748. // VBOs
  91749. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91750. // Cache
  91751. var previousAlphaMode = engine.getAlphaMode();
  91752. // Go Blend.
  91753. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91754. // Blends the map on the main canvas.
  91755. this._internalRender(currentEffect);
  91756. // Restore Alpha
  91757. engine.setAlphaMode(previousAlphaMode);
  91758. this.onAfterComposeObservable.notifyObservers(this);
  91759. // Handle size changes.
  91760. var size = this._mainTexture.getSize();
  91761. this._setMainTextureSize();
  91762. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91763. // Recreate RTT and post processes on size change.
  91764. this.onSizeChangedObservable.notifyObservers(this);
  91765. this._disposeTextureAndPostProcesses();
  91766. this._createMainTexture();
  91767. this._createTextureAndPostProcesses();
  91768. }
  91769. };
  91770. /**
  91771. * Determine if a given mesh will be used in the current effect.
  91772. * @param mesh mesh to test
  91773. * @returns true if the mesh will be used
  91774. */
  91775. EffectLayer.prototype.hasMesh = function (mesh) {
  91776. return true;
  91777. };
  91778. /**
  91779. * Returns true if the layer contains information to display, otherwise false.
  91780. * @returns true if the glow layer should be rendered
  91781. */
  91782. EffectLayer.prototype.shouldRender = function () {
  91783. return this.isEnabled && this._shouldRender;
  91784. };
  91785. /**
  91786. * Returns true if the mesh should render, otherwise false.
  91787. * @param mesh The mesh to render
  91788. * @returns true if it should render otherwise false
  91789. */
  91790. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91791. return true;
  91792. };
  91793. /**
  91794. * Returns true if the mesh should render, otherwise false.
  91795. * @param mesh The mesh to render
  91796. * @returns true if it should render otherwise false
  91797. */
  91798. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91799. return true;
  91800. };
  91801. /**
  91802. * Renders the submesh passed in parameter to the generation map.
  91803. */
  91804. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91805. var _this = this;
  91806. if (!this.shouldRender()) {
  91807. return;
  91808. }
  91809. var material = subMesh.getMaterial();
  91810. var mesh = subMesh.getRenderingMesh();
  91811. var scene = this._scene;
  91812. var engine = scene.getEngine();
  91813. if (!material) {
  91814. return;
  91815. }
  91816. // Do not block in blend mode.
  91817. if (material.needAlphaBlendingForMesh(mesh)) {
  91818. return;
  91819. }
  91820. // Culling
  91821. engine.setState(material.backFaceCulling);
  91822. // Managing instances
  91823. var batch = mesh._getInstancesRenderList(subMesh._id);
  91824. if (batch.mustReturn) {
  91825. return;
  91826. }
  91827. // Early Exit per mesh
  91828. if (!this._shouldRenderMesh(mesh)) {
  91829. return;
  91830. }
  91831. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91832. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91833. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91834. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91835. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91836. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91837. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91838. // Alpha test
  91839. if (material && material.needAlphaTesting()) {
  91840. var alphaTexture = material.getAlphaTestTexture();
  91841. if (alphaTexture) {
  91842. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91843. var textureMatrix = alphaTexture.getTextureMatrix();
  91844. if (textureMatrix) {
  91845. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91846. }
  91847. }
  91848. }
  91849. // Glow emissive only
  91850. if (this._emissiveTextureAndColor.texture) {
  91851. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91852. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91853. }
  91854. // Bones
  91855. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91856. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91857. }
  91858. // Morph targets
  91859. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91860. // Draw
  91861. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91862. }
  91863. else {
  91864. // Need to reset refresh rate of the shadowMap
  91865. this._mainTexture.resetRefreshCounter();
  91866. }
  91867. };
  91868. /**
  91869. * Rebuild the required buffers.
  91870. * @hidden Internal use only.
  91871. */
  91872. EffectLayer.prototype._rebuild = function () {
  91873. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91874. if (vb) {
  91875. vb._rebuild();
  91876. }
  91877. this._generateIndexBuffer();
  91878. };
  91879. /**
  91880. * Dispose only the render target textures and post process.
  91881. */
  91882. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91883. this._mainTexture.dispose();
  91884. for (var i = 0; i < this._postProcesses.length; i++) {
  91885. if (this._postProcesses[i]) {
  91886. this._postProcesses[i].dispose();
  91887. }
  91888. }
  91889. this._postProcesses = [];
  91890. for (var i = 0; i < this._textures.length; i++) {
  91891. if (this._textures[i]) {
  91892. this._textures[i].dispose();
  91893. }
  91894. }
  91895. this._textures = [];
  91896. };
  91897. /**
  91898. * Dispose the highlight layer and free resources.
  91899. */
  91900. EffectLayer.prototype.dispose = function () {
  91901. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91902. if (vertexBuffer) {
  91903. vertexBuffer.dispose();
  91904. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91905. }
  91906. if (this._indexBuffer) {
  91907. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91908. this._indexBuffer = null;
  91909. }
  91910. // Clean textures and post processes
  91911. this._disposeTextureAndPostProcesses();
  91912. // Remove from scene
  91913. var index = this._scene.effectLayers.indexOf(this, 0);
  91914. if (index > -1) {
  91915. this._scene.effectLayers.splice(index, 1);
  91916. }
  91917. // Callback
  91918. this.onDisposeObservable.notifyObservers(this);
  91919. this.onDisposeObservable.clear();
  91920. this.onBeforeRenderMainTextureObservable.clear();
  91921. this.onBeforeComposeObservable.clear();
  91922. this.onAfterComposeObservable.clear();
  91923. this.onSizeChangedObservable.clear();
  91924. };
  91925. /**
  91926. * Gets the class name of the effect layer
  91927. * @returns the string with the class name of the effect layer
  91928. */
  91929. EffectLayer.prototype.getClassName = function () {
  91930. return "EffectLayer";
  91931. };
  91932. /**
  91933. * Creates an effect layer from parsed effect layer data
  91934. * @param parsedEffectLayer defines effect layer data
  91935. * @param scene defines the current scene
  91936. * @param rootUrl defines the root URL containing the effect layer information
  91937. * @returns a parsed effect Layer
  91938. */
  91939. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91940. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91941. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91942. };
  91943. __decorate([
  91944. BABYLON.serialize()
  91945. ], EffectLayer.prototype, "name", void 0);
  91946. __decorate([
  91947. BABYLON.serializeAsColor4()
  91948. ], EffectLayer.prototype, "neutralColor", void 0);
  91949. __decorate([
  91950. BABYLON.serialize()
  91951. ], EffectLayer.prototype, "isEnabled", void 0);
  91952. __decorate([
  91953. BABYLON.serializeAsCameraReference()
  91954. ], EffectLayer.prototype, "camera", null);
  91955. return EffectLayer;
  91956. }());
  91957. BABYLON.EffectLayer = EffectLayer;
  91958. })(BABYLON || (BABYLON = {}));
  91959. //# sourceMappingURL=babylon.effectLayer.js.map
  91960. var BABYLON;
  91961. (function (BABYLON) {
  91962. /**
  91963. * Special Glow Blur post process only blurring the alpha channel
  91964. * It enforces keeping the most luminous color in the color channel.
  91965. */
  91966. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91967. __extends(GlowBlurPostProcess, _super);
  91968. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91970. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91971. _this.direction = direction;
  91972. _this.kernel = kernel;
  91973. _this.onApplyObservable.add(function (effect) {
  91974. effect.setFloat2("screenSize", _this.width, _this.height);
  91975. effect.setVector2("direction", _this.direction);
  91976. effect.setFloat("blurWidth", _this.kernel);
  91977. });
  91978. return _this;
  91979. }
  91980. return GlowBlurPostProcess;
  91981. }(BABYLON.PostProcess));
  91982. /**
  91983. * The highlight layer Helps adding a glow effect around a mesh.
  91984. *
  91985. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91986. * glowy meshes to your scene.
  91987. *
  91988. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91989. */
  91990. var HighlightLayer = /** @class */ (function (_super) {
  91991. __extends(HighlightLayer, _super);
  91992. /**
  91993. * Instantiates a new highlight Layer and references it to the scene..
  91994. * @param name The name of the layer
  91995. * @param scene The scene to use the layer in
  91996. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91997. */
  91998. function HighlightLayer(name, scene, options) {
  91999. var _this = _super.call(this, name, scene) || this;
  92000. _this.name = name;
  92001. /**
  92002. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92003. */
  92004. _this.innerGlow = true;
  92005. /**
  92006. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92007. */
  92008. _this.outerGlow = true;
  92009. /**
  92010. * An event triggered when the highlight layer is being blurred.
  92011. */
  92012. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92013. /**
  92014. * An event triggered when the highlight layer has been blurred.
  92015. */
  92016. _this.onAfterBlurObservable = new BABYLON.Observable();
  92017. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92018. _this._meshes = {};
  92019. _this._excludedMeshes = {};
  92020. _this.neutralColor = HighlightLayer.NeutralColor;
  92021. // Warn on stencil
  92022. if (!_this._engine.isStencilEnable) {
  92023. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  92024. }
  92025. // Adapt options
  92026. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92027. // Initialize the layer
  92028. _this._init({
  92029. alphaBlendingMode: _this._options.alphaBlendingMode,
  92030. camera: _this._options.camera,
  92031. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92032. mainTextureRatio: _this._options.mainTextureRatio
  92033. });
  92034. // Do not render as long as no meshes have been added
  92035. _this._shouldRender = false;
  92036. return _this;
  92037. }
  92038. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92039. /**
  92040. * Gets the horizontal size of the blur.
  92041. */
  92042. get: function () {
  92043. return this._horizontalBlurPostprocess.kernel;
  92044. },
  92045. /**
  92046. * Specifies the horizontal size of the blur.
  92047. */
  92048. set: function (value) {
  92049. this._horizontalBlurPostprocess.kernel = value;
  92050. },
  92051. enumerable: true,
  92052. configurable: true
  92053. });
  92054. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92055. /**
  92056. * Gets the vertical size of the blur.
  92057. */
  92058. get: function () {
  92059. return this._verticalBlurPostprocess.kernel;
  92060. },
  92061. /**
  92062. * Specifies the vertical size of the blur.
  92063. */
  92064. set: function (value) {
  92065. this._verticalBlurPostprocess.kernel = value;
  92066. },
  92067. enumerable: true,
  92068. configurable: true
  92069. });
  92070. /**
  92071. * Get the effect name of the layer.
  92072. * @return The effect name
  92073. */
  92074. HighlightLayer.prototype.getEffectName = function () {
  92075. return HighlightLayer.EffectName;
  92076. };
  92077. /**
  92078. * Create the merge effect. This is the shader use to blit the information back
  92079. * to the main canvas at the end of the scene rendering.
  92080. */
  92081. HighlightLayer.prototype._createMergeEffect = function () {
  92082. // Effect
  92083. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92084. };
  92085. /**
  92086. * Creates the render target textures and post processes used in the highlight layer.
  92087. */
  92088. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92089. var _this = this;
  92090. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92091. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92092. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92093. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92094. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92095. width: blurTextureWidth,
  92096. height: blurTextureHeight
  92097. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92098. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92099. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92100. this._blurTexture.anisotropicFilteringLevel = 16;
  92101. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92102. this._blurTexture.renderParticles = false;
  92103. this._blurTexture.ignoreCameraViewport = true;
  92104. this._textures = [this._blurTexture];
  92105. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92106. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92107. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92108. effect.setTexture("textureSampler", _this._mainTexture);
  92109. });
  92110. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92111. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92112. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92113. });
  92114. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92115. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92116. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92117. });
  92118. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92119. }
  92120. else {
  92121. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92122. width: blurTextureWidth,
  92123. height: blurTextureHeight
  92124. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92125. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92126. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92127. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92128. effect.setTexture("textureSampler", _this._mainTexture);
  92129. });
  92130. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92131. width: blurTextureWidth,
  92132. height: blurTextureHeight
  92133. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92134. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92135. }
  92136. this._mainTexture.onAfterUnbindObservable.add(function () {
  92137. _this.onBeforeBlurObservable.notifyObservers(_this);
  92138. var internalTexture = _this._blurTexture.getInternalTexture();
  92139. if (internalTexture) {
  92140. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92141. }
  92142. _this.onAfterBlurObservable.notifyObservers(_this);
  92143. });
  92144. // Prevent autoClear.
  92145. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92146. };
  92147. /**
  92148. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92149. */
  92150. HighlightLayer.prototype.needStencil = function () {
  92151. return true;
  92152. };
  92153. /**
  92154. * Checks for the readiness of the element composing the layer.
  92155. * @param subMesh the mesh to check for
  92156. * @param useInstances specify wether or not to use instances to render the mesh
  92157. * @param emissiveTexture the associated emissive texture used to generate the glow
  92158. * @return true if ready otherwise, false
  92159. */
  92160. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92161. var material = subMesh.getMaterial();
  92162. var mesh = subMesh.getRenderingMesh();
  92163. if (!material || !mesh || !this._meshes) {
  92164. return false;
  92165. }
  92166. var emissiveTexture = null;
  92167. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92168. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92169. emissiveTexture = material.emissiveTexture;
  92170. }
  92171. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92172. };
  92173. /**
  92174. * Implementation specific of rendering the generating effect on the main canvas.
  92175. * @param effect The effect used to render through
  92176. */
  92177. HighlightLayer.prototype._internalRender = function (effect) {
  92178. // Texture
  92179. effect.setTexture("textureSampler", this._blurTexture);
  92180. // Cache
  92181. var engine = this._engine;
  92182. var previousStencilBuffer = engine.getStencilBuffer();
  92183. var previousStencilFunction = engine.getStencilFunction();
  92184. var previousStencilMask = engine.getStencilMask();
  92185. var previousStencilOperationPass = engine.getStencilOperationPass();
  92186. var previousStencilOperationFail = engine.getStencilOperationFail();
  92187. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92188. var previousStencilReference = engine.getStencilFunctionReference();
  92189. // Stencil operations
  92190. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92191. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92192. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92193. // Draw order
  92194. engine.setStencilMask(0x00);
  92195. engine.setStencilBuffer(true);
  92196. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92197. // 2 passes inner outer
  92198. if (this.outerGlow) {
  92199. effect.setFloat("offset", 0);
  92200. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92201. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92202. }
  92203. if (this.innerGlow) {
  92204. effect.setFloat("offset", 1);
  92205. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92206. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92207. }
  92208. // Restore Cache
  92209. engine.setStencilFunction(previousStencilFunction);
  92210. engine.setStencilMask(previousStencilMask);
  92211. engine.setStencilBuffer(previousStencilBuffer);
  92212. engine.setStencilOperationPass(previousStencilOperationPass);
  92213. engine.setStencilOperationFail(previousStencilOperationFail);
  92214. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92215. engine.setStencilFunctionReference(previousStencilReference);
  92216. };
  92217. /**
  92218. * Returns true if the layer contains information to display, otherwise false.
  92219. */
  92220. HighlightLayer.prototype.shouldRender = function () {
  92221. if (_super.prototype.shouldRender.call(this)) {
  92222. return this._meshes ? true : false;
  92223. }
  92224. return false;
  92225. };
  92226. /**
  92227. * Returns true if the mesh should render, otherwise false.
  92228. * @param mesh The mesh to render
  92229. * @returns true if it should render otherwise false
  92230. */
  92231. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92232. // Excluded Mesh
  92233. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92234. return false;
  92235. }
  92236. ;
  92237. return true;
  92238. };
  92239. /**
  92240. * Sets the required values for both the emissive texture and and the main color.
  92241. */
  92242. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92243. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92244. if (highlightLayerMesh) {
  92245. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92246. }
  92247. else {
  92248. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92249. }
  92250. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92251. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92252. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92253. }
  92254. else {
  92255. this._emissiveTextureAndColor.texture = null;
  92256. }
  92257. };
  92258. /**
  92259. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92260. * @param mesh The mesh to exclude from the highlight layer
  92261. */
  92262. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92263. if (!this._excludedMeshes) {
  92264. return;
  92265. }
  92266. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92267. if (!meshExcluded) {
  92268. this._excludedMeshes[mesh.uniqueId] = {
  92269. mesh: mesh,
  92270. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92271. mesh.getEngine().setStencilBuffer(false);
  92272. }),
  92273. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92274. mesh.getEngine().setStencilBuffer(true);
  92275. }),
  92276. };
  92277. }
  92278. };
  92279. /**
  92280. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92281. * @param mesh The mesh to highlight
  92282. */
  92283. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92284. if (!this._excludedMeshes) {
  92285. return;
  92286. }
  92287. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92288. if (meshExcluded) {
  92289. if (meshExcluded.beforeRender) {
  92290. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92291. }
  92292. if (meshExcluded.afterRender) {
  92293. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92294. }
  92295. }
  92296. this._excludedMeshes[mesh.uniqueId] = null;
  92297. };
  92298. /**
  92299. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92300. * @param mesh mesh to test
  92301. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92302. */
  92303. HighlightLayer.prototype.hasMesh = function (mesh) {
  92304. if (!this._meshes) {
  92305. return false;
  92306. }
  92307. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92308. };
  92309. /**
  92310. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92311. * @param mesh The mesh to highlight
  92312. * @param color The color of the highlight
  92313. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92314. */
  92315. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92316. var _this = this;
  92317. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92318. if (!this._meshes) {
  92319. return;
  92320. }
  92321. var meshHighlight = this._meshes[mesh.uniqueId];
  92322. if (meshHighlight) {
  92323. meshHighlight.color = color;
  92324. }
  92325. else {
  92326. this._meshes[mesh.uniqueId] = {
  92327. mesh: mesh,
  92328. color: color,
  92329. // Lambda required for capture due to Observable this context
  92330. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92331. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92332. _this._defaultStencilReference(mesh);
  92333. }
  92334. else {
  92335. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92336. }
  92337. }),
  92338. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92339. glowEmissiveOnly: glowEmissiveOnly
  92340. };
  92341. }
  92342. this._shouldRender = true;
  92343. };
  92344. /**
  92345. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92346. * @param mesh The mesh to highlight
  92347. */
  92348. HighlightLayer.prototype.removeMesh = function (mesh) {
  92349. if (!this._meshes) {
  92350. return;
  92351. }
  92352. var meshHighlight = this._meshes[mesh.uniqueId];
  92353. if (meshHighlight) {
  92354. if (meshHighlight.observerHighlight) {
  92355. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92356. }
  92357. if (meshHighlight.observerDefault) {
  92358. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92359. }
  92360. delete this._meshes[mesh.uniqueId];
  92361. }
  92362. this._shouldRender = false;
  92363. for (var meshHighlightToCheck in this._meshes) {
  92364. if (this._meshes[meshHighlightToCheck]) {
  92365. this._shouldRender = true;
  92366. break;
  92367. }
  92368. }
  92369. };
  92370. /**
  92371. * Force the stencil to the normal expected value for none glowing parts
  92372. */
  92373. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92374. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92375. };
  92376. /**
  92377. * Free any resources and references associated to a mesh.
  92378. * Internal use
  92379. * @param mesh The mesh to free.
  92380. */
  92381. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92382. this.removeMesh(mesh);
  92383. this.removeExcludedMesh(mesh);
  92384. };
  92385. /**
  92386. * Dispose the highlight layer and free resources.
  92387. */
  92388. HighlightLayer.prototype.dispose = function () {
  92389. if (this._meshes) {
  92390. // Clean mesh references
  92391. for (var id in this._meshes) {
  92392. var meshHighlight = this._meshes[id];
  92393. if (meshHighlight && meshHighlight.mesh) {
  92394. if (meshHighlight.observerHighlight) {
  92395. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92396. }
  92397. if (meshHighlight.observerDefault) {
  92398. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92399. }
  92400. }
  92401. }
  92402. this._meshes = null;
  92403. }
  92404. if (this._excludedMeshes) {
  92405. for (var id in this._excludedMeshes) {
  92406. var meshHighlight = this._excludedMeshes[id];
  92407. if (meshHighlight) {
  92408. if (meshHighlight.beforeRender) {
  92409. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92410. }
  92411. if (meshHighlight.afterRender) {
  92412. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92413. }
  92414. }
  92415. }
  92416. this._excludedMeshes = null;
  92417. }
  92418. _super.prototype.dispose.call(this);
  92419. };
  92420. /**
  92421. * Gets the class name of the effect layer
  92422. * @returns the string with the class name of the effect layer
  92423. */
  92424. HighlightLayer.prototype.getClassName = function () {
  92425. return "HighlightLayer";
  92426. };
  92427. /**
  92428. * Serializes this Highlight layer
  92429. * @returns a serialized Highlight layer object
  92430. */
  92431. HighlightLayer.prototype.serialize = function () {
  92432. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92433. serializationObject.customType = "BABYLON.HighlightLayer";
  92434. // Highlighted meshes
  92435. serializationObject.meshes = [];
  92436. if (this._meshes) {
  92437. for (var m in this._meshes) {
  92438. var mesh = this._meshes[m];
  92439. if (mesh) {
  92440. serializationObject.meshes.push({
  92441. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92442. color: mesh.color.asArray(),
  92443. meshId: mesh.mesh.id
  92444. });
  92445. }
  92446. }
  92447. }
  92448. // Excluded meshes
  92449. serializationObject.excludedMeshes = [];
  92450. if (this._excludedMeshes) {
  92451. for (var e in this._excludedMeshes) {
  92452. var excludedMesh = this._excludedMeshes[e];
  92453. if (excludedMesh) {
  92454. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92455. }
  92456. }
  92457. }
  92458. return serializationObject;
  92459. };
  92460. /**
  92461. * Creates a Highlight layer from parsed Highlight layer data
  92462. * @param parsedHightlightLayer defines the Highlight layer data
  92463. * @param scene defines the current scene
  92464. * @param rootUrl defines the root URL containing the Highlight layer information
  92465. * @returns a parsed Highlight layer
  92466. */
  92467. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92468. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92469. var index;
  92470. // Excluded meshes
  92471. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92472. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92473. if (mesh) {
  92474. hl.addExcludedMesh(mesh);
  92475. }
  92476. }
  92477. // Included meshes
  92478. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92479. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92480. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92481. if (mesh) {
  92482. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92483. }
  92484. }
  92485. return hl;
  92486. };
  92487. /**
  92488. * Effect Name of the highlight layer.
  92489. */
  92490. HighlightLayer.EffectName = "HighlightLayer";
  92491. /**
  92492. * The neutral color used during the preparation of the glow effect.
  92493. * This is black by default as the blend operation is a blend operation.
  92494. */
  92495. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92496. /**
  92497. * Stencil value used for glowing meshes.
  92498. */
  92499. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92500. /**
  92501. * Stencil value used for the other meshes in the scene.
  92502. */
  92503. HighlightLayer.NormalMeshStencilReference = 0x01;
  92504. __decorate([
  92505. BABYLON.serialize()
  92506. ], HighlightLayer.prototype, "innerGlow", void 0);
  92507. __decorate([
  92508. BABYLON.serialize()
  92509. ], HighlightLayer.prototype, "outerGlow", void 0);
  92510. __decorate([
  92511. BABYLON.serialize()
  92512. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92513. __decorate([
  92514. BABYLON.serialize()
  92515. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92516. __decorate([
  92517. BABYLON.serialize("options")
  92518. ], HighlightLayer.prototype, "_options", void 0);
  92519. return HighlightLayer;
  92520. }(BABYLON.EffectLayer));
  92521. BABYLON.HighlightLayer = HighlightLayer;
  92522. })(BABYLON || (BABYLON = {}));
  92523. //# sourceMappingURL=babylon.highlightLayer.js.map
  92524. var BABYLON;
  92525. (function (BABYLON) {
  92526. /**
  92527. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92528. *
  92529. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92530. * glowy meshes to your scene.
  92531. *
  92532. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92533. */
  92534. var GlowLayer = /** @class */ (function (_super) {
  92535. __extends(GlowLayer, _super);
  92536. /**
  92537. * Instantiates a new glow Layer and references it to the scene.
  92538. * @param name The name of the layer
  92539. * @param scene The scene to use the layer in
  92540. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92541. */
  92542. function GlowLayer(name, scene, options) {
  92543. var _this = _super.call(this, name, scene) || this;
  92544. _this._intensity = 1.0;
  92545. _this._includedOnlyMeshes = [];
  92546. _this._excludedMeshes = [];
  92547. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92548. // Adapt options
  92549. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92550. // Initialize the layer
  92551. _this._init({
  92552. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92553. camera: _this._options.camera,
  92554. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92555. mainTextureRatio: _this._options.mainTextureRatio
  92556. });
  92557. return _this;
  92558. }
  92559. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92560. /**
  92561. * Gets the kernel size of the blur.
  92562. */
  92563. get: function () {
  92564. return this._horizontalBlurPostprocess1.kernel;
  92565. },
  92566. /**
  92567. * Sets the kernel size of the blur.
  92568. */
  92569. set: function (value) {
  92570. this._horizontalBlurPostprocess1.kernel = value;
  92571. this._verticalBlurPostprocess1.kernel = value;
  92572. this._horizontalBlurPostprocess2.kernel = value;
  92573. this._verticalBlurPostprocess2.kernel = value;
  92574. },
  92575. enumerable: true,
  92576. configurable: true
  92577. });
  92578. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92579. /**
  92580. * Gets the glow intensity.
  92581. */
  92582. get: function () {
  92583. return this._intensity;
  92584. },
  92585. /**
  92586. * Sets the glow intensity.
  92587. */
  92588. set: function (value) {
  92589. this._intensity = value;
  92590. },
  92591. enumerable: true,
  92592. configurable: true
  92593. });
  92594. /**
  92595. * Get the effect name of the layer.
  92596. * @return The effect name
  92597. */
  92598. GlowLayer.prototype.getEffectName = function () {
  92599. return GlowLayer.EffectName;
  92600. };
  92601. /**
  92602. * Create the merge effect. This is the shader use to blit the information back
  92603. * to the main canvas at the end of the scene rendering.
  92604. */
  92605. GlowLayer.prototype._createMergeEffect = function () {
  92606. // Effect
  92607. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92608. };
  92609. /**
  92610. * Creates the render target textures and post processes used in the glow layer.
  92611. */
  92612. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92613. var _this = this;
  92614. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92615. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92616. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92617. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92618. var textureType = 0;
  92619. if (this._engine.getCaps().textureHalfFloatRender) {
  92620. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92621. }
  92622. else {
  92623. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92624. }
  92625. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92626. width: blurTextureWidth,
  92627. height: blurTextureHeight
  92628. }, this._scene, false, true, textureType);
  92629. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92630. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92631. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92632. this._blurTexture1.renderParticles = false;
  92633. this._blurTexture1.ignoreCameraViewport = true;
  92634. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92635. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92636. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92637. width: blurTextureWidth2,
  92638. height: blurTextureHeight2
  92639. }, this._scene, false, true, textureType);
  92640. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92641. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92642. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92643. this._blurTexture2.renderParticles = false;
  92644. this._blurTexture2.ignoreCameraViewport = true;
  92645. this._textures = [this._blurTexture1, this._blurTexture2];
  92646. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92647. width: blurTextureWidth,
  92648. height: blurTextureHeight
  92649. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92650. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92651. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92652. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92653. effect.setTexture("textureSampler", _this._mainTexture);
  92654. });
  92655. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92656. width: blurTextureWidth,
  92657. height: blurTextureHeight
  92658. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92659. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92660. width: blurTextureWidth2,
  92661. height: blurTextureHeight2
  92662. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92663. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92664. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92665. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92666. effect.setTexture("textureSampler", _this._blurTexture1);
  92667. });
  92668. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92669. width: blurTextureWidth2,
  92670. height: blurTextureHeight2
  92671. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92672. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92673. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92674. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92675. this._mainTexture.samples = this._options.mainTextureSamples;
  92676. this._mainTexture.onAfterUnbindObservable.add(function () {
  92677. var internalTexture = _this._blurTexture1.getInternalTexture();
  92678. if (internalTexture) {
  92679. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92680. internalTexture = _this._blurTexture2.getInternalTexture();
  92681. if (internalTexture) {
  92682. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92683. }
  92684. }
  92685. });
  92686. // Prevent autoClear.
  92687. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92688. };
  92689. /**
  92690. * Checks for the readiness of the element composing the layer.
  92691. * @param subMesh the mesh to check for
  92692. * @param useInstances specify wether or not to use instances to render the mesh
  92693. * @param emissiveTexture the associated emissive texture used to generate the glow
  92694. * @return true if ready otherwise, false
  92695. */
  92696. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92697. var material = subMesh.getMaterial();
  92698. var mesh = subMesh.getRenderingMesh();
  92699. if (!material || !mesh) {
  92700. return false;
  92701. }
  92702. var emissiveTexture = material.emissiveTexture;
  92703. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92704. };
  92705. /**
  92706. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92707. */
  92708. GlowLayer.prototype.needStencil = function () {
  92709. return false;
  92710. };
  92711. /**
  92712. * Implementation specific of rendering the generating effect on the main canvas.
  92713. * @param effect The effect used to render through
  92714. */
  92715. GlowLayer.prototype._internalRender = function (effect) {
  92716. // Texture
  92717. effect.setTexture("textureSampler", this._blurTexture1);
  92718. effect.setTexture("textureSampler2", this._blurTexture2);
  92719. effect.setFloat("offset", this._intensity);
  92720. // Cache
  92721. var engine = this._engine;
  92722. var previousStencilBuffer = engine.getStencilBuffer();
  92723. // Draw order
  92724. engine.setStencilBuffer(false);
  92725. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92726. // Draw order
  92727. engine.setStencilBuffer(previousStencilBuffer);
  92728. };
  92729. /**
  92730. * Sets the required values for both the emissive texture and and the main color.
  92731. */
  92732. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92733. var textureLevel = 1.0;
  92734. if (this.customEmissiveTextureSelector) {
  92735. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92736. }
  92737. else {
  92738. if (material) {
  92739. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92740. if (this._emissiveTextureAndColor.texture) {
  92741. textureLevel = this._emissiveTextureAndColor.texture.level;
  92742. }
  92743. }
  92744. else {
  92745. this._emissiveTextureAndColor.texture = null;
  92746. }
  92747. }
  92748. if (this.customEmissiveColorSelector) {
  92749. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92750. }
  92751. else {
  92752. if (material.emissiveColor) {
  92753. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92754. }
  92755. else {
  92756. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92757. }
  92758. }
  92759. };
  92760. /**
  92761. * Returns true if the mesh should render, otherwise false.
  92762. * @param mesh The mesh to render
  92763. * @returns true if it should render otherwise false
  92764. */
  92765. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92766. return this.hasMesh(mesh);
  92767. };
  92768. /**
  92769. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92770. * @param mesh The mesh to exclude from the glow layer
  92771. */
  92772. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92773. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92774. this._excludedMeshes.push(mesh.uniqueId);
  92775. }
  92776. };
  92777. /**
  92778. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92779. * @param mesh The mesh to remove
  92780. */
  92781. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92782. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92783. if (index !== -1) {
  92784. this._excludedMeshes.splice(index, 1);
  92785. }
  92786. };
  92787. /**
  92788. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92789. * @param mesh The mesh to include in the glow layer
  92790. */
  92791. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92792. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92793. this._includedOnlyMeshes.push(mesh.uniqueId);
  92794. }
  92795. };
  92796. /**
  92797. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92798. * @param mesh The mesh to remove
  92799. */
  92800. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92801. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92802. if (index !== -1) {
  92803. this._includedOnlyMeshes.splice(index, 1);
  92804. }
  92805. };
  92806. /**
  92807. * Determine if a given mesh will be used in the glow layer
  92808. * @param mesh The mesh to test
  92809. * @returns true if the mesh will be highlighted by the current glow layer
  92810. */
  92811. GlowLayer.prototype.hasMesh = function (mesh) {
  92812. // Included Mesh
  92813. if (this._includedOnlyMeshes.length) {
  92814. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92815. }
  92816. ;
  92817. // Excluded Mesh
  92818. if (this._excludedMeshes.length) {
  92819. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92820. }
  92821. ;
  92822. return true;
  92823. };
  92824. /**
  92825. * Free any resources and references associated to a mesh.
  92826. * Internal use
  92827. * @param mesh The mesh to free.
  92828. */
  92829. GlowLayer.prototype._disposeMesh = function (mesh) {
  92830. this.removeIncludedOnlyMesh(mesh);
  92831. this.removeExcludedMesh(mesh);
  92832. };
  92833. /**
  92834. * Gets the class name of the effect layer
  92835. * @returns the string with the class name of the effect layer
  92836. */
  92837. GlowLayer.prototype.getClassName = function () {
  92838. return "GlowLayer";
  92839. };
  92840. /**
  92841. * Serializes this glow layer
  92842. * @returns a serialized glow layer object
  92843. */
  92844. GlowLayer.prototype.serialize = function () {
  92845. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92846. serializationObject.customType = "BABYLON.GlowLayer";
  92847. var index;
  92848. // Included meshes
  92849. serializationObject.includedMeshes = [];
  92850. if (this._includedOnlyMeshes.length) {
  92851. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92852. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92853. if (mesh) {
  92854. serializationObject.includedMeshes.push(mesh.id);
  92855. }
  92856. }
  92857. }
  92858. // Excluded meshes
  92859. serializationObject.excludedMeshes = [];
  92860. if (this._excludedMeshes.length) {
  92861. for (index = 0; index < this._excludedMeshes.length; index++) {
  92862. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92863. if (mesh) {
  92864. serializationObject.excludedMeshes.push(mesh.id);
  92865. }
  92866. }
  92867. }
  92868. return serializationObject;
  92869. };
  92870. /**
  92871. * Creates a Glow Layer from parsed glow layer data
  92872. * @param parsedGlowLayer defines glow layer data
  92873. * @param scene defines the current scene
  92874. * @param rootUrl defines the root URL containing the glow layer information
  92875. * @returns a parsed Glow Layer
  92876. */
  92877. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92878. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92879. var index;
  92880. // Excluded meshes
  92881. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92882. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92883. if (mesh) {
  92884. gl.addExcludedMesh(mesh);
  92885. }
  92886. }
  92887. // Included meshes
  92888. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92889. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92890. if (mesh) {
  92891. gl.addIncludedOnlyMesh(mesh);
  92892. }
  92893. }
  92894. return gl;
  92895. };
  92896. /**
  92897. * Effect Name of the layer.
  92898. */
  92899. GlowLayer.EffectName = "GlowLayer";
  92900. /**
  92901. * The default blur kernel size used for the glow.
  92902. */
  92903. GlowLayer.DefaultBlurKernelSize = 32;
  92904. /**
  92905. * The default texture size ratio used for the glow.
  92906. */
  92907. GlowLayer.DefaultTextureRatio = 0.5;
  92908. __decorate([
  92909. BABYLON.serialize()
  92910. ], GlowLayer.prototype, "blurKernelSize", null);
  92911. __decorate([
  92912. BABYLON.serialize()
  92913. ], GlowLayer.prototype, "intensity", null);
  92914. __decorate([
  92915. BABYLON.serialize("options")
  92916. ], GlowLayer.prototype, "_options", void 0);
  92917. return GlowLayer;
  92918. }(BABYLON.EffectLayer));
  92919. BABYLON.GlowLayer = GlowLayer;
  92920. })(BABYLON || (BABYLON = {}));
  92921. //# sourceMappingURL=babylon.glowLayer.js.map
  92922. var BABYLON;
  92923. (function (BABYLON) {
  92924. /**
  92925. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92926. */
  92927. var AssetTaskState;
  92928. (function (AssetTaskState) {
  92929. /**
  92930. * Initialization
  92931. */
  92932. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92933. /**
  92934. * Running
  92935. */
  92936. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92937. /**
  92938. * Done
  92939. */
  92940. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92941. /**
  92942. * Error
  92943. */
  92944. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92945. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92946. /**
  92947. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92948. */
  92949. var AbstractAssetTask = /** @class */ (function () {
  92950. /**
  92951. * Creates a new {BABYLON.AssetsManager}
  92952. * @param name defines the name of the task
  92953. */
  92954. function AbstractAssetTask(
  92955. /**
  92956. * Task name
  92957. */ name) {
  92958. this.name = name;
  92959. this._isCompleted = false;
  92960. this._taskState = AssetTaskState.INIT;
  92961. }
  92962. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92963. /**
  92964. * Get if the task is completed
  92965. */
  92966. get: function () {
  92967. return this._isCompleted;
  92968. },
  92969. enumerable: true,
  92970. configurable: true
  92971. });
  92972. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92973. /**
  92974. * Gets the current state of the task
  92975. */
  92976. get: function () {
  92977. return this._taskState;
  92978. },
  92979. enumerable: true,
  92980. configurable: true
  92981. });
  92982. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92983. /**
  92984. * Gets the current error object (if task is in error)
  92985. */
  92986. get: function () {
  92987. return this._errorObject;
  92988. },
  92989. enumerable: true,
  92990. configurable: true
  92991. });
  92992. /**
  92993. * Internal only
  92994. * @hidden
  92995. */
  92996. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92997. if (this._errorObject) {
  92998. return;
  92999. }
  93000. this._errorObject = {
  93001. message: message,
  93002. exception: exception
  93003. };
  93004. };
  93005. /**
  93006. * Execute the current task
  93007. * @param scene defines the scene where you want your assets to be loaded
  93008. * @param onSuccess is a callback called when the task is successfully executed
  93009. * @param onError is a callback called if an error occurs
  93010. */
  93011. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93012. var _this = this;
  93013. this._taskState = AssetTaskState.RUNNING;
  93014. this.runTask(scene, function () {
  93015. _this.onDoneCallback(onSuccess, onError);
  93016. }, function (msg, exception) {
  93017. _this.onErrorCallback(onError, msg, exception);
  93018. });
  93019. };
  93020. /**
  93021. * Execute the current task
  93022. * @param scene defines the scene where you want your assets to be loaded
  93023. * @param onSuccess is a callback called when the task is successfully executed
  93024. * @param onError is a callback called if an error occurs
  93025. */
  93026. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93027. throw new Error("runTask is not implemented");
  93028. };
  93029. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93030. this._taskState = AssetTaskState.ERROR;
  93031. this._errorObject = {
  93032. message: message,
  93033. exception: exception
  93034. };
  93035. if (this.onError) {
  93036. this.onError(this, message, exception);
  93037. }
  93038. onError();
  93039. };
  93040. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93041. try {
  93042. this._taskState = AssetTaskState.DONE;
  93043. this._isCompleted = true;
  93044. if (this.onSuccess) {
  93045. this.onSuccess(this);
  93046. }
  93047. onSuccess();
  93048. }
  93049. catch (e) {
  93050. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93051. }
  93052. };
  93053. return AbstractAssetTask;
  93054. }());
  93055. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93056. /**
  93057. * Class used to share progress information about assets loading
  93058. */
  93059. var AssetsProgressEvent = /** @class */ (function () {
  93060. /**
  93061. * Creates a {BABYLON.AssetsProgressEvent}
  93062. * @param remainingCount defines the number of remaining tasks to process
  93063. * @param totalCount defines the total number of tasks
  93064. * @param task defines the task that was just processed
  93065. */
  93066. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93067. this.remainingCount = remainingCount;
  93068. this.totalCount = totalCount;
  93069. this.task = task;
  93070. }
  93071. return AssetsProgressEvent;
  93072. }());
  93073. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93074. /**
  93075. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93076. */
  93077. var MeshAssetTask = /** @class */ (function (_super) {
  93078. __extends(MeshAssetTask, _super);
  93079. /**
  93080. * Creates a new {BABYLON.MeshAssetTask}
  93081. * @param name defines the name of the task
  93082. * @param meshesNames defines the list of mesh's names you want to load
  93083. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93084. * @param sceneFilename defines the filename of the scene to load from
  93085. */
  93086. function MeshAssetTask(
  93087. /**
  93088. * Defines the name of the task
  93089. */
  93090. name,
  93091. /**
  93092. * Defines the list of mesh's names you want to load
  93093. */
  93094. meshesNames,
  93095. /**
  93096. * Defines the root url to use as a base to load your meshes and associated resources
  93097. */
  93098. rootUrl,
  93099. /**
  93100. * Defines the filename of the scene to load from
  93101. */
  93102. sceneFilename) {
  93103. var _this = _super.call(this, name) || this;
  93104. _this.name = name;
  93105. _this.meshesNames = meshesNames;
  93106. _this.rootUrl = rootUrl;
  93107. _this.sceneFilename = sceneFilename;
  93108. return _this;
  93109. }
  93110. /**
  93111. * Execute the current task
  93112. * @param scene defines the scene where you want your assets to be loaded
  93113. * @param onSuccess is a callback called when the task is successfully executed
  93114. * @param onError is a callback called if an error occurs
  93115. */
  93116. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93117. var _this = this;
  93118. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93119. _this.loadedMeshes = meshes;
  93120. _this.loadedParticleSystems = particleSystems;
  93121. _this.loadedSkeletons = skeletons;
  93122. onSuccess();
  93123. }, null, function (scene, message, exception) {
  93124. onError(message, exception);
  93125. });
  93126. };
  93127. return MeshAssetTask;
  93128. }(AbstractAssetTask));
  93129. BABYLON.MeshAssetTask = MeshAssetTask;
  93130. /**
  93131. * Define a task used by {BABYLON.AssetsManager} to load text content
  93132. */
  93133. var TextFileAssetTask = /** @class */ (function (_super) {
  93134. __extends(TextFileAssetTask, _super);
  93135. /**
  93136. * Creates a new TextFileAssetTask object
  93137. * @param name defines the name of the task
  93138. * @param url defines the location of the file to load
  93139. */
  93140. function TextFileAssetTask(
  93141. /**
  93142. * Defines the name of the task
  93143. */
  93144. name,
  93145. /**
  93146. * Defines the location of the file to load
  93147. */
  93148. url) {
  93149. var _this = _super.call(this, name) || this;
  93150. _this.name = name;
  93151. _this.url = url;
  93152. return _this;
  93153. }
  93154. /**
  93155. * Execute the current task
  93156. * @param scene defines the scene where you want your assets to be loaded
  93157. * @param onSuccess is a callback called when the task is successfully executed
  93158. * @param onError is a callback called if an error occurs
  93159. */
  93160. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93161. var _this = this;
  93162. scene._loadFile(this.url, function (data) {
  93163. _this.text = data;
  93164. onSuccess();
  93165. }, undefined, false, false, function (request, exception) {
  93166. if (request) {
  93167. onError(request.status + " " + request.statusText, exception);
  93168. }
  93169. });
  93170. };
  93171. return TextFileAssetTask;
  93172. }(AbstractAssetTask));
  93173. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93174. /**
  93175. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93176. */
  93177. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93178. __extends(BinaryFileAssetTask, _super);
  93179. /**
  93180. * Creates a new BinaryFileAssetTask object
  93181. * @param name defines the name of the new task
  93182. * @param url defines the location of the file to load
  93183. */
  93184. function BinaryFileAssetTask(
  93185. /**
  93186. * Defines the name of the task
  93187. */
  93188. name,
  93189. /**
  93190. * Defines the location of the file to load
  93191. */
  93192. url) {
  93193. var _this = _super.call(this, name) || this;
  93194. _this.name = name;
  93195. _this.url = url;
  93196. return _this;
  93197. }
  93198. /**
  93199. * Execute the current task
  93200. * @param scene defines the scene where you want your assets to be loaded
  93201. * @param onSuccess is a callback called when the task is successfully executed
  93202. * @param onError is a callback called if an error occurs
  93203. */
  93204. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93205. var _this = this;
  93206. scene._loadFile(this.url, function (data) {
  93207. _this.data = data;
  93208. onSuccess();
  93209. }, undefined, true, true, function (request, exception) {
  93210. if (request) {
  93211. onError(request.status + " " + request.statusText, exception);
  93212. }
  93213. });
  93214. };
  93215. return BinaryFileAssetTask;
  93216. }(AbstractAssetTask));
  93217. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93218. /**
  93219. * Define a task used by {BABYLON.AssetsManager} to load images
  93220. */
  93221. var ImageAssetTask = /** @class */ (function (_super) {
  93222. __extends(ImageAssetTask, _super);
  93223. /**
  93224. * Creates a new ImageAssetTask
  93225. * @param name defines the name of the task
  93226. * @param url defines the location of the image to load
  93227. */
  93228. function ImageAssetTask(
  93229. /**
  93230. * Defines the name of the task
  93231. */
  93232. name,
  93233. /**
  93234. * Defines the location of the image to load
  93235. */
  93236. url) {
  93237. var _this = _super.call(this, name) || this;
  93238. _this.name = name;
  93239. _this.url = url;
  93240. return _this;
  93241. }
  93242. /**
  93243. * Execute the current task
  93244. * @param scene defines the scene where you want your assets to be loaded
  93245. * @param onSuccess is a callback called when the task is successfully executed
  93246. * @param onError is a callback called if an error occurs
  93247. */
  93248. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93249. var _this = this;
  93250. var img = new Image();
  93251. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93252. img.onload = function () {
  93253. _this.image = img;
  93254. onSuccess();
  93255. };
  93256. img.onerror = function (err) {
  93257. onError("Error loading image", err);
  93258. };
  93259. img.src = this.url;
  93260. };
  93261. return ImageAssetTask;
  93262. }(AbstractAssetTask));
  93263. BABYLON.ImageAssetTask = ImageAssetTask;
  93264. /**
  93265. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93266. */
  93267. var TextureAssetTask = /** @class */ (function (_super) {
  93268. __extends(TextureAssetTask, _super);
  93269. /**
  93270. * Creates a new TextureAssetTask object
  93271. * @param name defines the name of the task
  93272. * @param url defines the location of the file to load
  93273. * @param noMipmap defines if mipmap should not be generated (default is false)
  93274. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93275. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93276. */
  93277. function TextureAssetTask(
  93278. /**
  93279. * Defines the name of the task
  93280. */
  93281. name,
  93282. /**
  93283. * Defines the location of the file to load
  93284. */
  93285. url,
  93286. /**
  93287. * Defines if mipmap should not be generated (default is false)
  93288. */
  93289. noMipmap,
  93290. /**
  93291. * Defines if texture must be inverted on Y axis (default is false)
  93292. */
  93293. invertY,
  93294. /**
  93295. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93296. */
  93297. samplingMode) {
  93298. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93299. var _this = _super.call(this, name) || this;
  93300. _this.name = name;
  93301. _this.url = url;
  93302. _this.noMipmap = noMipmap;
  93303. _this.invertY = invertY;
  93304. _this.samplingMode = samplingMode;
  93305. return _this;
  93306. }
  93307. /**
  93308. * Execute the current task
  93309. * @param scene defines the scene where you want your assets to be loaded
  93310. * @param onSuccess is a callback called when the task is successfully executed
  93311. * @param onError is a callback called if an error occurs
  93312. */
  93313. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93314. var onload = function () {
  93315. onSuccess();
  93316. };
  93317. var onerror = function (message, exception) {
  93318. onError(message, exception);
  93319. };
  93320. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93321. };
  93322. return TextureAssetTask;
  93323. }(AbstractAssetTask));
  93324. BABYLON.TextureAssetTask = TextureAssetTask;
  93325. /**
  93326. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93327. */
  93328. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93329. __extends(CubeTextureAssetTask, _super);
  93330. /**
  93331. * Creates a new CubeTextureAssetTask
  93332. * @param name defines the name of the task
  93333. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93334. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93335. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93336. * @param files defines the explicit list of files (undefined by default)
  93337. */
  93338. function CubeTextureAssetTask(
  93339. /**
  93340. * Defines the name of the task
  93341. */
  93342. name,
  93343. /**
  93344. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93345. */
  93346. url,
  93347. /**
  93348. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93349. */
  93350. extensions,
  93351. /**
  93352. * Defines if mipmaps should not be generated (default is false)
  93353. */
  93354. noMipmap,
  93355. /**
  93356. * Defines the explicit list of files (undefined by default)
  93357. */
  93358. files) {
  93359. var _this = _super.call(this, name) || this;
  93360. _this.name = name;
  93361. _this.url = url;
  93362. _this.extensions = extensions;
  93363. _this.noMipmap = noMipmap;
  93364. _this.files = files;
  93365. return _this;
  93366. }
  93367. /**
  93368. * Execute the current task
  93369. * @param scene defines the scene where you want your assets to be loaded
  93370. * @param onSuccess is a callback called when the task is successfully executed
  93371. * @param onError is a callback called if an error occurs
  93372. */
  93373. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93374. var onload = function () {
  93375. onSuccess();
  93376. };
  93377. var onerror = function (message, exception) {
  93378. onError(message, exception);
  93379. };
  93380. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93381. };
  93382. return CubeTextureAssetTask;
  93383. }(AbstractAssetTask));
  93384. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93385. /**
  93386. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93387. */
  93388. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93389. __extends(HDRCubeTextureAssetTask, _super);
  93390. /**
  93391. * Creates a new HDRCubeTextureAssetTask object
  93392. * @param name defines the name of the task
  93393. * @param url defines the location of the file to load
  93394. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  93395. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93396. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93397. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93398. * @param reserved Internal use only
  93399. */
  93400. function HDRCubeTextureAssetTask(
  93401. /**
  93402. * Defines the name of the task
  93403. */
  93404. name,
  93405. /**
  93406. * Defines the location of the file to load
  93407. */
  93408. url,
  93409. /**
  93410. * Defines the desired size (the more it increases the longer the generation will be)
  93411. */
  93412. size,
  93413. /**
  93414. * Defines if mipmaps should not be generated (default is false)
  93415. */
  93416. noMipmap,
  93417. /**
  93418. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93419. */
  93420. generateHarmonics,
  93421. /**
  93422. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93423. */
  93424. gammaSpace,
  93425. /**
  93426. * Internal Use Only
  93427. */
  93428. reserved) {
  93429. if (noMipmap === void 0) { noMipmap = false; }
  93430. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93431. if (gammaSpace === void 0) { gammaSpace = false; }
  93432. if (reserved === void 0) { reserved = false; }
  93433. var _this = _super.call(this, name) || this;
  93434. _this.name = name;
  93435. _this.url = url;
  93436. _this.size = size;
  93437. _this.noMipmap = noMipmap;
  93438. _this.generateHarmonics = generateHarmonics;
  93439. _this.gammaSpace = gammaSpace;
  93440. _this.reserved = reserved;
  93441. return _this;
  93442. }
  93443. /**
  93444. * Execute the current task
  93445. * @param scene defines the scene where you want your assets to be loaded
  93446. * @param onSuccess is a callback called when the task is successfully executed
  93447. * @param onError is a callback called if an error occurs
  93448. */
  93449. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93450. var onload = function () {
  93451. onSuccess();
  93452. };
  93453. var onerror = function (message, exception) {
  93454. onError(message, exception);
  93455. };
  93456. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93457. };
  93458. return HDRCubeTextureAssetTask;
  93459. }(AbstractAssetTask));
  93460. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93461. /**
  93462. * This class can be used to easily import assets into a scene
  93463. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93464. */
  93465. var AssetsManager = /** @class */ (function () {
  93466. /**
  93467. * Creates a new AssetsManager
  93468. * @param scene defines the scene to work on
  93469. */
  93470. function AssetsManager(scene) {
  93471. this._isLoading = false;
  93472. this._tasks = new Array();
  93473. this._waitingTasksCount = 0;
  93474. this._totalTasksCount = 0;
  93475. /**
  93476. * Observable called when all tasks are processed
  93477. */
  93478. this.onTaskSuccessObservable = new BABYLON.Observable();
  93479. /**
  93480. * Observable called when a task had an error
  93481. */
  93482. this.onTaskErrorObservable = new BABYLON.Observable();
  93483. /**
  93484. * Observable called when a task is successful
  93485. */
  93486. this.onTasksDoneObservable = new BABYLON.Observable();
  93487. /**
  93488. * Observable called when a task is done (whatever the result is)
  93489. */
  93490. this.onProgressObservable = new BABYLON.Observable();
  93491. /**
  93492. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93493. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93494. */
  93495. this.useDefaultLoadingScreen = true;
  93496. this._scene = scene;
  93497. }
  93498. /**
  93499. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93500. * @param taskName defines the name of the new task
  93501. * @param meshesNames defines the name of meshes to load
  93502. * @param rootUrl defines the root url to use to locate files
  93503. * @param sceneFilename defines the filename of the scene file
  93504. * @returns a new {BABYLON.MeshAssetTask} object
  93505. */
  93506. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93507. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93508. this._tasks.push(task);
  93509. return task;
  93510. };
  93511. /**
  93512. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93513. * @param taskName defines the name of the new task
  93514. * @param url defines the url of the file to load
  93515. * @returns a new {BABYLON.TextFileAssetTask} object
  93516. */
  93517. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93518. var task = new TextFileAssetTask(taskName, url);
  93519. this._tasks.push(task);
  93520. return task;
  93521. };
  93522. /**
  93523. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93524. * @param taskName defines the name of the new task
  93525. * @param url defines the url of the file to load
  93526. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93527. */
  93528. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93529. var task = new BinaryFileAssetTask(taskName, url);
  93530. this._tasks.push(task);
  93531. return task;
  93532. };
  93533. /**
  93534. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93535. * @param taskName defines the name of the new task
  93536. * @param url defines the url of the file to load
  93537. * @returns a new {BABYLON.ImageAssetTask} object
  93538. */
  93539. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93540. var task = new ImageAssetTask(taskName, url);
  93541. this._tasks.push(task);
  93542. return task;
  93543. };
  93544. /**
  93545. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93546. * @param taskName defines the name of the new task
  93547. * @param url defines the url of the file to load
  93548. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93549. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93550. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93551. * @returns a new {BABYLON.TextureAssetTask} object
  93552. */
  93553. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93555. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93556. this._tasks.push(task);
  93557. return task;
  93558. };
  93559. /**
  93560. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93561. * @param taskName defines the name of the new task
  93562. * @param url defines the url of the file to load
  93563. * @param extensions defines the extension to use to load the cube map (can be null)
  93564. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93565. * @param files defines the list of files to load (can be null)
  93566. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93567. */
  93568. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93569. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93570. this._tasks.push(task);
  93571. return task;
  93572. };
  93573. /**
  93574. *
  93575. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93576. * @param taskName defines the name of the new task
  93577. * @param url defines the url of the file to load
  93578. * @param size defines the size you want for the cubemap (can be null)
  93579. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93580. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93581. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93582. * @param reserved Internal use only
  93583. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93584. */
  93585. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93586. if (noMipmap === void 0) { noMipmap = false; }
  93587. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93588. if (gammaSpace === void 0) { gammaSpace = false; }
  93589. if (reserved === void 0) { reserved = false; }
  93590. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93591. this._tasks.push(task);
  93592. return task;
  93593. };
  93594. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93595. var _this = this;
  93596. this._waitingTasksCount--;
  93597. try {
  93598. if (task.taskState === AssetTaskState.DONE) {
  93599. // Let's remove successfull tasks
  93600. BABYLON.Tools.SetImmediate(function () {
  93601. var index = _this._tasks.indexOf(task);
  93602. if (index > -1) {
  93603. _this._tasks.splice(index, 1);
  93604. }
  93605. });
  93606. }
  93607. if (this.onProgress) {
  93608. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93609. }
  93610. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93611. }
  93612. catch (e) {
  93613. BABYLON.Tools.Error("Error running progress callbacks.");
  93614. console.log(e);
  93615. }
  93616. if (this._waitingTasksCount === 0) {
  93617. try {
  93618. if (this.onFinish) {
  93619. this.onFinish(this._tasks);
  93620. }
  93621. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93622. }
  93623. catch (e) {
  93624. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93625. console.log(e);
  93626. }
  93627. this._isLoading = false;
  93628. this._scene.getEngine().hideLoadingUI();
  93629. }
  93630. };
  93631. AssetsManager.prototype._runTask = function (task) {
  93632. var _this = this;
  93633. var done = function () {
  93634. try {
  93635. if (_this.onTaskSuccess) {
  93636. _this.onTaskSuccess(task);
  93637. }
  93638. _this.onTaskSuccessObservable.notifyObservers(task);
  93639. _this._decreaseWaitingTasksCount(task);
  93640. }
  93641. catch (e) {
  93642. error("Error executing task success callbacks", e);
  93643. }
  93644. };
  93645. var error = function (message, exception) {
  93646. task._setErrorObject(message, exception);
  93647. if (_this.onTaskError) {
  93648. _this.onTaskError(task);
  93649. }
  93650. _this.onTaskErrorObservable.notifyObservers(task);
  93651. _this._decreaseWaitingTasksCount(task);
  93652. };
  93653. task.run(this._scene, done, error);
  93654. };
  93655. /**
  93656. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93657. * @return the current instance of the {BABYLON.AssetsManager}
  93658. */
  93659. AssetsManager.prototype.reset = function () {
  93660. this._isLoading = false;
  93661. this._tasks = new Array();
  93662. return this;
  93663. };
  93664. /**
  93665. * Start the loading process
  93666. * @return the current instance of the {BABYLON.AssetsManager}
  93667. */
  93668. AssetsManager.prototype.load = function () {
  93669. if (this._isLoading) {
  93670. return this;
  93671. }
  93672. this._isLoading = true;
  93673. this._waitingTasksCount = this._tasks.length;
  93674. this._totalTasksCount = this._tasks.length;
  93675. if (this._waitingTasksCount === 0) {
  93676. this._isLoading = false;
  93677. if (this.onFinish) {
  93678. this.onFinish(this._tasks);
  93679. }
  93680. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93681. return this;
  93682. }
  93683. if (this.useDefaultLoadingScreen) {
  93684. this._scene.getEngine().displayLoadingUI();
  93685. }
  93686. for (var index = 0; index < this._tasks.length; index++) {
  93687. var task = this._tasks[index];
  93688. this._runTask(task);
  93689. }
  93690. return this;
  93691. };
  93692. return AssetsManager;
  93693. }());
  93694. BABYLON.AssetsManager = AssetsManager;
  93695. })(BABYLON || (BABYLON = {}));
  93696. //# sourceMappingURL=babylon.assetsManager.js.map
  93697. var BABYLON;
  93698. (function (BABYLON) {
  93699. var serializedGeometries = [];
  93700. var serializeGeometry = function (geometry, serializationGeometries) {
  93701. if (serializedGeometries[geometry.id]) {
  93702. return;
  93703. }
  93704. if (geometry.doNotSerialize) {
  93705. return;
  93706. }
  93707. if (geometry instanceof BABYLON.BoxGeometry) {
  93708. serializationGeometries.boxes.push(geometry.serialize());
  93709. }
  93710. else if (geometry instanceof BABYLON.SphereGeometry) {
  93711. serializationGeometries.spheres.push(geometry.serialize());
  93712. }
  93713. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93714. serializationGeometries.cylinders.push(geometry.serialize());
  93715. }
  93716. else if (geometry instanceof BABYLON.TorusGeometry) {
  93717. serializationGeometries.toruses.push(geometry.serialize());
  93718. }
  93719. else if (geometry instanceof BABYLON.GroundGeometry) {
  93720. serializationGeometries.grounds.push(geometry.serialize());
  93721. }
  93722. else if (geometry instanceof BABYLON.Plane) {
  93723. serializationGeometries.planes.push(geometry.serialize());
  93724. }
  93725. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93726. serializationGeometries.torusKnots.push(geometry.serialize());
  93727. }
  93728. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93729. throw new Error("Unknown primitive type");
  93730. }
  93731. else {
  93732. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93733. }
  93734. serializedGeometries[geometry.id] = true;
  93735. };
  93736. var serializeMesh = function (mesh, serializationScene) {
  93737. var serializationObject = {};
  93738. // Geometry
  93739. var geometry = mesh._geometry;
  93740. if (geometry) {
  93741. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93742. // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  93743. serializeGeometry(geometry, serializationScene.geometries);
  93744. }
  93745. }
  93746. // Custom
  93747. if (mesh.serialize) {
  93748. mesh.serialize(serializationObject);
  93749. }
  93750. return serializationObject;
  93751. };
  93752. var finalizeSingleMesh = function (mesh, serializationObject) {
  93753. //only works if the mesh is already loaded
  93754. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93755. //serialize material
  93756. if (mesh.material) {
  93757. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93758. serializationObject.materials = serializationObject.materials || [];
  93759. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93760. serializationObject.materials.push(mesh.material.serialize());
  93761. }
  93762. }
  93763. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93764. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93765. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93766. serializationObject.multiMaterials.push(mesh.material.serialize());
  93767. }
  93768. }
  93769. }
  93770. //serialize geometry
  93771. var geometry = mesh._geometry;
  93772. if (geometry) {
  93773. if (!serializationObject.geometries) {
  93774. serializationObject.geometries = {};
  93775. serializationObject.geometries.boxes = [];
  93776. serializationObject.geometries.spheres = [];
  93777. serializationObject.geometries.cylinders = [];
  93778. serializationObject.geometries.toruses = [];
  93779. serializationObject.geometries.grounds = [];
  93780. serializationObject.geometries.planes = [];
  93781. serializationObject.geometries.torusKnots = [];
  93782. serializationObject.geometries.vertexData = [];
  93783. }
  93784. serializeGeometry(geometry, serializationObject.geometries);
  93785. }
  93786. // Skeletons
  93787. if (mesh.skeleton) {
  93788. serializationObject.skeletons = serializationObject.skeletons || [];
  93789. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93790. }
  93791. //serialize the actual mesh
  93792. serializationObject.meshes = serializationObject.meshes || [];
  93793. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93794. }
  93795. };
  93796. var SceneSerializer = /** @class */ (function () {
  93797. function SceneSerializer() {
  93798. }
  93799. SceneSerializer.ClearCache = function () {
  93800. serializedGeometries = [];
  93801. };
  93802. SceneSerializer.Serialize = function (scene) {
  93803. var serializationObject = {};
  93804. SceneSerializer.ClearCache();
  93805. // Scene
  93806. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93807. serializationObject.autoClear = scene.autoClear;
  93808. serializationObject.clearColor = scene.clearColor.asArray();
  93809. serializationObject.ambientColor = scene.ambientColor.asArray();
  93810. serializationObject.gravity = scene.gravity.asArray();
  93811. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93812. serializationObject.workerCollisions = scene.workerCollisions;
  93813. // Fog
  93814. if (scene.fogMode && scene.fogMode !== 0) {
  93815. serializationObject.fogMode = scene.fogMode;
  93816. serializationObject.fogColor = scene.fogColor.asArray();
  93817. serializationObject.fogStart = scene.fogStart;
  93818. serializationObject.fogEnd = scene.fogEnd;
  93819. serializationObject.fogDensity = scene.fogDensity;
  93820. }
  93821. //Physics
  93822. if (scene.isPhysicsEnabled()) {
  93823. var physicEngine = scene.getPhysicsEngine();
  93824. if (physicEngine) {
  93825. serializationObject.physicsEnabled = true;
  93826. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93827. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93828. }
  93829. }
  93830. // Metadata
  93831. if (scene.metadata) {
  93832. serializationObject.metadata = scene.metadata;
  93833. }
  93834. // Morph targets
  93835. serializationObject.morphTargetManagers = [];
  93836. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93837. var abstractMesh = _a[_i];
  93838. var manager = abstractMesh.morphTargetManager;
  93839. if (manager) {
  93840. serializationObject.morphTargetManagers.push(manager.serialize());
  93841. }
  93842. }
  93843. // Lights
  93844. serializationObject.lights = [];
  93845. var index;
  93846. var light;
  93847. for (index = 0; index < scene.lights.length; index++) {
  93848. light = scene.lights[index];
  93849. if (!light.doNotSerialize) {
  93850. serializationObject.lights.push(light.serialize());
  93851. }
  93852. }
  93853. // Cameras
  93854. serializationObject.cameras = [];
  93855. for (index = 0; index < scene.cameras.length; index++) {
  93856. var camera = scene.cameras[index];
  93857. if (!camera.doNotSerialize) {
  93858. serializationObject.cameras.push(camera.serialize());
  93859. }
  93860. }
  93861. if (scene.activeCamera) {
  93862. serializationObject.activeCameraID = scene.activeCamera.id;
  93863. }
  93864. // Animations
  93865. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93866. // Materials
  93867. serializationObject.materials = [];
  93868. serializationObject.multiMaterials = [];
  93869. var material;
  93870. for (index = 0; index < scene.materials.length; index++) {
  93871. material = scene.materials[index];
  93872. if (!material.doNotSerialize) {
  93873. serializationObject.materials.push(material.serialize());
  93874. }
  93875. }
  93876. // MultiMaterials
  93877. serializationObject.multiMaterials = [];
  93878. for (index = 0; index < scene.multiMaterials.length; index++) {
  93879. var multiMaterial = scene.multiMaterials[index];
  93880. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93881. }
  93882. // Environment texture
  93883. if (scene.environmentTexture) {
  93884. serializationObject.environmentTexture = scene.environmentTexture.name;
  93885. }
  93886. // Skeletons
  93887. serializationObject.skeletons = [];
  93888. for (index = 0; index < scene.skeletons.length; index++) {
  93889. var skeleton = scene.skeletons[index];
  93890. if (!skeleton.doNotSerialize) {
  93891. serializationObject.skeletons.push(skeleton.serialize());
  93892. }
  93893. }
  93894. // Transform nodes
  93895. serializationObject.transformNodes = [];
  93896. for (index = 0; index < scene.transformNodes.length; index++) {
  93897. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93898. }
  93899. // Geometries
  93900. serializationObject.geometries = {};
  93901. serializationObject.geometries.boxes = [];
  93902. serializationObject.geometries.spheres = [];
  93903. serializationObject.geometries.cylinders = [];
  93904. serializationObject.geometries.toruses = [];
  93905. serializationObject.geometries.grounds = [];
  93906. serializationObject.geometries.planes = [];
  93907. serializationObject.geometries.torusKnots = [];
  93908. serializationObject.geometries.vertexData = [];
  93909. serializedGeometries = [];
  93910. var geometries = scene.getGeometries();
  93911. for (index = 0; index < geometries.length; index++) {
  93912. var geometry = geometries[index];
  93913. if (geometry.isReady()) {
  93914. serializeGeometry(geometry, serializationObject.geometries);
  93915. }
  93916. }
  93917. // Meshes
  93918. serializationObject.meshes = [];
  93919. for (index = 0; index < scene.meshes.length; index++) {
  93920. var abstractMesh = scene.meshes[index];
  93921. if (abstractMesh instanceof BABYLON.Mesh) {
  93922. var mesh = abstractMesh;
  93923. if (!mesh.doNotSerialize) {
  93924. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93925. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93926. }
  93927. }
  93928. }
  93929. }
  93930. // Particles Systems
  93931. serializationObject.particleSystems = [];
  93932. for (index = 0; index < scene.particleSystems.length; index++) {
  93933. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93934. }
  93935. // Lens flares
  93936. serializationObject.lensFlareSystems = [];
  93937. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93938. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93939. }
  93940. // Shadows
  93941. serializationObject.shadowGenerators = [];
  93942. for (index = 0; index < scene.lights.length; index++) {
  93943. light = scene.lights[index];
  93944. var shadowGenerator = light.getShadowGenerator();
  93945. if (shadowGenerator) {
  93946. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93947. }
  93948. }
  93949. // Action Manager
  93950. if (scene.actionManager) {
  93951. serializationObject.actions = scene.actionManager.serialize("scene");
  93952. }
  93953. // Audio
  93954. serializationObject.sounds = [];
  93955. for (index = 0; index < scene.soundTracks.length; index++) {
  93956. var soundtrack = scene.soundTracks[index];
  93957. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93958. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93959. }
  93960. }
  93961. // Effect layers
  93962. serializationObject.effectLayers = [];
  93963. for (index = 0; index < scene.effectLayers.length; index++) {
  93964. var layer = scene.effectLayers[index];
  93965. if (layer.serialize) {
  93966. serializationObject.effectLayers.push(layer.serialize());
  93967. }
  93968. }
  93969. return serializationObject;
  93970. };
  93971. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93972. if (withParents === void 0) { withParents = false; }
  93973. if (withChildren === void 0) { withChildren = false; }
  93974. var serializationObject = {};
  93975. SceneSerializer.ClearCache();
  93976. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93977. if (withParents || withChildren) {
  93978. //deliberate for loop! not for each, appended should be processed as well.
  93979. for (var i = 0; i < toSerialize.length; ++i) {
  93980. if (withChildren) {
  93981. toSerialize[i].getDescendants().forEach(function (node) {
  93982. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93983. toSerialize.push(node);
  93984. }
  93985. });
  93986. }
  93987. //make sure the array doesn't contain the object already
  93988. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93989. toSerialize.push(toSerialize[i].parent);
  93990. }
  93991. }
  93992. }
  93993. toSerialize.forEach(function (mesh) {
  93994. finalizeSingleMesh(mesh, serializationObject);
  93995. });
  93996. return serializationObject;
  93997. };
  93998. return SceneSerializer;
  93999. }());
  94000. BABYLON.SceneSerializer = SceneSerializer;
  94001. })(BABYLON || (BABYLON = {}));
  94002. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94003. var BABYLON;
  94004. (function (BABYLON) {
  94005. var ReflectionProbe = /** @class */ (function () {
  94006. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94007. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94008. var _this = this;
  94009. this.name = name;
  94010. this._viewMatrix = BABYLON.Matrix.Identity();
  94011. this._target = BABYLON.Vector3.Zero();
  94012. this._add = BABYLON.Vector3.Zero();
  94013. this._invertYAxis = false;
  94014. this.position = BABYLON.Vector3.Zero();
  94015. this._scene = scene;
  94016. this._scene.reflectionProbes.push(this);
  94017. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94018. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94019. switch (faceIndex) {
  94020. case 0:
  94021. _this._add.copyFromFloats(1, 0, 0);
  94022. break;
  94023. case 1:
  94024. _this._add.copyFromFloats(-1, 0, 0);
  94025. break;
  94026. case 2:
  94027. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94028. break;
  94029. case 3:
  94030. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94031. break;
  94032. case 4:
  94033. _this._add.copyFromFloats(0, 0, 1);
  94034. break;
  94035. case 5:
  94036. _this._add.copyFromFloats(0, 0, -1);
  94037. break;
  94038. }
  94039. if (_this._attachedMesh) {
  94040. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94041. }
  94042. _this.position.addToRef(_this._add, _this._target);
  94043. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94044. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94045. scene._forcedViewPosition = _this.position;
  94046. });
  94047. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94048. scene._forcedViewPosition = null;
  94049. scene.updateTransformMatrix(true);
  94050. });
  94051. if (scene.activeCamera) {
  94052. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94053. }
  94054. }
  94055. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94056. get: function () {
  94057. return this._renderTargetTexture.samples;
  94058. },
  94059. set: function (value) {
  94060. this._renderTargetTexture.samples = value;
  94061. },
  94062. enumerable: true,
  94063. configurable: true
  94064. });
  94065. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94066. get: function () {
  94067. return this._renderTargetTexture.refreshRate;
  94068. },
  94069. set: function (value) {
  94070. this._renderTargetTexture.refreshRate = value;
  94071. },
  94072. enumerable: true,
  94073. configurable: true
  94074. });
  94075. ReflectionProbe.prototype.getScene = function () {
  94076. return this._scene;
  94077. };
  94078. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94079. get: function () {
  94080. return this._renderTargetTexture;
  94081. },
  94082. enumerable: true,
  94083. configurable: true
  94084. });
  94085. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94086. get: function () {
  94087. return this._renderTargetTexture.renderList;
  94088. },
  94089. enumerable: true,
  94090. configurable: true
  94091. });
  94092. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94093. this._attachedMesh = mesh;
  94094. };
  94095. /**
  94096. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94097. *
  94098. * @param renderingGroupId The rendering group id corresponding to its index
  94099. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94100. */
  94101. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94102. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94103. };
  94104. ReflectionProbe.prototype.dispose = function () {
  94105. var index = this._scene.reflectionProbes.indexOf(this);
  94106. if (index !== -1) {
  94107. // Remove from the scene if found
  94108. this._scene.reflectionProbes.splice(index, 1);
  94109. }
  94110. if (this._renderTargetTexture) {
  94111. this._renderTargetTexture.dispose();
  94112. this._renderTargetTexture = null;
  94113. }
  94114. };
  94115. return ReflectionProbe;
  94116. }());
  94117. BABYLON.ReflectionProbe = ReflectionProbe;
  94118. })(BABYLON || (BABYLON = {}));
  94119. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94120. var BABYLON;
  94121. (function (BABYLON) {
  94122. var Layer = /** @class */ (function () {
  94123. function Layer(name, imgUrl, scene, isBackground, color) {
  94124. this.name = name;
  94125. this.scale = new BABYLON.Vector2(1, 1);
  94126. this.offset = new BABYLON.Vector2(0, 0);
  94127. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94128. this.layerMask = 0x0FFFFFFF;
  94129. this._vertexBuffers = {};
  94130. // Events
  94131. /**
  94132. * An event triggered when the layer is disposed.
  94133. */
  94134. this.onDisposeObservable = new BABYLON.Observable();
  94135. /**
  94136. * An event triggered before rendering the scene
  94137. */
  94138. this.onBeforeRenderObservable = new BABYLON.Observable();
  94139. /**
  94140. * An event triggered after rendering the scene
  94141. */
  94142. this.onAfterRenderObservable = new BABYLON.Observable();
  94143. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94144. this.isBackground = isBackground === undefined ? true : isBackground;
  94145. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94146. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94147. this._scene.layers.push(this);
  94148. var engine = this._scene.getEngine();
  94149. // VBO
  94150. var vertices = [];
  94151. vertices.push(1, 1);
  94152. vertices.push(-1, 1);
  94153. vertices.push(-1, -1);
  94154. vertices.push(1, -1);
  94155. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94156. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94157. this._createIndexBuffer();
  94158. // Effects
  94159. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94160. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94161. }
  94162. Object.defineProperty(Layer.prototype, "onDispose", {
  94163. set: function (callback) {
  94164. if (this._onDisposeObserver) {
  94165. this.onDisposeObservable.remove(this._onDisposeObserver);
  94166. }
  94167. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94168. },
  94169. enumerable: true,
  94170. configurable: true
  94171. });
  94172. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94173. set: function (callback) {
  94174. if (this._onBeforeRenderObserver) {
  94175. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94176. }
  94177. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94178. },
  94179. enumerable: true,
  94180. configurable: true
  94181. });
  94182. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94183. set: function (callback) {
  94184. if (this._onAfterRenderObserver) {
  94185. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94186. }
  94187. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94188. },
  94189. enumerable: true,
  94190. configurable: true
  94191. });
  94192. Layer.prototype._createIndexBuffer = function () {
  94193. var engine = this._scene.getEngine();
  94194. // Indices
  94195. var indices = [];
  94196. indices.push(0);
  94197. indices.push(1);
  94198. indices.push(2);
  94199. indices.push(0);
  94200. indices.push(2);
  94201. indices.push(3);
  94202. this._indexBuffer = engine.createIndexBuffer(indices);
  94203. };
  94204. Layer.prototype._rebuild = function () {
  94205. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94206. if (vb) {
  94207. vb._rebuild();
  94208. }
  94209. this._createIndexBuffer();
  94210. };
  94211. Layer.prototype.render = function () {
  94212. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94213. // Check
  94214. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94215. return;
  94216. var engine = this._scene.getEngine();
  94217. this.onBeforeRenderObservable.notifyObservers(this);
  94218. // Render
  94219. engine.enableEffect(currentEffect);
  94220. engine.setState(false);
  94221. // Texture
  94222. currentEffect.setTexture("textureSampler", this.texture);
  94223. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94224. // Color
  94225. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94226. // Scale / offset
  94227. currentEffect.setVector2("offset", this.offset);
  94228. currentEffect.setVector2("scale", this.scale);
  94229. // VBOs
  94230. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94231. // Draw order
  94232. if (!this.alphaTest) {
  94233. engine.setAlphaMode(this.alphaBlendingMode);
  94234. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94236. }
  94237. else {
  94238. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94239. }
  94240. this.onAfterRenderObservable.notifyObservers(this);
  94241. };
  94242. Layer.prototype.dispose = function () {
  94243. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94244. if (vertexBuffer) {
  94245. vertexBuffer.dispose();
  94246. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94247. }
  94248. if (this._indexBuffer) {
  94249. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94250. this._indexBuffer = null;
  94251. }
  94252. if (this.texture) {
  94253. this.texture.dispose();
  94254. this.texture = null;
  94255. }
  94256. // Remove from scene
  94257. var index = this._scene.layers.indexOf(this);
  94258. this._scene.layers.splice(index, 1);
  94259. // Callback
  94260. this.onDisposeObservable.notifyObservers(this);
  94261. this.onDisposeObservable.clear();
  94262. this.onAfterRenderObservable.clear();
  94263. this.onBeforeRenderObservable.clear();
  94264. };
  94265. return Layer;
  94266. }());
  94267. BABYLON.Layer = Layer;
  94268. })(BABYLON || (BABYLON = {}));
  94269. //# sourceMappingURL=babylon.layer.js.map
  94270. var BABYLON;
  94271. (function (BABYLON) {
  94272. var TextureTools = /** @class */ (function () {
  94273. function TextureTools() {
  94274. }
  94275. /**
  94276. * Uses the GPU to create a copy texture rescaled at a given size
  94277. * @param texture Texture to copy from
  94278. * @param width Desired width
  94279. * @param height Desired height
  94280. * @return Generated texture
  94281. */
  94282. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94283. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94284. var scene = texture.getScene();
  94285. var engine = scene.getEngine();
  94286. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94287. rtt.wrapU = texture.wrapU;
  94288. rtt.wrapV = texture.wrapV;
  94289. rtt.uOffset = texture.uOffset;
  94290. rtt.vOffset = texture.vOffset;
  94291. rtt.uScale = texture.uScale;
  94292. rtt.vScale = texture.vScale;
  94293. rtt.uAng = texture.uAng;
  94294. rtt.vAng = texture.vAng;
  94295. rtt.wAng = texture.wAng;
  94296. rtt.coordinatesIndex = texture.coordinatesIndex;
  94297. rtt.level = texture.level;
  94298. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94299. rtt._texture.isReady = false;
  94300. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94301. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94302. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94303. passPostProcess.getEffect().executeWhenCompiled(function () {
  94304. passPostProcess.onApply = function (effect) {
  94305. effect.setTexture("textureSampler", texture);
  94306. };
  94307. var internalTexture = rtt.getInternalTexture();
  94308. if (internalTexture) {
  94309. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94310. engine.unBindFramebuffer(internalTexture);
  94311. rtt.disposeFramebufferObjects();
  94312. passPostProcess.dispose();
  94313. internalTexture.isReady = true;
  94314. }
  94315. });
  94316. return rtt;
  94317. };
  94318. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94319. if (!scene._environmentBRDFTexture) {
  94320. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94321. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94322. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94323. scene._environmentBRDFTexture = texture;
  94324. }
  94325. return scene._environmentBRDFTexture;
  94326. };
  94327. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  94328. return TextureTools;
  94329. }());
  94330. BABYLON.TextureTools = TextureTools;
  94331. })(BABYLON || (BABYLON = {}));
  94332. //# sourceMappingURL=babylon.textureTools.js.map
  94333. var BABYLON;
  94334. (function (BABYLON) {
  94335. var FramingBehavior = /** @class */ (function () {
  94336. function FramingBehavior() {
  94337. this._mode = FramingBehavior.FitFrustumSidesMode;
  94338. this._radiusScale = 1.0;
  94339. this._positionScale = 0.5;
  94340. this._defaultElevation = 0.3;
  94341. this._elevationReturnTime = 1500;
  94342. this._elevationReturnWaitTime = 1000;
  94343. this._zoomStopsAnimation = false;
  94344. this._framingTime = 1500;
  94345. this._isPointerDown = false;
  94346. this._lastInteractionTime = -Infinity;
  94347. // Framing control
  94348. this._animatables = new Array();
  94349. this._betaIsAnimating = false;
  94350. }
  94351. Object.defineProperty(FramingBehavior.prototype, "name", {
  94352. get: function () {
  94353. return "Framing";
  94354. },
  94355. enumerable: true,
  94356. configurable: true
  94357. });
  94358. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94359. /**
  94360. * Gets current mode used by the behavior.
  94361. */
  94362. get: function () {
  94363. return this._mode;
  94364. },
  94365. /**
  94366. * Sets the current mode used by the behavior
  94367. */
  94368. set: function (mode) {
  94369. this._mode = mode;
  94370. },
  94371. enumerable: true,
  94372. configurable: true
  94373. });
  94374. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94375. /**
  94376. * Gets the scale applied to the radius
  94377. */
  94378. get: function () {
  94379. return this._radiusScale;
  94380. },
  94381. /**
  94382. * Sets the scale applied to the radius (1 by default)
  94383. */
  94384. set: function (radius) {
  94385. this._radiusScale = radius;
  94386. },
  94387. enumerable: true,
  94388. configurable: true
  94389. });
  94390. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94391. /**
  94392. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94393. */
  94394. get: function () {
  94395. return this._positionScale;
  94396. },
  94397. /**
  94398. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94399. */
  94400. set: function (scale) {
  94401. this._positionScale = scale;
  94402. },
  94403. enumerable: true,
  94404. configurable: true
  94405. });
  94406. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94407. /**
  94408. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94409. * behaviour is triggered, in radians.
  94410. */
  94411. get: function () {
  94412. return this._defaultElevation;
  94413. },
  94414. /**
  94415. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94416. * behaviour is triggered, in radians.
  94417. */
  94418. set: function (elevation) {
  94419. this._defaultElevation = elevation;
  94420. },
  94421. enumerable: true,
  94422. configurable: true
  94423. });
  94424. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94425. /**
  94426. * Gets the time (in milliseconds) taken to return to the default beta position.
  94427. * Negative value indicates camera should not return to default.
  94428. */
  94429. get: function () {
  94430. return this._elevationReturnTime;
  94431. },
  94432. /**
  94433. * Sets the time (in milliseconds) taken to return to the default beta position.
  94434. * Negative value indicates camera should not return to default.
  94435. */
  94436. set: function (speed) {
  94437. this._elevationReturnTime = speed;
  94438. },
  94439. enumerable: true,
  94440. configurable: true
  94441. });
  94442. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94443. /**
  94444. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94445. */
  94446. get: function () {
  94447. return this._elevationReturnWaitTime;
  94448. },
  94449. /**
  94450. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94451. */
  94452. set: function (time) {
  94453. this._elevationReturnWaitTime = time;
  94454. },
  94455. enumerable: true,
  94456. configurable: true
  94457. });
  94458. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94459. /**
  94460. * Gets the flag that indicates if user zooming should stop animation.
  94461. */
  94462. get: function () {
  94463. return this._zoomStopsAnimation;
  94464. },
  94465. /**
  94466. * Sets the flag that indicates if user zooming should stop animation.
  94467. */
  94468. set: function (flag) {
  94469. this._zoomStopsAnimation = flag;
  94470. },
  94471. enumerable: true,
  94472. configurable: true
  94473. });
  94474. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94475. /**
  94476. * Gets the transition time when framing the mesh, in milliseconds
  94477. */
  94478. get: function () {
  94479. return this._framingTime;
  94480. },
  94481. /**
  94482. * Sets the transition time when framing the mesh, in milliseconds
  94483. */
  94484. set: function (time) {
  94485. this._framingTime = time;
  94486. },
  94487. enumerable: true,
  94488. configurable: true
  94489. });
  94490. FramingBehavior.prototype.init = function () {
  94491. // Do notihng
  94492. };
  94493. FramingBehavior.prototype.attach = function (camera) {
  94494. var _this = this;
  94495. this._attachedCamera = camera;
  94496. var scene = this._attachedCamera.getScene();
  94497. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94498. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94499. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94500. _this._isPointerDown = true;
  94501. return;
  94502. }
  94503. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94504. _this._isPointerDown = false;
  94505. }
  94506. });
  94507. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94508. if (mesh) {
  94509. _this.zoomOnMesh(mesh);
  94510. }
  94511. });
  94512. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94513. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94514. _this._applyUserInteraction();
  94515. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94516. // back to the default position after a given timeout
  94517. _this._maintainCameraAboveGround();
  94518. });
  94519. };
  94520. FramingBehavior.prototype.detach = function () {
  94521. if (!this._attachedCamera) {
  94522. return;
  94523. }
  94524. var scene = this._attachedCamera.getScene();
  94525. if (this._onPrePointerObservableObserver) {
  94526. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94527. }
  94528. if (this._onAfterCheckInputsObserver) {
  94529. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94530. }
  94531. if (this._onMeshTargetChangedObserver) {
  94532. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94533. }
  94534. this._attachedCamera = null;
  94535. };
  94536. /**
  94537. * Targets the given mesh and updates zoom level accordingly.
  94538. * @param mesh The mesh to target.
  94539. * @param radius Optional. If a cached radius position already exists, overrides default.
  94540. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94541. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94542. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94543. */
  94544. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94545. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94546. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94547. mesh.computeWorldMatrix(true);
  94548. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94549. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94550. };
  94551. /**
  94552. * Targets the given mesh with its children and updates zoom level accordingly.
  94553. * @param mesh The mesh to target.
  94554. * @param radius Optional. If a cached radius position already exists, overrides default.
  94555. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94556. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94557. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94558. */
  94559. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94560. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94561. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94562. mesh.computeWorldMatrix(true);
  94563. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94564. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94565. };
  94566. /**
  94567. * Targets the given meshes with their children and updates zoom level accordingly.
  94568. * @param meshes The mesh to target.
  94569. * @param radius Optional. If a cached radius position already exists, overrides default.
  94570. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94571. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94572. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94573. */
  94574. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94575. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94576. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94577. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94578. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94579. for (var i = 0; i < meshes.length; i++) {
  94580. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94581. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94582. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94583. }
  94584. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94585. };
  94586. /**
  94587. * Targets the given mesh and updates zoom level accordingly.
  94588. * @param mesh The mesh to target.
  94589. * @param radius Optional. If a cached radius position already exists, overrides default.
  94590. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94591. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94592. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94593. */
  94594. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94595. var _this = this;
  94596. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94597. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94598. var zoomTarget;
  94599. if (!this._attachedCamera) {
  94600. return;
  94601. }
  94602. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94603. var bottom = minimumWorld.y;
  94604. var top = maximumWorld.y;
  94605. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94606. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94607. if (focusOnOriginXZ) {
  94608. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94609. }
  94610. else {
  94611. var centerWorld = minimumWorld.add(radiusWorld);
  94612. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94613. }
  94614. if (!this._vectorTransition) {
  94615. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94616. }
  94617. this._betaIsAnimating = true;
  94618. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94619. if (animatable) {
  94620. this._animatables.push(animatable);
  94621. }
  94622. // sets the radius and lower radius bounds
  94623. // Small delta ensures camera is not always at lower zoom limit.
  94624. var radius = 0;
  94625. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94626. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94627. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94628. radius = position;
  94629. }
  94630. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94631. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94632. if (this._attachedCamera.lowerRadiusLimit === null) {
  94633. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94634. }
  94635. }
  94636. // Set sensibilities
  94637. var extend = maximumWorld.subtract(minimumWorld).length();
  94638. this._attachedCamera.panningSensibility = 5000 / extend;
  94639. this._attachedCamera.wheelPrecision = 100 / radius;
  94640. // transition to new radius
  94641. if (!this._radiusTransition) {
  94642. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94643. }
  94644. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94645. _this.stopAllAnimations();
  94646. if (onAnimationEnd) {
  94647. onAnimationEnd();
  94648. }
  94649. if (_this._attachedCamera) {
  94650. _this._attachedCamera.storeState();
  94651. }
  94652. });
  94653. if (animatable) {
  94654. this._animatables.push(animatable);
  94655. }
  94656. };
  94657. /**
  94658. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94659. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94660. * frustum width.
  94661. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94662. * to fully enclose the mesh in the viewing frustum.
  94663. */
  94664. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94665. var size = maximumWorld.subtract(minimumWorld);
  94666. var boxVectorGlobalDiagonal = size.length();
  94667. var frustumSlope = this._getFrustumSlope();
  94668. // Formula for setting distance
  94669. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94670. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94671. // Horizon distance
  94672. var radius = radiusWithoutFraming * this._radiusScale;
  94673. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94674. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94675. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94676. var camera = this._attachedCamera;
  94677. if (!camera) {
  94678. return 0;
  94679. }
  94680. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94681. // Don't exceed the requested limit
  94682. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94683. }
  94684. // Don't exceed the upper radius limit
  94685. if (camera.upperRadiusLimit) {
  94686. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94687. }
  94688. return distance;
  94689. };
  94690. /**
  94691. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94692. * is automatically returned to its default position (expected to be above ground plane).
  94693. */
  94694. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94695. var _this = this;
  94696. if (this._elevationReturnTime < 0) {
  94697. return;
  94698. }
  94699. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94700. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94701. var limitBeta = Math.PI * 0.5;
  94702. // Bring the camera back up if below the ground plane
  94703. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94704. this._betaIsAnimating = true;
  94705. //Transition to new position
  94706. this.stopAllAnimations();
  94707. if (!this._betaTransition) {
  94708. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94709. }
  94710. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94711. _this._clearAnimationLocks();
  94712. _this.stopAllAnimations();
  94713. });
  94714. if (animatabe) {
  94715. this._animatables.push(animatabe);
  94716. }
  94717. }
  94718. };
  94719. /**
  94720. * Returns the frustum slope based on the canvas ratio and camera FOV
  94721. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94722. */
  94723. FramingBehavior.prototype._getFrustumSlope = function () {
  94724. // Calculate the viewport ratio
  94725. // Aspect Ratio is Height/Width.
  94726. var camera = this._attachedCamera;
  94727. if (!camera) {
  94728. return BABYLON.Vector2.Zero();
  94729. }
  94730. var engine = camera.getScene().getEngine();
  94731. var aspectRatio = engine.getAspectRatio(camera);
  94732. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94733. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94734. var frustumSlopeY = Math.tan(camera.fov / 2);
  94735. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94736. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94737. // along the forward vector.
  94738. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94739. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94740. };
  94741. /**
  94742. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94743. */
  94744. FramingBehavior.prototype._clearAnimationLocks = function () {
  94745. this._betaIsAnimating = false;
  94746. };
  94747. /**
  94748. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94749. */
  94750. FramingBehavior.prototype._applyUserInteraction = function () {
  94751. if (this.isUserIsMoving) {
  94752. this._lastInteractionTime = BABYLON.Tools.Now;
  94753. this.stopAllAnimations();
  94754. this._clearAnimationLocks();
  94755. }
  94756. };
  94757. /**
  94758. * Stops and removes all animations that have been applied to the camera
  94759. */
  94760. FramingBehavior.prototype.stopAllAnimations = function () {
  94761. if (this._attachedCamera) {
  94762. this._attachedCamera.animations = [];
  94763. }
  94764. while (this._animatables.length) {
  94765. if (this._animatables[0]) {
  94766. this._animatables[0].onAnimationEnd = null;
  94767. this._animatables[0].stop();
  94768. }
  94769. this._animatables.shift();
  94770. }
  94771. };
  94772. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94773. /**
  94774. * Gets a value indicating if the user is moving the camera
  94775. */
  94776. get: function () {
  94777. if (!this._attachedCamera) {
  94778. return false;
  94779. }
  94780. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94781. this._attachedCamera.inertialBetaOffset !== 0 ||
  94782. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94783. this._attachedCamera.inertialPanningX !== 0 ||
  94784. this._attachedCamera.inertialPanningY !== 0 ||
  94785. this._isPointerDown;
  94786. },
  94787. enumerable: true,
  94788. configurable: true
  94789. });
  94790. /**
  94791. * The easing function used by animations
  94792. */
  94793. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94794. /**
  94795. * The easing mode used by animations
  94796. */
  94797. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94798. // Statics
  94799. /**
  94800. * The camera can move all the way towards the mesh.
  94801. */
  94802. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94803. /**
  94804. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94805. */
  94806. FramingBehavior.FitFrustumSidesMode = 1;
  94807. return FramingBehavior;
  94808. }());
  94809. BABYLON.FramingBehavior = FramingBehavior;
  94810. })(BABYLON || (BABYLON = {}));
  94811. //# sourceMappingURL=babylon.framingBehavior.js.map
  94812. var BABYLON;
  94813. (function (BABYLON) {
  94814. /**
  94815. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94816. */
  94817. var BouncingBehavior = /** @class */ (function () {
  94818. function BouncingBehavior() {
  94819. /**
  94820. * The duration of the animation, in milliseconds
  94821. */
  94822. this.transitionDuration = 450;
  94823. /**
  94824. * Length of the distance animated by the transition when lower radius is reached
  94825. */
  94826. this.lowerRadiusTransitionRange = 2;
  94827. /**
  94828. * Length of the distance animated by the transition when upper radius is reached
  94829. */
  94830. this.upperRadiusTransitionRange = -2;
  94831. this._autoTransitionRange = false;
  94832. // Animations
  94833. this._radiusIsAnimating = false;
  94834. this._radiusBounceTransition = null;
  94835. this._animatables = new Array();
  94836. }
  94837. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94838. get: function () {
  94839. return "Bouncing";
  94840. },
  94841. enumerable: true,
  94842. configurable: true
  94843. });
  94844. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94845. /**
  94846. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94847. */
  94848. get: function () {
  94849. return this._autoTransitionRange;
  94850. },
  94851. /**
  94852. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94853. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94854. */
  94855. set: function (value) {
  94856. var _this = this;
  94857. if (this._autoTransitionRange === value) {
  94858. return;
  94859. }
  94860. this._autoTransitionRange = value;
  94861. var camera = this._attachedCamera;
  94862. if (!camera) {
  94863. return;
  94864. }
  94865. if (value) {
  94866. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94867. if (!mesh) {
  94868. return;
  94869. }
  94870. mesh.computeWorldMatrix(true);
  94871. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94872. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94873. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94874. });
  94875. }
  94876. else if (this._onMeshTargetChangedObserver) {
  94877. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94878. }
  94879. },
  94880. enumerable: true,
  94881. configurable: true
  94882. });
  94883. BouncingBehavior.prototype.init = function () {
  94884. // Do notihng
  94885. };
  94886. BouncingBehavior.prototype.attach = function (camera) {
  94887. var _this = this;
  94888. this._attachedCamera = camera;
  94889. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94890. if (!_this._attachedCamera) {
  94891. return;
  94892. }
  94893. // Add the bounce animation to the lower radius limit
  94894. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94895. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94896. }
  94897. // Add the bounce animation to the upper radius limit
  94898. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94899. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94900. }
  94901. });
  94902. };
  94903. BouncingBehavior.prototype.detach = function () {
  94904. if (!this._attachedCamera) {
  94905. return;
  94906. }
  94907. if (this._onAfterCheckInputsObserver) {
  94908. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94909. }
  94910. if (this._onMeshTargetChangedObserver) {
  94911. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94912. }
  94913. this._attachedCamera = null;
  94914. };
  94915. /**
  94916. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94917. * @param radiusLimit The limit to check against.
  94918. * @return Bool to indicate if at limit.
  94919. */
  94920. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94921. if (!this._attachedCamera) {
  94922. return false;
  94923. }
  94924. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94925. return true;
  94926. }
  94927. return false;
  94928. };
  94929. /**
  94930. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94931. * @param radiusDelta The delta by which to animate to. Can be negative.
  94932. */
  94933. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94934. var _this = this;
  94935. if (!this._attachedCamera) {
  94936. return;
  94937. }
  94938. if (!this._radiusBounceTransition) {
  94939. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94940. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94941. }
  94942. // Prevent zoom until bounce has completed
  94943. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94944. this._attachedCamera.wheelPrecision = Infinity;
  94945. this._attachedCamera.inertialRadiusOffset = 0;
  94946. // Animate to the radius limit
  94947. this.stopAllAnimations();
  94948. this._radiusIsAnimating = true;
  94949. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94950. if (animatable) {
  94951. this._animatables.push(animatable);
  94952. }
  94953. };
  94954. /**
  94955. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94956. */
  94957. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94958. this._radiusIsAnimating = false;
  94959. if (this._attachedCamera) {
  94960. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94961. }
  94962. };
  94963. /**
  94964. * Stops and removes all animations that have been applied to the camera
  94965. */
  94966. BouncingBehavior.prototype.stopAllAnimations = function () {
  94967. if (this._attachedCamera) {
  94968. this._attachedCamera.animations = [];
  94969. }
  94970. while (this._animatables.length) {
  94971. this._animatables[0].onAnimationEnd = null;
  94972. this._animatables[0].stop();
  94973. this._animatables.shift();
  94974. }
  94975. };
  94976. /**
  94977. * The easing function used by animations
  94978. */
  94979. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94980. /**
  94981. * The easing mode used by animations
  94982. */
  94983. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94984. return BouncingBehavior;
  94985. }());
  94986. BABYLON.BouncingBehavior = BouncingBehavior;
  94987. })(BABYLON || (BABYLON = {}));
  94988. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94989. var BABYLON;
  94990. (function (BABYLON) {
  94991. var AutoRotationBehavior = /** @class */ (function () {
  94992. function AutoRotationBehavior() {
  94993. this._zoomStopsAnimation = false;
  94994. this._idleRotationSpeed = 0.05;
  94995. this._idleRotationWaitTime = 2000;
  94996. this._idleRotationSpinupTime = 2000;
  94997. this._isPointerDown = false;
  94998. this._lastFrameTime = null;
  94999. this._lastInteractionTime = -Infinity;
  95000. this._cameraRotationSpeed = 0;
  95001. this._lastFrameRadius = 0;
  95002. }
  95003. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95004. get: function () {
  95005. return "AutoRotation";
  95006. },
  95007. enumerable: true,
  95008. configurable: true
  95009. });
  95010. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95011. /**
  95012. * Gets the flag that indicates if user zooming should stop animation.
  95013. */
  95014. get: function () {
  95015. return this._zoomStopsAnimation;
  95016. },
  95017. /**
  95018. * Sets the flag that indicates if user zooming should stop animation.
  95019. */
  95020. set: function (flag) {
  95021. this._zoomStopsAnimation = flag;
  95022. },
  95023. enumerable: true,
  95024. configurable: true
  95025. });
  95026. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95027. /**
  95028. * Gets the default speed at which the camera rotates around the model.
  95029. */
  95030. get: function () {
  95031. return this._idleRotationSpeed;
  95032. },
  95033. /**
  95034. * Sets the default speed at which the camera rotates around the model.
  95035. */
  95036. set: function (speed) {
  95037. this._idleRotationSpeed = speed;
  95038. },
  95039. enumerable: true,
  95040. configurable: true
  95041. });
  95042. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95043. /**
  95044. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95045. */
  95046. get: function () {
  95047. return this._idleRotationWaitTime;
  95048. },
  95049. /**
  95050. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95051. */
  95052. set: function (time) {
  95053. this._idleRotationWaitTime = time;
  95054. },
  95055. enumerable: true,
  95056. configurable: true
  95057. });
  95058. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95059. /**
  95060. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95061. */
  95062. get: function () {
  95063. return this._idleRotationSpinupTime;
  95064. },
  95065. /**
  95066. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95067. */
  95068. set: function (time) {
  95069. this._idleRotationSpinupTime = time;
  95070. },
  95071. enumerable: true,
  95072. configurable: true
  95073. });
  95074. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95075. /**
  95076. * Gets a value indicating if the camera is currently rotating because of this behavior
  95077. */
  95078. get: function () {
  95079. return Math.abs(this._cameraRotationSpeed) > 0;
  95080. },
  95081. enumerable: true,
  95082. configurable: true
  95083. });
  95084. AutoRotationBehavior.prototype.init = function () {
  95085. // Do notihng
  95086. };
  95087. AutoRotationBehavior.prototype.attach = function (camera) {
  95088. var _this = this;
  95089. this._attachedCamera = camera;
  95090. var scene = this._attachedCamera.getScene();
  95091. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95092. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95093. _this._isPointerDown = true;
  95094. return;
  95095. }
  95096. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95097. _this._isPointerDown = false;
  95098. }
  95099. });
  95100. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95101. var now = BABYLON.Tools.Now;
  95102. var dt = 0;
  95103. if (_this._lastFrameTime != null) {
  95104. dt = now - _this._lastFrameTime;
  95105. }
  95106. _this._lastFrameTime = now;
  95107. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95108. _this._applyUserInteraction();
  95109. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95110. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95111. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95112. // Step camera rotation by rotation speed
  95113. if (_this._attachedCamera) {
  95114. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95115. }
  95116. });
  95117. };
  95118. AutoRotationBehavior.prototype.detach = function () {
  95119. if (!this._attachedCamera) {
  95120. return;
  95121. }
  95122. var scene = this._attachedCamera.getScene();
  95123. if (this._onPrePointerObservableObserver) {
  95124. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95125. }
  95126. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95127. this._attachedCamera = null;
  95128. };
  95129. /**
  95130. * Returns true if user is scrolling.
  95131. * @return true if user is scrolling.
  95132. */
  95133. AutoRotationBehavior.prototype._userIsZooming = function () {
  95134. if (!this._attachedCamera) {
  95135. return false;
  95136. }
  95137. return this._attachedCamera.inertialRadiusOffset !== 0;
  95138. };
  95139. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95140. if (!this._attachedCamera) {
  95141. return false;
  95142. }
  95143. var zoomHasHitLimit = false;
  95144. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95145. zoomHasHitLimit = true;
  95146. }
  95147. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95148. this._lastFrameRadius = this._attachedCamera.radius;
  95149. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95150. };
  95151. /**
  95152. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95153. */
  95154. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95155. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95156. this._lastInteractionTime = BABYLON.Tools.Now;
  95157. }
  95158. };
  95159. // Tools
  95160. AutoRotationBehavior.prototype._userIsMoving = function () {
  95161. if (!this._attachedCamera) {
  95162. return false;
  95163. }
  95164. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95165. this._attachedCamera.inertialBetaOffset !== 0 ||
  95166. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95167. this._attachedCamera.inertialPanningX !== 0 ||
  95168. this._attachedCamera.inertialPanningY !== 0 ||
  95169. this._isPointerDown;
  95170. };
  95171. return AutoRotationBehavior;
  95172. }());
  95173. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95174. })(BABYLON || (BABYLON = {}));
  95175. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95176. var BABYLON;
  95177. (function (BABYLON) {
  95178. var NullEngineOptions = /** @class */ (function () {
  95179. function NullEngineOptions() {
  95180. this.renderWidth = 512;
  95181. this.renderHeight = 256;
  95182. this.textureSize = 512;
  95183. this.deterministicLockstep = false;
  95184. this.lockstepMaxSteps = 4;
  95185. }
  95186. return NullEngineOptions;
  95187. }());
  95188. BABYLON.NullEngineOptions = NullEngineOptions;
  95189. /**
  95190. * The null engine class provides support for headless version of babylon.js.
  95191. * This can be used in server side scenario or for testing purposes
  95192. */
  95193. var NullEngine = /** @class */ (function (_super) {
  95194. __extends(NullEngine, _super);
  95195. function NullEngine(options) {
  95196. if (options === void 0) { options = new NullEngineOptions(); }
  95197. var _this = _super.call(this, null) || this;
  95198. if (options.deterministicLockstep === undefined) {
  95199. options.deterministicLockstep = false;
  95200. }
  95201. if (options.lockstepMaxSteps === undefined) {
  95202. options.lockstepMaxSteps = 4;
  95203. }
  95204. _this._options = options;
  95205. // Init caps
  95206. // We consider we are on a webgl1 capable device
  95207. _this._caps = new BABYLON.EngineCapabilities();
  95208. _this._caps.maxTexturesImageUnits = 16;
  95209. _this._caps.maxVertexTextureImageUnits = 16;
  95210. _this._caps.maxTextureSize = 512;
  95211. _this._caps.maxCubemapTextureSize = 512;
  95212. _this._caps.maxRenderTextureSize = 512;
  95213. _this._caps.maxVertexAttribs = 16;
  95214. _this._caps.maxVaryingVectors = 16;
  95215. _this._caps.maxFragmentUniformVectors = 16;
  95216. _this._caps.maxVertexUniformVectors = 16;
  95217. // Extensions
  95218. _this._caps.standardDerivatives = false;
  95219. _this._caps.astc = null;
  95220. _this._caps.s3tc = null;
  95221. _this._caps.pvrtc = null;
  95222. _this._caps.etc1 = null;
  95223. _this._caps.etc2 = null;
  95224. _this._caps.textureAnisotropicFilterExtension = null;
  95225. _this._caps.maxAnisotropy = 0;
  95226. _this._caps.uintIndices = false;
  95227. _this._caps.fragmentDepthSupported = false;
  95228. _this._caps.highPrecisionShaderSupported = true;
  95229. _this._caps.colorBufferFloat = false;
  95230. _this._caps.textureFloat = false;
  95231. _this._caps.textureFloatLinearFiltering = false;
  95232. _this._caps.textureFloatRender = false;
  95233. _this._caps.textureHalfFloat = false;
  95234. _this._caps.textureHalfFloatLinearFiltering = false;
  95235. _this._caps.textureHalfFloatRender = false;
  95236. _this._caps.textureLOD = false;
  95237. _this._caps.drawBuffersExtension = false;
  95238. _this._caps.depthTextureExtension = false;
  95239. _this._caps.vertexArrayObject = false;
  95240. _this._caps.instancedArrays = false;
  95241. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95242. // Wrappers
  95243. if (typeof URL === "undefined") {
  95244. URL = {
  95245. createObjectURL: function () { },
  95246. revokeObjectURL: function () { }
  95247. };
  95248. }
  95249. if (typeof Blob === "undefined") {
  95250. Blob = function () { };
  95251. }
  95252. return _this;
  95253. }
  95254. NullEngine.prototype.isDeterministicLockStep = function () {
  95255. return this._options.deterministicLockstep;
  95256. };
  95257. NullEngine.prototype.getLockstepMaxSteps = function () {
  95258. return this._options.lockstepMaxSteps;
  95259. };
  95260. NullEngine.prototype.getHardwareScalingLevel = function () {
  95261. return 1.0;
  95262. };
  95263. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95264. return {
  95265. capacity: 0,
  95266. references: 1,
  95267. is32Bits: false
  95268. };
  95269. };
  95270. NullEngine.prototype.createIndexBuffer = function (indices) {
  95271. return {
  95272. capacity: 0,
  95273. references: 1,
  95274. is32Bits: false
  95275. };
  95276. };
  95277. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95278. if (stencil === void 0) { stencil = false; }
  95279. };
  95280. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95281. if (useScreen === void 0) { useScreen = false; }
  95282. if (!useScreen && this._currentRenderTarget) {
  95283. return this._currentRenderTarget.width;
  95284. }
  95285. return this._options.renderWidth;
  95286. };
  95287. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95288. if (useScreen === void 0) { useScreen = false; }
  95289. if (!useScreen && this._currentRenderTarget) {
  95290. return this._currentRenderTarget.height;
  95291. }
  95292. return this._options.renderHeight;
  95293. };
  95294. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95295. this._cachedViewport = viewport;
  95296. };
  95297. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95298. return {
  95299. transformFeedback: null,
  95300. __SPECTOR_rebuildProgram: null
  95301. };
  95302. };
  95303. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95304. return [];
  95305. };
  95306. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95307. return [];
  95308. };
  95309. NullEngine.prototype.bindSamplers = function (effect) {
  95310. this._currentEffect = null;
  95311. };
  95312. NullEngine.prototype.enableEffect = function (effect) {
  95313. this._currentEffect = effect;
  95314. if (effect.onBind) {
  95315. effect.onBind(effect);
  95316. }
  95317. effect.onBindObservable.notifyObservers(effect);
  95318. };
  95319. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95320. if (zOffset === void 0) { zOffset = 0; }
  95321. if (reverseSide === void 0) { reverseSide = false; }
  95322. };
  95323. NullEngine.prototype.setIntArray = function (uniform, array) {
  95324. };
  95325. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95326. };
  95327. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95328. };
  95329. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95330. };
  95331. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95332. };
  95333. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95334. };
  95335. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95336. };
  95337. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95338. };
  95339. NullEngine.prototype.setArray = function (uniform, array) {
  95340. };
  95341. NullEngine.prototype.setArray2 = function (uniform, array) {
  95342. };
  95343. NullEngine.prototype.setArray3 = function (uniform, array) {
  95344. };
  95345. NullEngine.prototype.setArray4 = function (uniform, array) {
  95346. };
  95347. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95348. };
  95349. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95350. };
  95351. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95352. };
  95353. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95354. };
  95355. NullEngine.prototype.setFloat = function (uniform, value) {
  95356. };
  95357. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95358. };
  95359. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95360. };
  95361. NullEngine.prototype.setBool = function (uniform, bool) {
  95362. };
  95363. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95364. };
  95365. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95366. };
  95367. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95368. };
  95369. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95370. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95371. if (this._alphaMode === mode) {
  95372. return;
  95373. }
  95374. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95375. if (!noDepthWriteChange) {
  95376. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95377. }
  95378. this._alphaMode = mode;
  95379. };
  95380. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95381. };
  95382. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95383. if (this.preventCacheWipeBetweenFrames) {
  95384. return;
  95385. }
  95386. this.resetTextureCache();
  95387. this._currentEffect = null;
  95388. if (bruteForce) {
  95389. this._currentProgram = null;
  95390. this._stencilState.reset();
  95391. this._depthCullingState.reset();
  95392. this._alphaState.reset();
  95393. }
  95394. this._cachedVertexBuffers = null;
  95395. this._cachedIndexBuffer = null;
  95396. this._cachedEffectForVertexBuffers = null;
  95397. };
  95398. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95399. };
  95400. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95401. };
  95402. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95403. };
  95404. NullEngine.prototype._createTexture = function () {
  95405. return {};
  95406. };
  95407. NullEngine.prototype._releaseTexture = function (texture) {
  95408. };
  95409. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95411. if (onLoad === void 0) { onLoad = null; }
  95412. if (onError === void 0) { onError = null; }
  95413. if (buffer === void 0) { buffer = null; }
  95414. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95415. var url = String(urlArg);
  95416. texture.url = url;
  95417. texture.generateMipMaps = !noMipmap;
  95418. texture.samplingMode = samplingMode;
  95419. texture.invertY = invertY;
  95420. texture.baseWidth = this._options.textureSize;
  95421. texture.baseHeight = this._options.textureSize;
  95422. texture.width = this._options.textureSize;
  95423. texture.height = this._options.textureSize;
  95424. if (format) {
  95425. texture.format = format;
  95426. }
  95427. texture.isReady = true;
  95428. if (onLoad) {
  95429. onLoad();
  95430. }
  95431. return texture;
  95432. };
  95433. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95434. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95435. if (options !== undefined && typeof options === "object") {
  95436. fullOptions.generateMipMaps = options.generateMipMaps;
  95437. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95438. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95439. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95440. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95441. }
  95442. else {
  95443. fullOptions.generateMipMaps = options;
  95444. fullOptions.generateDepthBuffer = true;
  95445. fullOptions.generateStencilBuffer = false;
  95446. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95447. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95448. }
  95449. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95450. var width = size.width || size;
  95451. var height = size.height || size;
  95452. texture._depthStencilBuffer = {};
  95453. texture._framebuffer = {};
  95454. texture.baseWidth = width;
  95455. texture.baseHeight = height;
  95456. texture.width = width;
  95457. texture.height = height;
  95458. texture.isReady = true;
  95459. texture.samples = 1;
  95460. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95461. texture.samplingMode = fullOptions.samplingMode;
  95462. texture.type = fullOptions.type;
  95463. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95464. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95465. return texture;
  95466. };
  95467. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95468. texture.samplingMode = samplingMode;
  95469. };
  95470. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95471. if (this._currentRenderTarget) {
  95472. this.unBindFramebuffer(this._currentRenderTarget);
  95473. }
  95474. this._currentRenderTarget = texture;
  95475. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95476. if (this._cachedViewport && !forceFullscreenViewport) {
  95477. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95478. }
  95479. };
  95480. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95481. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95482. this._currentRenderTarget = null;
  95483. if (onBeforeUnbind) {
  95484. if (texture._MSAAFramebuffer) {
  95485. this._currentFramebuffer = texture._framebuffer;
  95486. }
  95487. onBeforeUnbind();
  95488. }
  95489. this._currentFramebuffer = null;
  95490. };
  95491. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95492. var vbo = {
  95493. capacity: 1,
  95494. references: 1,
  95495. is32Bits: false
  95496. };
  95497. return vbo;
  95498. };
  95499. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95500. if (offset === void 0) { offset = 0; }
  95501. };
  95502. /**
  95503. * Updates a dynamic vertex buffer.
  95504. * @param vertexBuffer the vertex buffer to update
  95505. * @param data the data used to update the vertex buffer
  95506. * @param byteOffset the byte offset of the data (optional)
  95507. * @param byteLength the byte length of the data (optional)
  95508. */
  95509. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95510. };
  95511. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95512. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95513. this._boundTexturesCache[this._activeChannel] = texture;
  95514. }
  95515. };
  95516. NullEngine.prototype._bindTexture = function (channel, texture) {
  95517. if (channel < 0) {
  95518. return;
  95519. }
  95520. this._bindTextureDirectly(0, texture);
  95521. };
  95522. NullEngine.prototype._releaseBuffer = function (buffer) {
  95523. buffer.references--;
  95524. if (buffer.references === 0) {
  95525. return true;
  95526. }
  95527. return false;
  95528. };
  95529. NullEngine.prototype.releaseEffects = function () {
  95530. };
  95531. return NullEngine;
  95532. }(BABYLON.Engine));
  95533. BABYLON.NullEngine = NullEngine;
  95534. })(BABYLON || (BABYLON = {}));
  95535. //# sourceMappingURL=babylon.nullEngine.js.map
  95536. var BABYLON;
  95537. (function (BABYLON) {
  95538. /**
  95539. * This class can be used to get instrumentation data from a Babylon engine
  95540. */
  95541. var EngineInstrumentation = /** @class */ (function () {
  95542. function EngineInstrumentation(engine) {
  95543. this.engine = engine;
  95544. this._captureGPUFrameTime = false;
  95545. this._gpuFrameTime = new BABYLON.PerfCounter();
  95546. this._captureShaderCompilationTime = false;
  95547. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95548. // Observers
  95549. this._onBeginFrameObserver = null;
  95550. this._onEndFrameObserver = null;
  95551. this._onBeforeShaderCompilationObserver = null;
  95552. this._onAfterShaderCompilationObserver = null;
  95553. }
  95554. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95555. // Properties
  95556. /**
  95557. * Gets the perf counter used for GPU frame time
  95558. */
  95559. get: function () {
  95560. return this._gpuFrameTime;
  95561. },
  95562. enumerable: true,
  95563. configurable: true
  95564. });
  95565. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95566. /**
  95567. * Gets the GPU frame time capture status
  95568. */
  95569. get: function () {
  95570. return this._captureGPUFrameTime;
  95571. },
  95572. /**
  95573. * Enable or disable the GPU frame time capture
  95574. */
  95575. set: function (value) {
  95576. var _this = this;
  95577. if (value === this._captureGPUFrameTime) {
  95578. return;
  95579. }
  95580. this._captureGPUFrameTime = value;
  95581. if (value) {
  95582. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95583. if (!_this._gpuFrameTimeToken) {
  95584. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95585. }
  95586. });
  95587. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95588. if (!_this._gpuFrameTimeToken) {
  95589. return;
  95590. }
  95591. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95592. if (time > -1) {
  95593. _this._gpuFrameTimeToken = null;
  95594. _this._gpuFrameTime.fetchNewFrame();
  95595. _this._gpuFrameTime.addCount(time, true);
  95596. }
  95597. });
  95598. }
  95599. else {
  95600. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95601. this._onBeginFrameObserver = null;
  95602. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95603. this._onEndFrameObserver = null;
  95604. }
  95605. },
  95606. enumerable: true,
  95607. configurable: true
  95608. });
  95609. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95610. /**
  95611. * Gets the perf counter used for shader compilation time
  95612. */
  95613. get: function () {
  95614. return this._shaderCompilationTime;
  95615. },
  95616. enumerable: true,
  95617. configurable: true
  95618. });
  95619. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95620. /**
  95621. * Gets the shader compilation time capture status
  95622. */
  95623. get: function () {
  95624. return this._captureShaderCompilationTime;
  95625. },
  95626. /**
  95627. * Enable or disable the shader compilation time capture
  95628. */
  95629. set: function (value) {
  95630. var _this = this;
  95631. if (value === this._captureShaderCompilationTime) {
  95632. return;
  95633. }
  95634. this._captureShaderCompilationTime = value;
  95635. if (value) {
  95636. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95637. _this._shaderCompilationTime.fetchNewFrame();
  95638. _this._shaderCompilationTime.beginMonitoring();
  95639. });
  95640. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95641. _this._shaderCompilationTime.endMonitoring();
  95642. });
  95643. }
  95644. else {
  95645. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95646. this._onBeforeShaderCompilationObserver = null;
  95647. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95648. this._onAfterShaderCompilationObserver = null;
  95649. }
  95650. },
  95651. enumerable: true,
  95652. configurable: true
  95653. });
  95654. EngineInstrumentation.prototype.dispose = function () {
  95655. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95656. this._onBeginFrameObserver = null;
  95657. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95658. this._onEndFrameObserver = null;
  95659. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95660. this._onBeforeShaderCompilationObserver = null;
  95661. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95662. this._onAfterShaderCompilationObserver = null;
  95663. this.engine = null;
  95664. };
  95665. return EngineInstrumentation;
  95666. }());
  95667. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95668. })(BABYLON || (BABYLON = {}));
  95669. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95670. var BABYLON;
  95671. (function (BABYLON) {
  95672. /**
  95673. * This class can be used to get instrumentation data from a Babylon engine
  95674. */
  95675. var SceneInstrumentation = /** @class */ (function () {
  95676. function SceneInstrumentation(scene) {
  95677. var _this = this;
  95678. this.scene = scene;
  95679. this._captureActiveMeshesEvaluationTime = false;
  95680. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95681. this._captureRenderTargetsRenderTime = false;
  95682. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95683. this._captureFrameTime = false;
  95684. this._frameTime = new BABYLON.PerfCounter();
  95685. this._captureRenderTime = false;
  95686. this._renderTime = new BABYLON.PerfCounter();
  95687. this._captureInterFrameTime = false;
  95688. this._interFrameTime = new BABYLON.PerfCounter();
  95689. this._captureParticlesRenderTime = false;
  95690. this._particlesRenderTime = new BABYLON.PerfCounter();
  95691. this._captureSpritesRenderTime = false;
  95692. this._spritesRenderTime = new BABYLON.PerfCounter();
  95693. this._capturePhysicsTime = false;
  95694. this._physicsTime = new BABYLON.PerfCounter();
  95695. this._captureAnimationsTime = false;
  95696. this._animationsTime = new BABYLON.PerfCounter();
  95697. // Observers
  95698. this._onBeforeActiveMeshesEvaluationObserver = null;
  95699. this._onAfterActiveMeshesEvaluationObserver = null;
  95700. this._onBeforeRenderTargetsRenderObserver = null;
  95701. this._onAfterRenderTargetsRenderObserver = null;
  95702. this._onAfterRenderObserver = null;
  95703. this._onBeforeDrawPhaseObserver = null;
  95704. this._onAfterDrawPhaseObserver = null;
  95705. this._onBeforeAnimationsObserver = null;
  95706. this._onBeforeParticlesRenderingObserver = null;
  95707. this._onAfterParticlesRenderingObserver = null;
  95708. this._onBeforeSpritesRenderingObserver = null;
  95709. this._onAfterSpritesRenderingObserver = null;
  95710. this._onBeforePhysicsObserver = null;
  95711. this._onAfterPhysicsObserver = null;
  95712. this._onAfterAnimationsObserver = null;
  95713. // Before render
  95714. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95715. if (_this._captureActiveMeshesEvaluationTime) {
  95716. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95717. }
  95718. if (_this._captureRenderTargetsRenderTime) {
  95719. _this._renderTargetsRenderTime.fetchNewFrame();
  95720. }
  95721. if (_this._captureFrameTime) {
  95722. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95723. _this._frameTime.beginMonitoring();
  95724. }
  95725. if (_this._captureInterFrameTime) {
  95726. _this._interFrameTime.endMonitoring();
  95727. }
  95728. if (_this._captureParticlesRenderTime) {
  95729. _this._particlesRenderTime.fetchNewFrame();
  95730. }
  95731. if (_this._captureSpritesRenderTime) {
  95732. _this._spritesRenderTime.fetchNewFrame();
  95733. }
  95734. if (_this._captureAnimationsTime) {
  95735. _this._animationsTime.beginMonitoring();
  95736. }
  95737. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95738. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95739. });
  95740. // After render
  95741. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95742. if (_this._captureFrameTime) {
  95743. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95744. _this._frameTime.endMonitoring();
  95745. }
  95746. if (_this._captureRenderTime) {
  95747. _this._renderTime.endMonitoring(false);
  95748. }
  95749. if (_this._captureInterFrameTime) {
  95750. _this._interFrameTime.beginMonitoring();
  95751. }
  95752. });
  95753. }
  95754. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95755. // Properties
  95756. /**
  95757. * Gets the perf counter used for active meshes evaluation time
  95758. */
  95759. get: function () {
  95760. return this._activeMeshesEvaluationTime;
  95761. },
  95762. enumerable: true,
  95763. configurable: true
  95764. });
  95765. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95766. /**
  95767. * Gets the active meshes evaluation time capture status
  95768. */
  95769. get: function () {
  95770. return this._captureActiveMeshesEvaluationTime;
  95771. },
  95772. /**
  95773. * Enable or disable the active meshes evaluation time capture
  95774. */
  95775. set: function (value) {
  95776. var _this = this;
  95777. if (value === this._captureActiveMeshesEvaluationTime) {
  95778. return;
  95779. }
  95780. this._captureActiveMeshesEvaluationTime = value;
  95781. if (value) {
  95782. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95783. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95784. _this._activeMeshesEvaluationTime.beginMonitoring();
  95785. });
  95786. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95787. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95788. _this._activeMeshesEvaluationTime.endMonitoring();
  95789. });
  95790. }
  95791. else {
  95792. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95793. this._onBeforeActiveMeshesEvaluationObserver = null;
  95794. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95795. this._onAfterActiveMeshesEvaluationObserver = null;
  95796. }
  95797. },
  95798. enumerable: true,
  95799. configurable: true
  95800. });
  95801. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95802. /**
  95803. * Gets the perf counter used for render targets render time
  95804. */
  95805. get: function () {
  95806. return this._renderTargetsRenderTime;
  95807. },
  95808. enumerable: true,
  95809. configurable: true
  95810. });
  95811. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95812. /**
  95813. * Gets the render targets render time capture status
  95814. */
  95815. get: function () {
  95816. return this._captureRenderTargetsRenderTime;
  95817. },
  95818. /**
  95819. * Enable or disable the render targets render time capture
  95820. */
  95821. set: function (value) {
  95822. var _this = this;
  95823. if (value === this._captureRenderTargetsRenderTime) {
  95824. return;
  95825. }
  95826. this._captureRenderTargetsRenderTime = value;
  95827. if (value) {
  95828. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95829. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95830. _this._renderTargetsRenderTime.beginMonitoring();
  95831. });
  95832. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95833. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95834. _this._renderTargetsRenderTime.endMonitoring(false);
  95835. });
  95836. }
  95837. else {
  95838. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95839. this._onBeforeRenderTargetsRenderObserver = null;
  95840. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95841. this._onAfterRenderTargetsRenderObserver = null;
  95842. }
  95843. },
  95844. enumerable: true,
  95845. configurable: true
  95846. });
  95847. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95848. /**
  95849. * Gets the perf counter used for particles render time
  95850. */
  95851. get: function () {
  95852. return this._particlesRenderTime;
  95853. },
  95854. enumerable: true,
  95855. configurable: true
  95856. });
  95857. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95858. /**
  95859. * Gets the particles render time capture status
  95860. */
  95861. get: function () {
  95862. return this._captureParticlesRenderTime;
  95863. },
  95864. /**
  95865. * Enable or disable the particles render time capture
  95866. */
  95867. set: function (value) {
  95868. var _this = this;
  95869. if (value === this._captureParticlesRenderTime) {
  95870. return;
  95871. }
  95872. this._captureParticlesRenderTime = value;
  95873. if (value) {
  95874. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95875. BABYLON.Tools.StartPerformanceCounter("Particles");
  95876. _this._particlesRenderTime.beginMonitoring();
  95877. });
  95878. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95879. BABYLON.Tools.EndPerformanceCounter("Particles");
  95880. _this._particlesRenderTime.endMonitoring(false);
  95881. });
  95882. }
  95883. else {
  95884. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95885. this._onBeforeParticlesRenderingObserver = null;
  95886. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95887. this._onAfterParticlesRenderingObserver = null;
  95888. }
  95889. },
  95890. enumerable: true,
  95891. configurable: true
  95892. });
  95893. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95894. /**
  95895. * Gets the perf counter used for sprites render time
  95896. */
  95897. get: function () {
  95898. return this._spritesRenderTime;
  95899. },
  95900. enumerable: true,
  95901. configurable: true
  95902. });
  95903. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95904. /**
  95905. * Gets the sprites render time capture status
  95906. */
  95907. get: function () {
  95908. return this._captureSpritesRenderTime;
  95909. },
  95910. /**
  95911. * Enable or disable the sprites render time capture
  95912. */
  95913. set: function (value) {
  95914. var _this = this;
  95915. if (value === this._captureSpritesRenderTime) {
  95916. return;
  95917. }
  95918. this._captureSpritesRenderTime = value;
  95919. if (value) {
  95920. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95921. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95922. _this._spritesRenderTime.beginMonitoring();
  95923. });
  95924. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95925. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95926. _this._spritesRenderTime.endMonitoring(false);
  95927. });
  95928. }
  95929. else {
  95930. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95931. this._onBeforeSpritesRenderingObserver = null;
  95932. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95933. this._onAfterSpritesRenderingObserver = null;
  95934. }
  95935. },
  95936. enumerable: true,
  95937. configurable: true
  95938. });
  95939. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95940. /**
  95941. * Gets the perf counter used for physics time
  95942. */
  95943. get: function () {
  95944. return this._physicsTime;
  95945. },
  95946. enumerable: true,
  95947. configurable: true
  95948. });
  95949. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95950. /**
  95951. * Gets the physics time capture status
  95952. */
  95953. get: function () {
  95954. return this._capturePhysicsTime;
  95955. },
  95956. /**
  95957. * Enable or disable the physics time capture
  95958. */
  95959. set: function (value) {
  95960. var _this = this;
  95961. if (value === this._capturePhysicsTime) {
  95962. return;
  95963. }
  95964. this._capturePhysicsTime = value;
  95965. if (value) {
  95966. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95967. BABYLON.Tools.StartPerformanceCounter("Physics");
  95968. _this._physicsTime.beginMonitoring();
  95969. });
  95970. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95971. BABYLON.Tools.EndPerformanceCounter("Physics");
  95972. _this._physicsTime.endMonitoring();
  95973. });
  95974. }
  95975. else {
  95976. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95977. this._onBeforePhysicsObserver = null;
  95978. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95979. this._onAfterPhysicsObserver = null;
  95980. }
  95981. },
  95982. enumerable: true,
  95983. configurable: true
  95984. });
  95985. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95986. /**
  95987. * Gets the perf counter used for animations time
  95988. */
  95989. get: function () {
  95990. return this._animationsTime;
  95991. },
  95992. enumerable: true,
  95993. configurable: true
  95994. });
  95995. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95996. /**
  95997. * Gets the animations time capture status
  95998. */
  95999. get: function () {
  96000. return this._captureAnimationsTime;
  96001. },
  96002. /**
  96003. * Enable or disable the animations time capture
  96004. */
  96005. set: function (value) {
  96006. var _this = this;
  96007. if (value === this._captureAnimationsTime) {
  96008. return;
  96009. }
  96010. this._captureAnimationsTime = value;
  96011. if (value) {
  96012. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  96013. _this._animationsTime.endMonitoring();
  96014. });
  96015. }
  96016. else {
  96017. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96018. this._onAfterAnimationsObserver = null;
  96019. }
  96020. },
  96021. enumerable: true,
  96022. configurable: true
  96023. });
  96024. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96025. /**
  96026. * Gets the perf counter used for frame time capture
  96027. */
  96028. get: function () {
  96029. return this._frameTime;
  96030. },
  96031. enumerable: true,
  96032. configurable: true
  96033. });
  96034. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96035. /**
  96036. * Gets the frame time capture status
  96037. */
  96038. get: function () {
  96039. return this._captureFrameTime;
  96040. },
  96041. /**
  96042. * Enable or disable the frame time capture
  96043. */
  96044. set: function (value) {
  96045. this._captureFrameTime = value;
  96046. },
  96047. enumerable: true,
  96048. configurable: true
  96049. });
  96050. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96051. /**
  96052. * Gets the perf counter used for inter-frames time capture
  96053. */
  96054. get: function () {
  96055. return this._interFrameTime;
  96056. },
  96057. enumerable: true,
  96058. configurable: true
  96059. });
  96060. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96061. /**
  96062. * Gets the inter-frames time capture status
  96063. */
  96064. get: function () {
  96065. return this._captureInterFrameTime;
  96066. },
  96067. /**
  96068. * Enable or disable the inter-frames time capture
  96069. */
  96070. set: function (value) {
  96071. this._captureInterFrameTime = value;
  96072. },
  96073. enumerable: true,
  96074. configurable: true
  96075. });
  96076. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96077. /**
  96078. * Gets the perf counter used for render time capture
  96079. */
  96080. get: function () {
  96081. return this._renderTime;
  96082. },
  96083. enumerable: true,
  96084. configurable: true
  96085. });
  96086. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96087. /**
  96088. * Gets the render time capture status
  96089. */
  96090. get: function () {
  96091. return this._captureRenderTime;
  96092. },
  96093. /**
  96094. * Enable or disable the render time capture
  96095. */
  96096. set: function (value) {
  96097. var _this = this;
  96098. if (value === this._captureRenderTime) {
  96099. return;
  96100. }
  96101. this._captureRenderTime = value;
  96102. if (value) {
  96103. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96104. _this._renderTime.beginMonitoring();
  96105. BABYLON.Tools.StartPerformanceCounter("Main render");
  96106. });
  96107. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96108. _this._renderTime.endMonitoring(false);
  96109. BABYLON.Tools.EndPerformanceCounter("Main render");
  96110. });
  96111. }
  96112. else {
  96113. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96114. this._onBeforeDrawPhaseObserver = null;
  96115. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96116. this._onAfterDrawPhaseObserver = null;
  96117. }
  96118. },
  96119. enumerable: true,
  96120. configurable: true
  96121. });
  96122. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96123. /**
  96124. * Gets the perf counter used for draw calls
  96125. */
  96126. get: function () {
  96127. return this.scene.getEngine()._drawCalls;
  96128. },
  96129. enumerable: true,
  96130. configurable: true
  96131. });
  96132. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96133. /**
  96134. * Gets the perf counter used for texture collisions
  96135. */
  96136. get: function () {
  96137. return this.scene.getEngine()._textureCollisions;
  96138. },
  96139. enumerable: true,
  96140. configurable: true
  96141. });
  96142. SceneInstrumentation.prototype.dispose = function () {
  96143. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96144. this._onAfterRenderObserver = null;
  96145. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96146. this._onBeforeActiveMeshesEvaluationObserver = null;
  96147. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96148. this._onAfterActiveMeshesEvaluationObserver = null;
  96149. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96150. this._onBeforeRenderTargetsRenderObserver = null;
  96151. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96152. this._onAfterRenderTargetsRenderObserver = null;
  96153. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96154. this._onBeforeAnimationsObserver = null;
  96155. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96156. this._onBeforeParticlesRenderingObserver = null;
  96157. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96158. this._onAfterParticlesRenderingObserver = null;
  96159. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96160. this._onBeforeSpritesRenderingObserver = null;
  96161. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96162. this._onAfterSpritesRenderingObserver = null;
  96163. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96164. this._onBeforeDrawPhaseObserver = null;
  96165. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96166. this._onAfterDrawPhaseObserver = null;
  96167. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96168. this._onBeforePhysicsObserver = null;
  96169. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96170. this._onAfterPhysicsObserver = null;
  96171. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96172. this._onAfterAnimationsObserver = null;
  96173. this.scene = null;
  96174. };
  96175. return SceneInstrumentation;
  96176. }());
  96177. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96178. })(BABYLON || (BABYLON = {}));
  96179. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96180. var BABYLON;
  96181. (function (BABYLON) {
  96182. /**
  96183. * @hidden
  96184. **/
  96185. var _TimeToken = /** @class */ (function () {
  96186. function _TimeToken() {
  96187. this._timeElapsedQueryEnded = false;
  96188. }
  96189. return _TimeToken;
  96190. }());
  96191. BABYLON._TimeToken = _TimeToken;
  96192. })(BABYLON || (BABYLON = {}));
  96193. //# sourceMappingURL=babylon.timeToken.js.map
  96194. var BABYLON;
  96195. (function (BABYLON) {
  96196. /**
  96197. * Background material defines definition.
  96198. * @hidden Mainly internal Use
  96199. */
  96200. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96201. __extends(BackgroundMaterialDefines, _super);
  96202. /**
  96203. * Constructor of the defines.
  96204. */
  96205. function BackgroundMaterialDefines() {
  96206. var _this = _super.call(this) || this;
  96207. /**
  96208. * True if the diffuse texture is in use.
  96209. */
  96210. _this.DIFFUSE = false;
  96211. /**
  96212. * The direct UV channel to use.
  96213. */
  96214. _this.DIFFUSEDIRECTUV = 0;
  96215. /**
  96216. * True if the diffuse texture is in gamma space.
  96217. */
  96218. _this.GAMMADIFFUSE = false;
  96219. /**
  96220. * True if the diffuse texture has opacity in the alpha channel.
  96221. */
  96222. _this.DIFFUSEHASALPHA = false;
  96223. /**
  96224. * True if you want the material to fade to transparent at grazing angle.
  96225. */
  96226. _this.OPACITYFRESNEL = false;
  96227. /**
  96228. * True if an extra blur needs to be added in the reflection.
  96229. */
  96230. _this.REFLECTIONBLUR = false;
  96231. /**
  96232. * True if you want the material to fade to reflection at grazing angle.
  96233. */
  96234. _this.REFLECTIONFRESNEL = false;
  96235. /**
  96236. * True if you want the material to falloff as far as you move away from the scene center.
  96237. */
  96238. _this.REFLECTIONFALLOFF = false;
  96239. /**
  96240. * False if the current Webgl implementation does not support the texture lod extension.
  96241. */
  96242. _this.TEXTURELODSUPPORT = false;
  96243. /**
  96244. * True to ensure the data are premultiplied.
  96245. */
  96246. _this.PREMULTIPLYALPHA = false;
  96247. /**
  96248. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96249. */
  96250. _this.USERGBCOLOR = false;
  96251. /**
  96252. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96253. * stays aligned with the desired configuration.
  96254. */
  96255. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96256. /**
  96257. * True to add noise in order to reduce the banding effect.
  96258. */
  96259. _this.NOISE = false;
  96260. /**
  96261. * is the reflection texture in BGR color scheme?
  96262. * Mainly used to solve a bug in ios10 video tag
  96263. */
  96264. _this.REFLECTIONBGR = false;
  96265. _this.IMAGEPROCESSING = false;
  96266. _this.VIGNETTE = false;
  96267. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96268. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96269. _this.TONEMAPPING = false;
  96270. _this.CONTRAST = false;
  96271. _this.COLORCURVES = false;
  96272. _this.COLORGRADING = false;
  96273. _this.COLORGRADING3D = false;
  96274. _this.SAMPLER3DGREENDEPTH = false;
  96275. _this.SAMPLER3DBGRMAP = false;
  96276. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96277. _this.EXPOSURE = false;
  96278. // Reflection.
  96279. _this.REFLECTION = false;
  96280. _this.REFLECTIONMAP_3D = false;
  96281. _this.REFLECTIONMAP_SPHERICAL = false;
  96282. _this.REFLECTIONMAP_PLANAR = false;
  96283. _this.REFLECTIONMAP_CUBIC = false;
  96284. _this.REFLECTIONMAP_PROJECTION = false;
  96285. _this.REFLECTIONMAP_SKYBOX = false;
  96286. _this.REFLECTIONMAP_EXPLICIT = false;
  96287. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96288. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96289. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96290. _this.INVERTCUBICMAP = false;
  96291. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96292. _this.LODINREFLECTIONALPHA = false;
  96293. _this.GAMMAREFLECTION = false;
  96294. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96295. // Default BJS.
  96296. _this.MAINUV1 = false;
  96297. _this.MAINUV2 = false;
  96298. _this.UV1 = false;
  96299. _this.UV2 = false;
  96300. _this.CLIPPLANE = false;
  96301. _this.POINTSIZE = false;
  96302. _this.FOG = false;
  96303. _this.NORMAL = false;
  96304. _this.NUM_BONE_INFLUENCERS = 0;
  96305. _this.BonesPerMesh = 0;
  96306. _this.INSTANCES = false;
  96307. _this.SHADOWFLOAT = false;
  96308. _this.rebuild();
  96309. return _this;
  96310. }
  96311. return BackgroundMaterialDefines;
  96312. }(BABYLON.MaterialDefines));
  96313. /**
  96314. * Background material used to create an efficient environement around your scene.
  96315. */
  96316. var BackgroundMaterial = /** @class */ (function (_super) {
  96317. __extends(BackgroundMaterial, _super);
  96318. /**
  96319. * Instantiates a Background Material in the given scene
  96320. * @param name The friendly name of the material
  96321. * @param scene The scene to add the material to
  96322. */
  96323. function BackgroundMaterial(name, scene) {
  96324. var _this = _super.call(this, name, scene) || this;
  96325. /**
  96326. * Key light Color (multiply against the environement texture)
  96327. */
  96328. _this.primaryColor = BABYLON.Color3.White();
  96329. _this._primaryColorShadowLevel = 0;
  96330. _this._primaryColorHighlightLevel = 0;
  96331. /**
  96332. * Reflection Texture used in the material.
  96333. * Should be author in a specific way for the best result (refer to the documentation).
  96334. */
  96335. _this.reflectionTexture = null;
  96336. /**
  96337. * Reflection Texture level of blur.
  96338. *
  96339. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96340. * texture twice.
  96341. */
  96342. _this.reflectionBlur = 0;
  96343. /**
  96344. * Diffuse Texture used in the material.
  96345. * Should be author in a specific way for the best result (refer to the documentation).
  96346. */
  96347. _this.diffuseTexture = null;
  96348. _this._shadowLights = null;
  96349. /**
  96350. * Specify the list of lights casting shadow on the material.
  96351. * All scene shadow lights will be included if null.
  96352. */
  96353. _this.shadowLights = null;
  96354. /**
  96355. * Helps adjusting the shadow to a softer level if required.
  96356. * 0 means black shadows and 1 means no shadows.
  96357. */
  96358. _this.shadowLevel = 0;
  96359. /**
  96360. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96361. * It is usually zero but might be interesting to modify according to your setup.
  96362. */
  96363. _this.sceneCenter = BABYLON.Vector3.Zero();
  96364. /**
  96365. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96366. * This helps ensuring a nice transition when the camera goes under the ground.
  96367. */
  96368. _this.opacityFresnel = true;
  96369. /**
  96370. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96371. * This helps adding a mirror texture on the ground.
  96372. */
  96373. _this.reflectionFresnel = false;
  96374. /**
  96375. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96376. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96377. */
  96378. _this.reflectionFalloffDistance = 0.0;
  96379. /**
  96380. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96381. */
  96382. _this.reflectionAmount = 1.0;
  96383. /**
  96384. * This specifies the weight of the reflection at grazing angle.
  96385. */
  96386. _this.reflectionReflectance0 = 0.05;
  96387. /**
  96388. * This specifies the weight of the reflection at a perpendicular point of view.
  96389. */
  96390. _this.reflectionReflectance90 = 0.5;
  96391. /**
  96392. * Helps to directly use the maps channels instead of their level.
  96393. */
  96394. _this.useRGBColor = true;
  96395. /**
  96396. * This helps reducing the banding effect that could occur on the background.
  96397. */
  96398. _this.enableNoise = false;
  96399. _this._fovMultiplier = 1.0;
  96400. /**
  96401. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96402. */
  96403. _this.useEquirectangularFOV = false;
  96404. _this._maxSimultaneousLights = 4;
  96405. /**
  96406. * Number of Simultaneous lights allowed on the material.
  96407. */
  96408. _this.maxSimultaneousLights = 4;
  96409. /**
  96410. * Keep track of the image processing observer to allow dispose and replace.
  96411. */
  96412. _this._imageProcessingObserver = null;
  96413. /**
  96414. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96415. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96416. */
  96417. _this.switchToBGR = false;
  96418. // Temp values kept as cache in the material.
  96419. _this._renderTargets = new BABYLON.SmartArray(16);
  96420. _this._reflectionControls = BABYLON.Vector4.Zero();
  96421. _this._white = BABYLON.Color3.White();
  96422. _this._primaryShadowColor = BABYLON.Color3.Black();
  96423. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96424. // Setup the default processing configuration to the scene.
  96425. _this._attachImageProcessingConfiguration(null);
  96426. _this.getRenderTargetTextures = function () {
  96427. _this._renderTargets.reset();
  96428. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96429. _this._renderTargets.push(_this._diffuseTexture);
  96430. }
  96431. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96432. _this._renderTargets.push(_this._reflectionTexture);
  96433. }
  96434. return _this._renderTargets;
  96435. };
  96436. return _this;
  96437. }
  96438. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96439. /**
  96440. * Experimental Internal Use Only.
  96441. *
  96442. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96443. * This acts as a helper to set the primary color to a more "human friendly" value.
  96444. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96445. * output color as close as possible from the chosen value.
  96446. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96447. * part of lighting setup.)
  96448. */
  96449. get: function () {
  96450. return this.__perceptualColor;
  96451. },
  96452. set: function (value) {
  96453. this.__perceptualColor = value;
  96454. this._computePrimaryColorFromPerceptualColor();
  96455. this._markAllSubMeshesAsLightsDirty();
  96456. },
  96457. enumerable: true,
  96458. configurable: true
  96459. });
  96460. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96461. /**
  96462. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96463. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96464. */
  96465. get: function () {
  96466. return this._primaryColorShadowLevel;
  96467. },
  96468. set: function (value) {
  96469. this._primaryColorShadowLevel = value;
  96470. this._computePrimaryColors();
  96471. this._markAllSubMeshesAsLightsDirty();
  96472. },
  96473. enumerable: true,
  96474. configurable: true
  96475. });
  96476. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96477. /**
  96478. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96479. * The primary color is used at the level chosen to define what the white area would look.
  96480. */
  96481. get: function () {
  96482. return this._primaryColorHighlightLevel;
  96483. },
  96484. set: function (value) {
  96485. this._primaryColorHighlightLevel = value;
  96486. this._computePrimaryColors();
  96487. this._markAllSubMeshesAsLightsDirty();
  96488. },
  96489. enumerable: true,
  96490. configurable: true
  96491. });
  96492. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96493. /**
  96494. * Sets the reflection reflectance fresnel values according to the default standard
  96495. * empirically know to work well :-)
  96496. */
  96497. set: function (value) {
  96498. var reflectionWeight = value;
  96499. if (reflectionWeight < 0.5) {
  96500. reflectionWeight = reflectionWeight * 2.0;
  96501. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96502. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96503. }
  96504. else {
  96505. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96506. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96507. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96508. }
  96509. },
  96510. enumerable: true,
  96511. configurable: true
  96512. });
  96513. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96514. /**
  96515. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96516. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96517. * Recommended to be keep at 1.0 except for special cases.
  96518. */
  96519. get: function () {
  96520. return this._fovMultiplier;
  96521. },
  96522. set: function (value) {
  96523. if (isNaN(value)) {
  96524. value = 1.0;
  96525. }
  96526. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96527. },
  96528. enumerable: true,
  96529. configurable: true
  96530. });
  96531. /**
  96532. * Attaches a new image processing configuration to the PBR Material.
  96533. * @param configuration (if null the scene configuration will be use)
  96534. */
  96535. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96536. var _this = this;
  96537. if (configuration === this._imageProcessingConfiguration) {
  96538. return;
  96539. }
  96540. // Detaches observer.
  96541. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96542. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96543. }
  96544. // Pick the scene configuration if needed.
  96545. if (!configuration) {
  96546. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96547. }
  96548. else {
  96549. this._imageProcessingConfiguration = configuration;
  96550. }
  96551. // Attaches observer.
  96552. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96553. _this._computePrimaryColorFromPerceptualColor();
  96554. _this._markAllSubMeshesAsImageProcessingDirty();
  96555. });
  96556. };
  96557. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96558. /**
  96559. * Gets the image processing configuration used either in this material.
  96560. */
  96561. get: function () {
  96562. return this._imageProcessingConfiguration;
  96563. },
  96564. /**
  96565. * Sets the Default image processing configuration used either in the this material.
  96566. *
  96567. * If sets to null, the scene one is in use.
  96568. */
  96569. set: function (value) {
  96570. this._attachImageProcessingConfiguration(value);
  96571. // Ensure the effect will be rebuilt.
  96572. this._markAllSubMeshesAsTexturesDirty();
  96573. },
  96574. enumerable: true,
  96575. configurable: true
  96576. });
  96577. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96578. /**
  96579. * Gets wether the color curves effect is enabled.
  96580. */
  96581. get: function () {
  96582. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96583. },
  96584. /**
  96585. * Sets wether the color curves effect is enabled.
  96586. */
  96587. set: function (value) {
  96588. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96589. },
  96590. enumerable: true,
  96591. configurable: true
  96592. });
  96593. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96594. /**
  96595. * Gets wether the color grading effect is enabled.
  96596. */
  96597. get: function () {
  96598. return this.imageProcessingConfiguration.colorGradingEnabled;
  96599. },
  96600. /**
  96601. * Gets wether the color grading effect is enabled.
  96602. */
  96603. set: function (value) {
  96604. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96605. },
  96606. enumerable: true,
  96607. configurable: true
  96608. });
  96609. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96610. /**
  96611. * Gets wether tonemapping is enabled or not.
  96612. */
  96613. get: function () {
  96614. return this._imageProcessingConfiguration.toneMappingEnabled;
  96615. },
  96616. /**
  96617. * Sets wether tonemapping is enabled or not
  96618. */
  96619. set: function (value) {
  96620. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96621. },
  96622. enumerable: true,
  96623. configurable: true
  96624. });
  96625. ;
  96626. ;
  96627. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96628. /**
  96629. * The camera exposure used on this material.
  96630. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96631. * This corresponds to a photographic exposure.
  96632. */
  96633. get: function () {
  96634. return this._imageProcessingConfiguration.exposure;
  96635. },
  96636. /**
  96637. * The camera exposure used on this material.
  96638. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96639. * This corresponds to a photographic exposure.
  96640. */
  96641. set: function (value) {
  96642. this._imageProcessingConfiguration.exposure = value;
  96643. },
  96644. enumerable: true,
  96645. configurable: true
  96646. });
  96647. ;
  96648. ;
  96649. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96650. /**
  96651. * Gets The camera contrast used on this material.
  96652. */
  96653. get: function () {
  96654. return this._imageProcessingConfiguration.contrast;
  96655. },
  96656. /**
  96657. * Sets The camera contrast used on this material.
  96658. */
  96659. set: function (value) {
  96660. this._imageProcessingConfiguration.contrast = value;
  96661. },
  96662. enumerable: true,
  96663. configurable: true
  96664. });
  96665. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96666. /**
  96667. * Gets the Color Grading 2D Lookup Texture.
  96668. */
  96669. get: function () {
  96670. return this._imageProcessingConfiguration.colorGradingTexture;
  96671. },
  96672. /**
  96673. * Sets the Color Grading 2D Lookup Texture.
  96674. */
  96675. set: function (value) {
  96676. this.imageProcessingConfiguration.colorGradingTexture = value;
  96677. },
  96678. enumerable: true,
  96679. configurable: true
  96680. });
  96681. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96682. /**
  96683. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96684. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96685. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  96686. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96687. */
  96688. get: function () {
  96689. return this.imageProcessingConfiguration.colorCurves;
  96690. },
  96691. /**
  96692. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96693. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96694. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  96695. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96696. */
  96697. set: function (value) {
  96698. this.imageProcessingConfiguration.colorCurves = value;
  96699. },
  96700. enumerable: true,
  96701. configurable: true
  96702. });
  96703. /**
  96704. * The entire material has been created in order to prevent overdraw.
  96705. * @returns false
  96706. */
  96707. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96708. return true;
  96709. };
  96710. /**
  96711. * The entire material has been created in order to prevent overdraw.
  96712. * @returns true if blending is enable
  96713. */
  96714. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96715. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96716. };
  96717. /**
  96718. * Checks wether the material is ready to be rendered for a given mesh.
  96719. * @param mesh The mesh to render
  96720. * @param subMesh The submesh to check against
  96721. * @param useInstances Specify wether or not the material is used with instances
  96722. * @returns true if all the dependencies are ready (Textures, Effects...)
  96723. */
  96724. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96725. var _this = this;
  96726. if (useInstances === void 0) { useInstances = false; }
  96727. if (subMesh.effect && this.isFrozen) {
  96728. if (this._wasPreviouslyReady) {
  96729. return true;
  96730. }
  96731. }
  96732. if (!subMesh._materialDefines) {
  96733. subMesh._materialDefines = new BackgroundMaterialDefines();
  96734. }
  96735. var scene = this.getScene();
  96736. var defines = subMesh._materialDefines;
  96737. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96738. if (defines._renderId === scene.getRenderId()) {
  96739. return true;
  96740. }
  96741. }
  96742. var engine = scene.getEngine();
  96743. // Lights
  96744. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96745. defines._needNormals = true;
  96746. // Textures
  96747. if (defines._areTexturesDirty) {
  96748. defines._needUVs = false;
  96749. if (scene.texturesEnabled) {
  96750. if (scene.getEngine().getCaps().textureLOD) {
  96751. defines.TEXTURELODSUPPORT = true;
  96752. }
  96753. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96754. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96755. return false;
  96756. }
  96757. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96758. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96759. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96760. defines.OPACITYFRESNEL = this._opacityFresnel;
  96761. }
  96762. else {
  96763. defines.DIFFUSE = false;
  96764. defines.DIFFUSEHASALPHA = false;
  96765. defines.GAMMADIFFUSE = false;
  96766. defines.OPACITYFRESNEL = false;
  96767. }
  96768. var reflectionTexture = this._reflectionTexture;
  96769. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96770. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96771. return false;
  96772. }
  96773. defines.REFLECTION = true;
  96774. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96775. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96776. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96777. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96778. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96779. defines.REFLECTIONBGR = this.switchToBGR;
  96780. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96781. defines.INVERTCUBICMAP = true;
  96782. }
  96783. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96784. switch (reflectionTexture.coordinatesMode) {
  96785. case BABYLON.Texture.EXPLICIT_MODE:
  96786. defines.REFLECTIONMAP_EXPLICIT = true;
  96787. break;
  96788. case BABYLON.Texture.PLANAR_MODE:
  96789. defines.REFLECTIONMAP_PLANAR = true;
  96790. break;
  96791. case BABYLON.Texture.PROJECTION_MODE:
  96792. defines.REFLECTIONMAP_PROJECTION = true;
  96793. break;
  96794. case BABYLON.Texture.SKYBOX_MODE:
  96795. defines.REFLECTIONMAP_SKYBOX = true;
  96796. break;
  96797. case BABYLON.Texture.SPHERICAL_MODE:
  96798. defines.REFLECTIONMAP_SPHERICAL = true;
  96799. break;
  96800. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96801. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96802. break;
  96803. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96804. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96805. break;
  96806. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96807. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96808. break;
  96809. case BABYLON.Texture.CUBIC_MODE:
  96810. case BABYLON.Texture.INVCUBIC_MODE:
  96811. default:
  96812. defines.REFLECTIONMAP_CUBIC = true;
  96813. break;
  96814. }
  96815. if (this.reflectionFresnel) {
  96816. defines.REFLECTIONFRESNEL = true;
  96817. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96818. this._reflectionControls.x = this.reflectionAmount;
  96819. this._reflectionControls.y = this.reflectionReflectance0;
  96820. this._reflectionControls.z = this.reflectionReflectance90;
  96821. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96822. }
  96823. else {
  96824. defines.REFLECTIONFRESNEL = false;
  96825. defines.REFLECTIONFALLOFF = false;
  96826. }
  96827. }
  96828. else {
  96829. defines.REFLECTION = false;
  96830. defines.REFLECTIONFRESNEL = false;
  96831. defines.REFLECTIONFALLOFF = false;
  96832. defines.REFLECTIONBLUR = false;
  96833. defines.REFLECTIONMAP_3D = false;
  96834. defines.REFLECTIONMAP_SPHERICAL = false;
  96835. defines.REFLECTIONMAP_PLANAR = false;
  96836. defines.REFLECTIONMAP_CUBIC = false;
  96837. defines.REFLECTIONMAP_PROJECTION = false;
  96838. defines.REFLECTIONMAP_SKYBOX = false;
  96839. defines.REFLECTIONMAP_EXPLICIT = false;
  96840. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96841. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96842. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96843. defines.INVERTCUBICMAP = false;
  96844. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96845. defines.LODINREFLECTIONALPHA = false;
  96846. defines.GAMMAREFLECTION = false;
  96847. }
  96848. }
  96849. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96850. defines.USERGBCOLOR = this._useRGBColor;
  96851. defines.NOISE = this._enableNoise;
  96852. }
  96853. if (defines._areLightsDirty) {
  96854. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96855. }
  96856. if (defines._areImageProcessingDirty) {
  96857. if (!this._imageProcessingConfiguration.isReady()) {
  96858. return false;
  96859. }
  96860. this._imageProcessingConfiguration.prepareDefines(defines);
  96861. }
  96862. // Misc.
  96863. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96864. // Values that need to be evaluated on every frame
  96865. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96866. // Attribs
  96867. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96868. if (mesh) {
  96869. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96870. mesh.createNormals(true);
  96871. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96872. }
  96873. }
  96874. }
  96875. // Get correct effect
  96876. if (defines.isDirty) {
  96877. defines.markAsProcessed();
  96878. scene.resetCachedMaterial();
  96879. // Fallbacks
  96880. var fallbacks = new BABYLON.EffectFallbacks();
  96881. if (defines.FOG) {
  96882. fallbacks.addFallback(0, "FOG");
  96883. }
  96884. if (defines.POINTSIZE) {
  96885. fallbacks.addFallback(1, "POINTSIZE");
  96886. }
  96887. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96888. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96889. fallbacks.addCPUSkinningFallback(0, mesh);
  96890. }
  96891. //Attributes
  96892. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96893. if (defines.NORMAL) {
  96894. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96895. }
  96896. if (defines.UV1) {
  96897. attribs.push(BABYLON.VertexBuffer.UVKind);
  96898. }
  96899. if (defines.UV2) {
  96900. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96901. }
  96902. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96903. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96904. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96905. "vFogInfos", "vFogColor", "pointSize",
  96906. "vClipPlane", "mBones",
  96907. "vPrimaryColor", "vPrimaryColorShadow",
  96908. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96909. "shadowLevel", "alpha",
  96910. "vBackgroundCenter", "vReflectionControl",
  96911. "vDiffuseInfos", "diffuseMatrix",
  96912. ];
  96913. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96914. var uniformBuffers = ["Material", "Scene"];
  96915. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96916. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96917. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96918. uniformsNames: uniforms,
  96919. uniformBuffersNames: uniformBuffers,
  96920. samplers: samplers,
  96921. defines: defines,
  96922. maxSimultaneousLights: this._maxSimultaneousLights
  96923. });
  96924. var onCompiled = function (effect) {
  96925. if (_this.onCompiled) {
  96926. _this.onCompiled(effect);
  96927. }
  96928. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96929. };
  96930. var join = defines.toString();
  96931. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96932. attributes: attribs,
  96933. uniformsNames: uniforms,
  96934. uniformBuffersNames: uniformBuffers,
  96935. samplers: samplers,
  96936. defines: join,
  96937. fallbacks: fallbacks,
  96938. onCompiled: onCompiled,
  96939. onError: this.onError,
  96940. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96941. }, engine), defines);
  96942. this.buildUniformLayout();
  96943. }
  96944. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96945. return false;
  96946. }
  96947. defines._renderId = scene.getRenderId();
  96948. this._wasPreviouslyReady = true;
  96949. return true;
  96950. };
  96951. /**
  96952. * Compute the primary color according to the chosen perceptual color.
  96953. */
  96954. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96955. if (!this.__perceptualColor) {
  96956. return;
  96957. }
  96958. this._primaryColor.copyFrom(this.__perceptualColor);
  96959. // Revert gamma space.
  96960. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96961. // Revert image processing configuration.
  96962. if (this._imageProcessingConfiguration) {
  96963. // Revert Exposure.
  96964. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96965. }
  96966. this._computePrimaryColors();
  96967. };
  96968. /**
  96969. * Compute the highlights and shadow colors according to their chosen levels.
  96970. */
  96971. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96972. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96973. return;
  96974. }
  96975. // Find the highlight color based on the configuration.
  96976. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96977. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96978. // Find the shadow color based on the configuration.
  96979. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96980. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96981. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96982. };
  96983. /**
  96984. * Build the uniform buffer used in the material.
  96985. */
  96986. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96987. // Order is important !
  96988. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96989. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96990. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96991. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96992. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96993. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96994. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96995. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96996. this._uniformBuffer.addUniform("pointSize", 1);
  96997. this._uniformBuffer.addUniform("shadowLevel", 1);
  96998. this._uniformBuffer.addUniform("alpha", 1);
  96999. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  97000. this._uniformBuffer.addUniform("vReflectionControl", 4);
  97001. this._uniformBuffer.create();
  97002. };
  97003. /**
  97004. * Unbind the material.
  97005. */
  97006. BackgroundMaterial.prototype.unbind = function () {
  97007. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  97008. this._uniformBuffer.setTexture("diffuseSampler", null);
  97009. }
  97010. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  97011. this._uniformBuffer.setTexture("reflectionSampler", null);
  97012. }
  97013. _super.prototype.unbind.call(this);
  97014. };
  97015. /**
  97016. * Bind only the world matrix to the material.
  97017. * @param world The world matrix to bind.
  97018. */
  97019. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  97020. this._activeEffect.setMatrix("world", world);
  97021. };
  97022. /**
  97023. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97024. * @param world The world matrix to bind.
  97025. * @param subMesh The submesh to bind for.
  97026. */
  97027. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97028. var scene = this.getScene();
  97029. var defines = subMesh._materialDefines;
  97030. if (!defines) {
  97031. return;
  97032. }
  97033. var effect = subMesh.effect;
  97034. if (!effect) {
  97035. return;
  97036. }
  97037. this._activeEffect = effect;
  97038. // Matrices
  97039. this.bindOnlyWorldMatrix(world);
  97040. // Bones
  97041. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97042. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97043. if (mustRebind) {
  97044. this._uniformBuffer.bindToEffect(effect, "Material");
  97045. this.bindViewProjection(effect);
  97046. var reflectionTexture = this._reflectionTexture;
  97047. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97048. // Texture uniforms
  97049. if (scene.texturesEnabled) {
  97050. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97051. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97052. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97053. }
  97054. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97055. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97056. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97057. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97058. }
  97059. }
  97060. if (this.shadowLevel > 0) {
  97061. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97062. }
  97063. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97064. // Point size
  97065. if (this.pointsCloud) {
  97066. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97067. }
  97068. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97069. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97070. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97071. }
  97072. else {
  97073. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97074. }
  97075. }
  97076. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97077. // Textures
  97078. if (scene.texturesEnabled) {
  97079. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97080. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97081. }
  97082. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97083. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97084. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97085. }
  97086. else if (!defines.REFLECTIONBLUR) {
  97087. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97088. }
  97089. else {
  97090. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97091. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97092. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97093. }
  97094. if (defines.REFLECTIONFRESNEL) {
  97095. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97096. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97097. }
  97098. }
  97099. }
  97100. // Clip plane
  97101. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97102. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97103. }
  97104. if (mustRebind || !this.isFrozen) {
  97105. if (scene.lightsEnabled) {
  97106. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97107. }
  97108. // View
  97109. this.bindView(effect);
  97110. // Fog
  97111. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97112. // image processing
  97113. this._imageProcessingConfiguration.bind(this._activeEffect);
  97114. }
  97115. this._uniformBuffer.update();
  97116. this._afterBind(mesh);
  97117. };
  97118. /**
  97119. * Dispose the material.
  97120. * @param forceDisposeEffect Force disposal of the associated effect.
  97121. * @param forceDisposeTextures Force disposal of the associated textures.
  97122. */
  97123. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97124. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97125. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97126. if (forceDisposeTextures) {
  97127. if (this.diffuseTexture) {
  97128. this.diffuseTexture.dispose();
  97129. }
  97130. if (this.reflectionTexture) {
  97131. this.reflectionTexture.dispose();
  97132. }
  97133. }
  97134. this._renderTargets.dispose();
  97135. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97136. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97137. }
  97138. _super.prototype.dispose.call(this, forceDisposeEffect);
  97139. };
  97140. /**
  97141. * Clones the material.
  97142. * @param name The cloned name.
  97143. * @returns The cloned material.
  97144. */
  97145. BackgroundMaterial.prototype.clone = function (name) {
  97146. var _this = this;
  97147. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97148. };
  97149. /**
  97150. * Serializes the current material to its JSON representation.
  97151. * @returns The JSON representation.
  97152. */
  97153. BackgroundMaterial.prototype.serialize = function () {
  97154. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97155. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97156. return serializationObject;
  97157. };
  97158. /**
  97159. * Gets the class name of the material
  97160. * @returns "BackgroundMaterial"
  97161. */
  97162. BackgroundMaterial.prototype.getClassName = function () {
  97163. return "BackgroundMaterial";
  97164. };
  97165. /**
  97166. * Parse a JSON input to create back a background material.
  97167. * @param source The JSON data to parse
  97168. * @param scene The scene to create the parsed material in
  97169. * @param rootUrl The root url of the assets the material depends upon
  97170. * @returns the instantiated BackgroundMaterial.
  97171. */
  97172. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97173. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97174. };
  97175. /**
  97176. * Standard reflectance value at parallel view angle.
  97177. */
  97178. BackgroundMaterial.StandardReflectance0 = 0.05;
  97179. /**
  97180. * Standard reflectance value at grazing angle.
  97181. */
  97182. BackgroundMaterial.StandardReflectance90 = 0.5;
  97183. __decorate([
  97184. BABYLON.serializeAsColor3()
  97185. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97186. __decorate([
  97187. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97188. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97189. __decorate([
  97190. BABYLON.serializeAsColor3()
  97191. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97192. __decorate([
  97193. BABYLON.serialize()
  97194. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97195. __decorate([
  97196. BABYLON.serialize()
  97197. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97198. __decorate([
  97199. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97200. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97201. __decorate([
  97202. BABYLON.serializeAsTexture()
  97203. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97204. __decorate([
  97205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97206. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97207. __decorate([
  97208. BABYLON.serialize()
  97209. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97210. __decorate([
  97211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97212. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97213. __decorate([
  97214. BABYLON.serializeAsTexture()
  97215. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97216. __decorate([
  97217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97218. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97219. __decorate([
  97220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97221. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97222. __decorate([
  97223. BABYLON.serialize()
  97224. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97225. __decorate([
  97226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97227. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97228. __decorate([
  97229. BABYLON.serializeAsVector3()
  97230. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97231. __decorate([
  97232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97233. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97234. __decorate([
  97235. BABYLON.serialize()
  97236. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97237. __decorate([
  97238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97239. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97240. __decorate([
  97241. BABYLON.serialize()
  97242. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97243. __decorate([
  97244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97245. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97246. __decorate([
  97247. BABYLON.serialize()
  97248. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97249. __decorate([
  97250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97251. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97252. __decorate([
  97253. BABYLON.serialize()
  97254. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97255. __decorate([
  97256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97257. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97258. __decorate([
  97259. BABYLON.serialize()
  97260. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97261. __decorate([
  97262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97263. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97264. __decorate([
  97265. BABYLON.serialize()
  97266. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97267. __decorate([
  97268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97269. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97270. __decorate([
  97271. BABYLON.serialize()
  97272. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97273. __decorate([
  97274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97275. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97276. __decorate([
  97277. BABYLON.serialize()
  97278. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97279. __decorate([
  97280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97281. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97282. __decorate([
  97283. BABYLON.serialize()
  97284. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97285. __decorate([
  97286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97287. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97288. __decorate([
  97289. BABYLON.serializeAsImageProcessingConfiguration()
  97290. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97291. return BackgroundMaterial;
  97292. }(BABYLON.PushMaterial));
  97293. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97294. })(BABYLON || (BABYLON = {}));
  97295. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97296. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97297. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97298. s = arguments[i];
  97299. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97300. t[p] = s[p];
  97301. }
  97302. return t;
  97303. };
  97304. var BABYLON;
  97305. (function (BABYLON) {
  97306. /**
  97307. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97308. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97309. * It also helps with the default setup of your imageProcessing configuration.
  97310. */
  97311. var EnvironmentHelper = /** @class */ (function () {
  97312. /**
  97313. * constructor
  97314. * @param options
  97315. * @param scene The scene to add the material to
  97316. */
  97317. function EnvironmentHelper(options, scene) {
  97318. var _this = this;
  97319. this._errorHandler = function (message, exception) {
  97320. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97321. };
  97322. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97323. this._scene = scene;
  97324. this.onErrorObservable = new BABYLON.Observable();
  97325. this._setupBackground();
  97326. this._setupImageProcessing();
  97327. }
  97328. /**
  97329. * Creates the default options for the helper.
  97330. */
  97331. EnvironmentHelper._getDefaultOptions = function () {
  97332. return {
  97333. createGround: true,
  97334. groundSize: 15,
  97335. groundTexture: this._groundTextureCDNUrl,
  97336. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97337. groundOpacity: 0.9,
  97338. enableGroundShadow: true,
  97339. groundShadowLevel: 0.5,
  97340. enableGroundMirror: false,
  97341. groundMirrorSizeRatio: 0.3,
  97342. groundMirrorBlurKernel: 64,
  97343. groundMirrorAmount: 1,
  97344. groundMirrorFresnelWeight: 1,
  97345. groundMirrorFallOffDistance: 0,
  97346. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97347. groundYBias: 0.00001,
  97348. createSkybox: true,
  97349. skyboxSize: 20,
  97350. skyboxTexture: this._skyboxTextureCDNUrl,
  97351. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97352. backgroundYRotation: 0,
  97353. sizeAuto: true,
  97354. rootPosition: BABYLON.Vector3.Zero(),
  97355. setupImageProcessing: true,
  97356. environmentTexture: this._environmentTextureCDNUrl,
  97357. cameraExposure: 0.8,
  97358. cameraContrast: 1.2,
  97359. toneMappingEnabled: true,
  97360. };
  97361. };
  97362. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97363. /**
  97364. * Gets the root mesh created by the helper.
  97365. */
  97366. get: function () {
  97367. return this._rootMesh;
  97368. },
  97369. enumerable: true,
  97370. configurable: true
  97371. });
  97372. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97373. /**
  97374. * Gets the skybox created by the helper.
  97375. */
  97376. get: function () {
  97377. return this._skybox;
  97378. },
  97379. enumerable: true,
  97380. configurable: true
  97381. });
  97382. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97383. /**
  97384. * Gets the skybox texture created by the helper.
  97385. */
  97386. get: function () {
  97387. return this._skyboxTexture;
  97388. },
  97389. enumerable: true,
  97390. configurable: true
  97391. });
  97392. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97393. /**
  97394. * Gets the skybox material created by the helper.
  97395. */
  97396. get: function () {
  97397. return this._skyboxMaterial;
  97398. },
  97399. enumerable: true,
  97400. configurable: true
  97401. });
  97402. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97403. /**
  97404. * Gets the ground mesh created by the helper.
  97405. */
  97406. get: function () {
  97407. return this._ground;
  97408. },
  97409. enumerable: true,
  97410. configurable: true
  97411. });
  97412. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97413. /**
  97414. * Gets the ground texture created by the helper.
  97415. */
  97416. get: function () {
  97417. return this._groundTexture;
  97418. },
  97419. enumerable: true,
  97420. configurable: true
  97421. });
  97422. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97423. /**
  97424. * Gets the ground mirror created by the helper.
  97425. */
  97426. get: function () {
  97427. return this._groundMirror;
  97428. },
  97429. enumerable: true,
  97430. configurable: true
  97431. });
  97432. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97433. /**
  97434. * Gets the ground mirror render list to helps pushing the meshes
  97435. * you wish in the ground reflection.
  97436. */
  97437. get: function () {
  97438. if (this._groundMirror) {
  97439. return this._groundMirror.renderList;
  97440. }
  97441. return null;
  97442. },
  97443. enumerable: true,
  97444. configurable: true
  97445. });
  97446. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97447. /**
  97448. * Gets the ground material created by the helper.
  97449. */
  97450. get: function () {
  97451. return this._groundMaterial;
  97452. },
  97453. enumerable: true,
  97454. configurable: true
  97455. });
  97456. /**
  97457. * Updates the background according to the new options
  97458. * @param options
  97459. */
  97460. EnvironmentHelper.prototype.updateOptions = function (options) {
  97461. var newOptions = __assign({}, this._options, options);
  97462. if (this._ground && !newOptions.createGround) {
  97463. this._ground.dispose();
  97464. this._ground = null;
  97465. }
  97466. if (this._groundMaterial && !newOptions.createGround) {
  97467. this._groundMaterial.dispose();
  97468. this._groundMaterial = null;
  97469. }
  97470. if (this._groundTexture) {
  97471. if (this._options.groundTexture != newOptions.groundTexture) {
  97472. this._groundTexture.dispose();
  97473. this._groundTexture = null;
  97474. }
  97475. }
  97476. if (this._skybox && !newOptions.createSkybox) {
  97477. this._skybox.dispose();
  97478. this._skybox = null;
  97479. }
  97480. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97481. this._skyboxMaterial.dispose();
  97482. this._skyboxMaterial = null;
  97483. }
  97484. if (this._skyboxTexture) {
  97485. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97486. this._skyboxTexture.dispose();
  97487. this._skyboxTexture = null;
  97488. }
  97489. }
  97490. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97491. this._groundMirror.dispose();
  97492. this._groundMirror = null;
  97493. }
  97494. if (this._scene.environmentTexture) {
  97495. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97496. this._scene.environmentTexture.dispose();
  97497. }
  97498. }
  97499. this._options = newOptions;
  97500. this._setupBackground();
  97501. this._setupImageProcessing();
  97502. };
  97503. /**
  97504. * Sets the primary color of all the available elements.
  97505. * @param color the main color to affect to the ground and the background
  97506. */
  97507. EnvironmentHelper.prototype.setMainColor = function (color) {
  97508. if (this.groundMaterial) {
  97509. this.groundMaterial.primaryColor = color;
  97510. }
  97511. if (this.skyboxMaterial) {
  97512. this.skyboxMaterial.primaryColor = color;
  97513. }
  97514. if (this.groundMirror) {
  97515. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97516. }
  97517. };
  97518. /**
  97519. * Setup the image processing according to the specified options.
  97520. */
  97521. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97522. if (this._options.setupImageProcessing) {
  97523. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97524. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97525. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97526. this._setupEnvironmentTexture();
  97527. }
  97528. };
  97529. /**
  97530. * Setup the environment texture according to the specified options.
  97531. */
  97532. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97533. if (this._scene.environmentTexture) {
  97534. return;
  97535. }
  97536. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97537. this._scene.environmentTexture = this._options.environmentTexture;
  97538. return;
  97539. }
  97540. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97541. this._scene.environmentTexture = environmentTexture;
  97542. };
  97543. /**
  97544. * Setup the background according to the specified options.
  97545. */
  97546. EnvironmentHelper.prototype._setupBackground = function () {
  97547. if (!this._rootMesh) {
  97548. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97549. }
  97550. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97551. var sceneSize = this._getSceneSize();
  97552. if (this._options.createGround) {
  97553. this._setupGround(sceneSize);
  97554. this._setupGroundMaterial();
  97555. this._setupGroundDiffuseTexture();
  97556. if (this._options.enableGroundMirror) {
  97557. this._setupGroundMirrorTexture(sceneSize);
  97558. }
  97559. this._setupMirrorInGroundMaterial();
  97560. }
  97561. if (this._options.createSkybox) {
  97562. this._setupSkybox(sceneSize);
  97563. this._setupSkyboxMaterial();
  97564. this._setupSkyboxReflectionTexture();
  97565. }
  97566. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97567. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97568. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97569. };
  97570. /**
  97571. * Get the scene sizes according to the setup.
  97572. */
  97573. EnvironmentHelper.prototype._getSceneSize = function () {
  97574. var _this = this;
  97575. var groundSize = this._options.groundSize;
  97576. var skyboxSize = this._options.skyboxSize;
  97577. var rootPosition = this._options.rootPosition;
  97578. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97579. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97580. }
  97581. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97582. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97583. });
  97584. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97585. if (this._options.sizeAuto) {
  97586. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97587. this._scene.activeCamera.upperRadiusLimit) {
  97588. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97589. skyboxSize = groundSize;
  97590. }
  97591. var sceneDiagonalLenght = sceneDiagonal.length();
  97592. if (sceneDiagonalLenght > groundSize) {
  97593. groundSize = sceneDiagonalLenght * 2;
  97594. skyboxSize = groundSize;
  97595. }
  97596. // 10 % bigger.
  97597. groundSize *= 1.1;
  97598. skyboxSize *= 1.5;
  97599. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97600. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97601. }
  97602. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97603. };
  97604. /**
  97605. * Setup the ground according to the specified options.
  97606. */
  97607. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97608. var _this = this;
  97609. if (!this._ground) {
  97610. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97611. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97612. this._ground.parent = this._rootMesh;
  97613. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97614. }
  97615. this._ground.receiveShadows = this._options.enableGroundShadow;
  97616. };
  97617. /**
  97618. * Setup the ground material according to the specified options.
  97619. */
  97620. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97621. if (!this._groundMaterial) {
  97622. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97623. }
  97624. this._groundMaterial.alpha = this._options.groundOpacity;
  97625. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97626. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97627. this._groundMaterial.primaryColor = this._options.groundColor;
  97628. this._groundMaterial.useRGBColor = false;
  97629. this._groundMaterial.enableNoise = true;
  97630. if (this._ground) {
  97631. this._ground.material = this._groundMaterial;
  97632. }
  97633. };
  97634. /**
  97635. * Setup the ground diffuse texture according to the specified options.
  97636. */
  97637. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97638. if (!this._groundMaterial) {
  97639. return;
  97640. }
  97641. if (this._groundTexture) {
  97642. return;
  97643. }
  97644. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97645. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97646. return;
  97647. }
  97648. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97649. diffuseTexture.gammaSpace = false;
  97650. diffuseTexture.hasAlpha = true;
  97651. this._groundMaterial.diffuseTexture = diffuseTexture;
  97652. };
  97653. /**
  97654. * Setup the ground mirror texture according to the specified options.
  97655. */
  97656. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97657. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97658. if (!this._groundMirror) {
  97659. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97660. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97661. this._groundMirror.anisotropicFilteringLevel = 1;
  97662. this._groundMirror.wrapU = wrapping;
  97663. this._groundMirror.wrapV = wrapping;
  97664. this._groundMirror.gammaSpace = false;
  97665. if (this._groundMirror.renderList) {
  97666. for (var i = 0; i < this._scene.meshes.length; i++) {
  97667. var mesh = this._scene.meshes[i];
  97668. if (mesh !== this._ground &&
  97669. mesh !== this._skybox &&
  97670. mesh !== this._rootMesh) {
  97671. this._groundMirror.renderList.push(mesh);
  97672. }
  97673. }
  97674. }
  97675. }
  97676. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97677. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97678. };
  97679. /**
  97680. * Setup the ground to receive the mirror texture.
  97681. */
  97682. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97683. if (this._groundMaterial) {
  97684. this._groundMaterial.reflectionTexture = this._groundMirror;
  97685. this._groundMaterial.reflectionFresnel = true;
  97686. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97687. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97688. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97689. }
  97690. };
  97691. /**
  97692. * Setup the skybox according to the specified options.
  97693. */
  97694. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97695. var _this = this;
  97696. if (!this._skybox) {
  97697. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97698. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97699. }
  97700. this._skybox.parent = this._rootMesh;
  97701. };
  97702. /**
  97703. * Setup the skybox material according to the specified options.
  97704. */
  97705. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97706. if (!this._skybox) {
  97707. return;
  97708. }
  97709. if (!this._skyboxMaterial) {
  97710. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97711. }
  97712. this._skyboxMaterial.useRGBColor = false;
  97713. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97714. this._skyboxMaterial.enableNoise = true;
  97715. this._skybox.material = this._skyboxMaterial;
  97716. };
  97717. /**
  97718. * Setup the skybox reflection texture according to the specified options.
  97719. */
  97720. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97721. if (!this._skyboxMaterial) {
  97722. return;
  97723. }
  97724. if (this._skyboxTexture) {
  97725. return;
  97726. }
  97727. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97728. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97729. return;
  97730. }
  97731. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97732. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97733. this._skyboxTexture.gammaSpace = false;
  97734. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97735. };
  97736. /**
  97737. * Dispose all the elements created by the Helper.
  97738. */
  97739. EnvironmentHelper.prototype.dispose = function () {
  97740. if (this._groundMaterial) {
  97741. this._groundMaterial.dispose(true, true);
  97742. }
  97743. if (this._skyboxMaterial) {
  97744. this._skyboxMaterial.dispose(true, true);
  97745. }
  97746. this._rootMesh.dispose(false);
  97747. };
  97748. /**
  97749. * Default ground texture URL.
  97750. */
  97751. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97752. /**
  97753. * Default skybox texture URL.
  97754. */
  97755. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97756. /**
  97757. * Default environment texture URL.
  97758. */
  97759. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97760. return EnvironmentHelper;
  97761. }());
  97762. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97763. })(BABYLON || (BABYLON = {}));
  97764. //# sourceMappingURL=babylon.environmentHelper.js.map
  97765. var BABYLON;
  97766. (function (BABYLON) {
  97767. /**
  97768. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97769. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97770. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97771. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97772. */
  97773. var VideoDome = /** @class */ (function (_super) {
  97774. __extends(VideoDome, _super);
  97775. /**
  97776. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97777. * @param name Element's name, child elements will append suffixes for their own names.
  97778. * @param urlsOrVideo
  97779. * @param options An object containing optional or exposed sub element properties:
  97780. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97781. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97782. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97783. * @param options **loop=true** Automatically loop video on end.
  97784. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97785. */
  97786. function VideoDome(name, urlsOrVideo, options, scene) {
  97787. var _this = _super.call(this, name, scene) || this;
  97788. // set defaults and manage values
  97789. name = name || "videoDome";
  97790. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97791. options.clickToPlay = Boolean(options.clickToPlay);
  97792. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97793. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97794. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97795. // create
  97796. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97797. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97798. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97799. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97800. flat: false,
  97801. radius: options.size,
  97802. subdivisions: options.resolution,
  97803. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97804. }, scene);
  97805. // configure material
  97806. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97807. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97808. material.reflectionTexture = _this._videoTexture;
  97809. material.useEquirectangularFOV = true;
  97810. material.fovMultiplier = 1.0;
  97811. // configure mesh
  97812. _this._mesh.material = material;
  97813. _this._mesh.parent = _this;
  97814. // optional configuration
  97815. if (options.clickToPlay) {
  97816. scene.onPointerUp = function () {
  97817. _this._videoTexture.video.play();
  97818. };
  97819. }
  97820. return _this;
  97821. }
  97822. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97823. /**
  97824. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97825. * Also see the options.resolution property.
  97826. */
  97827. get: function () {
  97828. return this._material.fovMultiplier;
  97829. },
  97830. set: function (value) {
  97831. this._material.fovMultiplier = value;
  97832. },
  97833. enumerable: true,
  97834. configurable: true
  97835. });
  97836. /**
  97837. * Releases resources associated with this node.
  97838. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97839. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97840. */
  97841. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97842. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97843. this._videoTexture.dispose();
  97844. this._mesh.dispose();
  97845. this._material.dispose();
  97846. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97847. };
  97848. return VideoDome;
  97849. }(BABYLON.Node));
  97850. BABYLON.VideoDome = VideoDome;
  97851. })(BABYLON || (BABYLON = {}));
  97852. //# sourceMappingURL=babylon.videoDome.js.map
  97853. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  97854. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  97855. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97856. globalObject["BABYLON"] = BABYLON;
  97857. //backwards compatibility
  97858. if(typeof earcut !== 'undefined') {
  97859. globalObject["Earcut"] = {
  97860. earcut: earcut
  97861. };
  97862. }
  97863. return BABYLON;
  97864. });
  97865. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22)))
  97866. /***/ }),
  97867. /* 1 */
  97868. /***/ (function(module, exports, __webpack_require__) {
  97869. (function (global, factory) {
  97870. true ? module.exports = factory() :
  97871. typeof define === 'function' && define.amd ? define(factory) :
  97872. (global.deepmerge = factory());
  97873. }(this, (function () { 'use strict';
  97874. var isMergeableObject = function isMergeableObject(value) {
  97875. return isNonNullObject(value)
  97876. && !isSpecial(value)
  97877. };
  97878. function isNonNullObject(value) {
  97879. return !!value && typeof value === 'object'
  97880. }
  97881. function isSpecial(value) {
  97882. var stringValue = Object.prototype.toString.call(value);
  97883. return stringValue === '[object RegExp]'
  97884. || stringValue === '[object Date]'
  97885. || isReactElement(value)
  97886. }
  97887. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  97888. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  97889. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  97890. function isReactElement(value) {
  97891. return value.$$typeof === REACT_ELEMENT_TYPE
  97892. }
  97893. function emptyTarget(val) {
  97894. return Array.isArray(val) ? [] : {}
  97895. }
  97896. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  97897. var clone = !optionsArgument || optionsArgument.clone !== false;
  97898. return (clone && isMergeableObject(value))
  97899. ? deepmerge(emptyTarget(value), value, optionsArgument)
  97900. : value
  97901. }
  97902. function defaultArrayMerge(target, source, optionsArgument) {
  97903. return target.concat(source).map(function(element) {
  97904. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  97905. })
  97906. }
  97907. function mergeObject(target, source, optionsArgument) {
  97908. var destination = {};
  97909. if (isMergeableObject(target)) {
  97910. Object.keys(target).forEach(function(key) {
  97911. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  97912. });
  97913. }
  97914. Object.keys(source).forEach(function(key) {
  97915. if (!isMergeableObject(source[key]) || !target[key]) {
  97916. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  97917. } else {
  97918. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  97919. }
  97920. });
  97921. return destination
  97922. }
  97923. function deepmerge(target, source, optionsArgument) {
  97924. var sourceIsArray = Array.isArray(source);
  97925. var targetIsArray = Array.isArray(target);
  97926. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  97927. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  97928. if (!sourceAndTargetTypesMatch) {
  97929. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  97930. } else if (sourceIsArray) {
  97931. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  97932. return arrayMerge(target, source, optionsArgument)
  97933. } else {
  97934. return mergeObject(target, source, optionsArgument)
  97935. }
  97936. }
  97937. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  97938. if (!Array.isArray(array)) {
  97939. throw new Error('first argument should be an array')
  97940. }
  97941. return array.reduce(function(prev, next) {
  97942. return deepmerge(prev, next, optionsArgument)
  97943. }, {})
  97944. };
  97945. var deepmerge_1 = deepmerge;
  97946. return deepmerge_1;
  97947. })));
  97948. /***/ }),
  97949. /* 2 */
  97950. /***/ (function(module, exports, __webpack_require__) {
  97951. "use strict";
  97952. Object.defineProperty(exports, "__esModule", { value: true });
  97953. /**
  97954. * Is the provided string a URL?
  97955. *
  97956. * @param urlToCheck the url to inspect
  97957. */
  97958. function isUrl(urlToCheck) {
  97959. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  97960. return true;
  97961. }
  97962. return false;
  97963. }
  97964. exports.isUrl = isUrl;
  97965. /**
  97966. * Convert a string from kebab-case to camelCase
  97967. * @param s string to convert
  97968. */
  97969. function kebabToCamel(s) {
  97970. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  97971. }
  97972. exports.kebabToCamel = kebabToCamel;
  97973. //https://gist.github.com/youssman/745578062609e8acac9f
  97974. /**
  97975. * Convert a string from camelCase to kebab-case
  97976. * @param str string to convert
  97977. */
  97978. function camelToKebab(str) {
  97979. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  97980. }
  97981. exports.camelToKebab = camelToKebab;
  97982. /**
  97983. * This will extend an object with configuration values.
  97984. * What it practically does it take the keys from the configuration and set them on the object.
  97985. * I the configuration is a tree, it will traverse into the tree.
  97986. * @param object the object to extend
  97987. * @param config the configuration object that will extend the object
  97988. */
  97989. function extendClassWithConfig(object, config) {
  97990. if (!config)
  97991. return;
  97992. Object.keys(config).forEach(function (key) {
  97993. if (key in object && typeof object[key] !== 'function') {
  97994. // if (typeof object[key] === 'function') return;
  97995. // if it is an object, iterate internally until reaching basic types
  97996. if (typeof object[key] === 'object') {
  97997. extendClassWithConfig(object[key], config[key]);
  97998. }
  97999. else {
  98000. if (config[key] !== undefined) {
  98001. object[key] = config[key];
  98002. }
  98003. }
  98004. }
  98005. });
  98006. }
  98007. exports.extendClassWithConfig = extendClassWithConfig;
  98008. /***/ }),
  98009. /* 3 */
  98010. /***/ (function(module, exports, __webpack_require__) {
  98011. "use strict";
  98012. Object.defineProperty(exports, "__esModule", { value: true });
  98013. var babylonjs_1 = __webpack_require__(0);
  98014. var helper_1 = __webpack_require__(2);
  98015. /**
  98016. * This is a simple HTML mapper.
  98017. * This mapper parses a single HTML element and returns the configuration from its attributes.
  98018. * it parses numbers and boolean values to the corresponding variable types.
  98019. * The following HTML element:
  98020. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  98021. *
  98022. * {
  98023. * test: 1, //a number!
  98024. * randomFlag: boolean, //camelCase and boolean
  98025. * a: {
  98026. * string: {
  98027. * object: "test" //dot-separated object levels
  98028. * }
  98029. * }
  98030. * }
  98031. */
  98032. var HTMLMapper = /** @class */ (function () {
  98033. function HTMLMapper() {
  98034. }
  98035. /**
  98036. * Map a specific element and get configuration from it
  98037. * @param element the HTML element to analyze.
  98038. */
  98039. HTMLMapper.prototype.map = function (element) {
  98040. var config = {};
  98041. var _loop_1 = function (attrIdx) {
  98042. var attr = element.attributes.item(attrIdx);
  98043. if (!attr) {
  98044. return "continue";
  98045. }
  98046. // map "object.property" to the right configuration place.
  98047. var split = attr.nodeName.split('.');
  98048. split.reduce(function (currentConfig, key, idx) {
  98049. //convert html-style to json-style
  98050. var camelKey = helper_1.kebabToCamel(key);
  98051. if (idx === split.length - 1) {
  98052. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  98053. if (val === "true") {
  98054. val = true;
  98055. }
  98056. else if (val === "false") {
  98057. val = false;
  98058. }
  98059. else {
  98060. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  98061. if (isnum) {
  98062. var number = parseFloat(val);
  98063. if (!isNaN(number)) {
  98064. val = number;
  98065. }
  98066. }
  98067. }
  98068. currentConfig[camelKey] = val;
  98069. }
  98070. else {
  98071. currentConfig[camelKey] = currentConfig[camelKey] || {};
  98072. }
  98073. return currentConfig[camelKey];
  98074. }, config);
  98075. };
  98076. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  98077. _loop_1(attrIdx);
  98078. }
  98079. return config;
  98080. };
  98081. return HTMLMapper;
  98082. }());
  98083. /**
  98084. * A simple string-to-JSON mapper.
  98085. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  98086. */
  98087. var JSONMapper = /** @class */ (function () {
  98088. function JSONMapper() {
  98089. }
  98090. JSONMapper.prototype.map = function (rawSource) {
  98091. return JSON.parse(rawSource);
  98092. };
  98093. return JSONMapper;
  98094. }());
  98095. /**
  98096. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  98097. * DOM elements and attributes.
  98098. */
  98099. var DOMMapper = /** @class */ (function () {
  98100. function DOMMapper() {
  98101. }
  98102. /**
  98103. * The mapping function that will convert HTML data to a viewer configuration object
  98104. * @param baseElement the baseElement from which to start traversing
  98105. * @returns a ViewerCOnfiguration object from the provided HTML Element
  98106. */
  98107. DOMMapper.prototype.map = function (baseElement) {
  98108. var htmlMapper = new HTMLMapper();
  98109. var config = htmlMapper.map(baseElement);
  98110. var traverseChildren = function (element, partConfig) {
  98111. var children = element.children;
  98112. if (children.length) {
  98113. for (var i = 0; i < children.length; ++i) {
  98114. var item = children.item(i);
  98115. // use the HTML Mapper to read configuration from a single element
  98116. var configMapped = htmlMapper.map(item);
  98117. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  98118. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  98119. partConfig[key] = [];
  98120. }
  98121. else {
  98122. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  98123. partConfig.push(configMapped);
  98124. }
  98125. else if (partConfig[key]) {
  98126. //exists already! probably an array
  98127. element.setAttribute('array', 'true');
  98128. var oldItem = partConfig[key];
  98129. partConfig = [oldItem, configMapped];
  98130. }
  98131. else {
  98132. partConfig[key] = configMapped;
  98133. }
  98134. }
  98135. traverseChildren(item, partConfig[key] || configMapped);
  98136. }
  98137. }
  98138. return partConfig;
  98139. };
  98140. traverseChildren(baseElement, config);
  98141. return config;
  98142. };
  98143. return DOMMapper;
  98144. }());
  98145. /**
  98146. * The MapperManager manages the different implemented mappers.
  98147. * It allows the user to register new mappers as well and use them to parse their own configuration data
  98148. */
  98149. var MapperManager = /** @class */ (function () {
  98150. function MapperManager() {
  98151. this._mappers = {
  98152. "html": new HTMLMapper(),
  98153. "json": new JSONMapper(),
  98154. "dom": new DOMMapper()
  98155. };
  98156. }
  98157. /**
  98158. * Get a specific configuration mapper.
  98159. *
  98160. * @param type the name of the mapper to load
  98161. */
  98162. MapperManager.prototype.getMapper = function (type) {
  98163. if (!this._mappers[type]) {
  98164. babylonjs_1.Tools.Error("No mapper defined for " + type);
  98165. }
  98166. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  98167. };
  98168. /**
  98169. * Use this functio to register your own configuration mapper.
  98170. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  98171. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  98172. * @param mapper The implemented mapper
  98173. */
  98174. MapperManager.prototype.registerMapper = function (type, mapper) {
  98175. this._mappers[type] = mapper;
  98176. };
  98177. /**
  98178. * Dispose the mapper manager and all of its mappers.
  98179. */
  98180. MapperManager.prototype.dispose = function () {
  98181. this._mappers = {};
  98182. };
  98183. /**
  98184. * The default mapper is the JSON mapper.
  98185. */
  98186. MapperManager.DefaultMapper = 'json';
  98187. return MapperManager;
  98188. }());
  98189. exports.MapperManager = MapperManager;
  98190. /**
  98191. * mapperManager is a singleton of the type MapperManager.
  98192. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  98193. * or indirectly with using BabylonViewer.disposeAll()
  98194. */
  98195. exports.mapperManager = new MapperManager();
  98196. /***/ }),
  98197. /* 4 */
  98198. /***/ (function(module, exports, __webpack_require__) {
  98199. "use strict";
  98200. Object.defineProperty(exports, "__esModule", { value: true });
  98201. var babylonjs_1 = __webpack_require__(0);
  98202. var modelAnimation_1 = __webpack_require__(28);
  98203. var deepmerge = __webpack_require__(1);
  98204. var helper_1 = __webpack_require__(2);
  98205. /**
  98206. * The current state of the model
  98207. */
  98208. var ModelState;
  98209. (function (ModelState) {
  98210. ModelState[ModelState["INIT"] = 0] = "INIT";
  98211. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  98212. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  98213. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  98214. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  98215. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  98216. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  98217. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  98218. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  98219. /**
  98220. * The viewer model is a container for all assets representing a sngle loaded model.
  98221. */
  98222. var ViewerModel = /** @class */ (function () {
  98223. function ViewerModel(_viewer, modelConfiguration) {
  98224. var _this = this;
  98225. this._viewer = _viewer;
  98226. /**
  98227. * the list of meshes that are a part of this model
  98228. */
  98229. this._meshes = [];
  98230. /**
  98231. * ParticleSystems connected to this model
  98232. */
  98233. this.particleSystems = [];
  98234. /**
  98235. * Skeletons defined in this model
  98236. */
  98237. this.skeletons = [];
  98238. this._loaderDone = false;
  98239. this._animatables = [];
  98240. this._frameRate = 60;
  98241. this.onLoadedObservable = new babylonjs_1.Observable();
  98242. this.onLoadErrorObservable = new babylonjs_1.Observable();
  98243. this.onLoadProgressObservable = new babylonjs_1.Observable();
  98244. this.onCompleteObservable = new babylonjs_1.Observable();
  98245. this.onAfterConfigure = new babylonjs_1.Observable();
  98246. this.state = ModelState.INIT;
  98247. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", this._viewer.sceneManager.scene);
  98248. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", this._viewer.sceneManager.scene);
  98249. this._pivotMesh.parent = this.rootMesh;
  98250. // rotate 180, gltf fun
  98251. this._pivotMesh.rotation.y += Math.PI;
  98252. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98253. this._animations = [];
  98254. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  98255. this._modelConfiguration = deepmerge(this._viewer.configuration.model || {}, modelConfiguration);
  98256. this._viewer.sceneManager.models.push(this);
  98257. this._viewer.onModelAddedObservable.notifyObservers(this);
  98258. this.onLoadedObservable.add(function () {
  98259. _this.updateConfiguration(_this._modelConfiguration);
  98260. _this._viewer.onModelLoadedObservable.notifyObservers(_this);
  98261. _this._initAnimations();
  98262. });
  98263. this.onCompleteObservable.add(function () {
  98264. _this.state = ModelState.COMPLETE;
  98265. });
  98266. }
  98267. Object.defineProperty(ViewerModel.prototype, "enabled", {
  98268. /**
  98269. * Is this model enabled?
  98270. */
  98271. get: function () {
  98272. return this.rootMesh.isEnabled();
  98273. },
  98274. /**
  98275. * Set whether this model is enabled or not.
  98276. */
  98277. set: function (enable) {
  98278. this.rootMesh.setEnabled(enable);
  98279. },
  98280. enumerable: true,
  98281. configurable: true
  98282. });
  98283. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  98284. set: function (done) {
  98285. this._loaderDone = done;
  98286. this._checkCompleteState();
  98287. },
  98288. enumerable: true,
  98289. configurable: true
  98290. });
  98291. ViewerModel.prototype._checkCompleteState = function () {
  98292. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  98293. this._modelComplete();
  98294. }
  98295. };
  98296. /**
  98297. * Get the viewer showing this model
  98298. */
  98299. ViewerModel.prototype.getViewer = function () {
  98300. return this._viewer;
  98301. };
  98302. /**
  98303. * Add a mesh to this model.
  98304. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  98305. *
  98306. * @param mesh the new mesh to add
  98307. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  98308. */
  98309. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  98310. if (!mesh.parent) {
  98311. mesh.parent = this._pivotMesh;
  98312. }
  98313. mesh.receiveShadows = !!this.configuration.receiveShadows;
  98314. this._meshes.push(mesh);
  98315. if (triggerLoaded) {
  98316. return this.onLoadedObservable.notifyObserversWithPromise(this);
  98317. }
  98318. };
  98319. Object.defineProperty(ViewerModel.prototype, "meshes", {
  98320. /**
  98321. * get the list of meshes (excluding the root mesh)
  98322. */
  98323. get: function () {
  98324. return this._meshes;
  98325. },
  98326. enumerable: true,
  98327. configurable: true
  98328. });
  98329. Object.defineProperty(ViewerModel.prototype, "configuration", {
  98330. /**
  98331. * Get the model's configuration
  98332. */
  98333. get: function () {
  98334. return this._modelConfiguration;
  98335. },
  98336. /**
  98337. * (Re-)set the model's entire configuration
  98338. * @param newConfiguration the new configuration to replace the new one
  98339. */
  98340. set: function (newConfiguration) {
  98341. this._modelConfiguration = newConfiguration;
  98342. this._configureModel();
  98343. },
  98344. enumerable: true,
  98345. configurable: true
  98346. });
  98347. /**
  98348. * Update the current configuration with new values.
  98349. * Configuration will not be overwritten, but merged with the new configuration.
  98350. * Priority is to the new configuration
  98351. * @param newConfiguration the configuration to be merged into the current configuration;
  98352. */
  98353. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  98354. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  98355. this._configureModel();
  98356. };
  98357. ViewerModel.prototype._initAnimations = function () {
  98358. var _this = this;
  98359. // check if this is not a gltf loader and init the animations
  98360. if (this.skeletons.length) {
  98361. this.skeletons.forEach(function (skeleton, idx) {
  98362. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.sceneManager.scene);
  98363. skeleton.getAnimatables().forEach(function (a) {
  98364. if (a.animations[0]) {
  98365. ag.addTargetedAnimation(a.animations[0], a);
  98366. }
  98367. });
  98368. _this.addAnimationGroup(ag);
  98369. });
  98370. }
  98371. var completeCallback = function () {
  98372. };
  98373. if (this._modelConfiguration.animation) {
  98374. if (this._modelConfiguration.animation.playOnce) {
  98375. this._animations.forEach(function (a) {
  98376. a.playMode = 0 /* ONCE */;
  98377. });
  98378. }
  98379. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  98380. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  98381. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  98382. completeCallback = function () {
  98383. _this.playAnimation(animationName_1);
  98384. };
  98385. }
  98386. }
  98387. this._enterScene(completeCallback);
  98388. };
  98389. /**
  98390. * Animates the model from the current position to the default position
  98391. * @param completeCallback A function to call when the animation has completed
  98392. */
  98393. ViewerModel.prototype._enterScene = function (completeCallback) {
  98394. var _this = this;
  98395. var callback = function () {
  98396. _this.state = ModelState.ENTRYDONE;
  98397. _this._viewer.sceneManager.animationBlendingEnabled = true;
  98398. _this._checkCompleteState();
  98399. if (completeCallback)
  98400. completeCallback();
  98401. };
  98402. if (!this._entryAnimation) {
  98403. callback();
  98404. return;
  98405. }
  98406. // disable blending for the sake of the entry animation;
  98407. this._viewer.sceneManager.animationBlendingEnabled = false;
  98408. this._applyAnimation(this._entryAnimation, true, callback);
  98409. };
  98410. /**
  98411. * Animates the model from the current position to the exit-screen position
  98412. * @param completeCallback A function to call when the animation has completed
  98413. */
  98414. ViewerModel.prototype._exitScene = function (completeCallback) {
  98415. if (!this._exitAnimation) {
  98416. completeCallback();
  98417. return;
  98418. }
  98419. this._applyAnimation(this._exitAnimation, false, completeCallback);
  98420. };
  98421. ViewerModel.prototype._modelComplete = function () {
  98422. var _this = this;
  98423. //reapply material defines to be sure:
  98424. var meshes = this._pivotMesh.getChildMeshes(false);
  98425. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  98426. _this._applyModelMaterialConfiguration(mesh.material);
  98427. });
  98428. this.state = ModelState.COMPLETE;
  98429. this.onCompleteObservable.notifyObservers(this);
  98430. };
  98431. /**
  98432. * Add a new animation group to this model.
  98433. * @param animationGroup the new animation group to be added
  98434. */
  98435. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  98436. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  98437. };
  98438. /**
  98439. * Get the ModelAnimation array
  98440. */
  98441. ViewerModel.prototype.getAnimations = function () {
  98442. return this._animations;
  98443. };
  98444. /**
  98445. * Get the animations' names. Using the names you can play a specific animation.
  98446. */
  98447. ViewerModel.prototype.getAnimationNames = function () {
  98448. return this._animations.map(function (a) { return a.name; });
  98449. };
  98450. /**
  98451. * Get an animation by the provided name. Used mainly when playing n animation.
  98452. * @param name the name of the animation to find
  98453. */
  98454. ViewerModel.prototype._getAnimationByName = function (name) {
  98455. // can't use .find, noe available on IE
  98456. var filtered = this._animations.filter(function (a) { return a.name === name; });
  98457. // what the next line means - if two animations have the same name, they will not be returned!
  98458. if (filtered.length === 1) {
  98459. return filtered[0];
  98460. }
  98461. else {
  98462. return null;
  98463. }
  98464. };
  98465. /**
  98466. * Choose an initialized animation using its name and start playing it
  98467. * @param name the name of the animation to play
  98468. * @returns The model aniamtion to be played.
  98469. */
  98470. ViewerModel.prototype.playAnimation = function (name) {
  98471. var animation = this.setCurrentAnimationByName(name);
  98472. if (animation) {
  98473. animation.start();
  98474. }
  98475. return animation;
  98476. };
  98477. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  98478. var animation = this._getAnimationByName(name);
  98479. if (animation) {
  98480. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  98481. this.currentAnimation.stop();
  98482. }
  98483. this.currentAnimation = animation;
  98484. return animation;
  98485. }
  98486. else {
  98487. throw new Error("animation not found - " + name);
  98488. }
  98489. };
  98490. ViewerModel.prototype._configureModel = function () {
  98491. var _this = this;
  98492. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  98493. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  98494. var updateMeshesWithNoParent = function (variable, value, param) {
  98495. meshesWithNoParent.forEach(function (mesh) {
  98496. if (param) {
  98497. mesh[variable][param] = value;
  98498. }
  98499. else {
  98500. mesh[variable] = value;
  98501. }
  98502. });
  98503. };
  98504. var updateXYZ = function (variable, configValues) {
  98505. if (configValues.x !== undefined) {
  98506. updateMeshesWithNoParent(variable, configValues.x, 'x');
  98507. }
  98508. if (configValues.y !== undefined) {
  98509. updateMeshesWithNoParent(variable, configValues.y, 'y');
  98510. }
  98511. if (configValues.z !== undefined) {
  98512. updateMeshesWithNoParent(variable, configValues.z, 'z');
  98513. }
  98514. if (configValues.w !== undefined) {
  98515. updateMeshesWithNoParent(variable, configValues.w, 'w');
  98516. }
  98517. };
  98518. if (this._modelConfiguration.normalize) {
  98519. var center = false;
  98520. var unitSize = false;
  98521. var parentIndex = void 0;
  98522. if (this._modelConfiguration.normalize === true) {
  98523. center = true;
  98524. unitSize = true;
  98525. }
  98526. else {
  98527. center = !!this._modelConfiguration.normalize.center;
  98528. unitSize = !!this._modelConfiguration.normalize.unitSize;
  98529. parentIndex = this._modelConfiguration.normalize.parentIndex;
  98530. }
  98531. var meshesToNormalize = [];
  98532. if (parentIndex !== undefined) {
  98533. meshesToNormalize.push(this._meshes[parentIndex]);
  98534. }
  98535. else {
  98536. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  98537. }
  98538. if (unitSize) {
  98539. meshesToNormalize.forEach(function (mesh) {
  98540. mesh.normalizeToUnitCube(true);
  98541. mesh.computeWorldMatrix(true);
  98542. });
  98543. }
  98544. if (center) {
  98545. meshesToNormalize.forEach(function (mesh) {
  98546. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  98547. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  98548. var halfSizeVec = sizeVec.scale(0.5);
  98549. var center = boundingInfo.min.add(halfSizeVec);
  98550. mesh.position = center.scale(-1);
  98551. mesh.position.y += halfSizeVec.y;
  98552. // Recompute Info.
  98553. mesh.computeWorldMatrix(true);
  98554. });
  98555. }
  98556. }
  98557. else {
  98558. // if centered, should be done here
  98559. }
  98560. // position?
  98561. if (this._modelConfiguration.position) {
  98562. updateXYZ('position', this._modelConfiguration.position);
  98563. }
  98564. if (this._modelConfiguration.rotation) {
  98565. //quaternion?
  98566. if (this._modelConfiguration.rotation.w) {
  98567. meshesWithNoParent.forEach(function (mesh) {
  98568. if (!mesh.rotationQuaternion) {
  98569. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  98570. }
  98571. });
  98572. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  98573. }
  98574. else {
  98575. updateXYZ('rotation', this._modelConfiguration.rotation);
  98576. }
  98577. }
  98578. if (this._modelConfiguration.rotationOffsetAxis) {
  98579. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  98580. meshesWithNoParent.forEach(function (m) {
  98581. if (_this._modelConfiguration.rotationOffsetAngle) {
  98582. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  98583. }
  98584. });
  98585. }
  98586. if (this._modelConfiguration.scaling) {
  98587. updateXYZ('scaling', this._modelConfiguration.scaling);
  98588. }
  98589. if (this._modelConfiguration.castShadow) {
  98590. this._meshes.forEach(function (mesh) {
  98591. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  98592. });
  98593. }
  98594. var meshes = this._pivotMesh.getChildMeshes(false);
  98595. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  98596. _this._applyModelMaterialConfiguration(mesh.material);
  98597. });
  98598. if (this._modelConfiguration.entryAnimation) {
  98599. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  98600. }
  98601. if (this._modelConfiguration.exitAnimation) {
  98602. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  98603. }
  98604. this.onAfterConfigure.notifyObservers(this);
  98605. };
  98606. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  98607. var anim = {
  98608. time: 0.5
  98609. };
  98610. if (animConfig.scaling) {
  98611. anim.scaling = babylonjs_1.Vector3.Zero();
  98612. }
  98613. if (animConfig.easingFunction !== undefined) {
  98614. anim.easingFunction = animConfig.easingFunction;
  98615. }
  98616. if (animConfig.easingMode !== undefined) {
  98617. anim.easingMode = animConfig.easingMode;
  98618. }
  98619. helper_1.extendClassWithConfig(anim, animConfig);
  98620. return anim;
  98621. };
  98622. /**
  98623. * Apply a material configuration to a material
  98624. * @param material Material to apply configuration to
  98625. */
  98626. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  98627. if (!this._modelConfiguration.material)
  98628. return;
  98629. helper_1.extendClassWithConfig(material, this._modelConfiguration.material);
  98630. if (material instanceof babylonjs_1.PBRMaterial) {
  98631. if (this._modelConfiguration.material.directIntensity !== undefined) {
  98632. material.directIntensity = this._modelConfiguration.material.directIntensity;
  98633. }
  98634. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  98635. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  98636. }
  98637. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  98638. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  98639. }
  98640. if (this._modelConfiguration.material.directEnabled !== undefined) {
  98641. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  98642. }
  98643. if (this._viewer.sceneManager.reflectionColor) {
  98644. material.reflectionColor = this._viewer.sceneManager.reflectionColor;
  98645. }
  98646. }
  98647. else if (material instanceof babylonjs_1.MultiMaterial) {
  98648. for (var i = 0; i < material.subMaterials.length; i++) {
  98649. var subMaterial = material.subMaterials[i];
  98650. if (subMaterial) {
  98651. this._applyModelMaterialConfiguration(subMaterial);
  98652. }
  98653. }
  98654. }
  98655. };
  98656. /**
  98657. * Start entry/exit animation given an animation configuration
  98658. * @param animationConfiguration Entry/Exit animation configuration
  98659. * @param isEntry Pass true if the animation is an entry animation
  98660. * @param completeCallback Callback to execute when the animation completes
  98661. */
  98662. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  98663. var animations = [];
  98664. //scale
  98665. if (animationConfiguration.scaling) {
  98666. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  98667. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  98668. if (!scaleStart.equals(scaleEnd)) {
  98669. this.rootMesh.scaling = scaleStart;
  98670. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  98671. animations.push(this._scaleTransition);
  98672. }
  98673. }
  98674. //Start the animation(s)
  98675. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  98676. completeCallback(); });
  98677. };
  98678. /**
  98679. * Begin @animations with the specified @easingFunction
  98680. * @param animations The BABYLON Animations to begin
  98681. * @param duration of transition, in seconds
  98682. * @param easingFunction An easing function to apply
  98683. * @param easingMode A easing mode to apply to the easingFunction
  98684. * @param onAnimationEnd Call back trigger at the end of the animation.
  98685. */
  98686. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  98687. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  98688. if (easingFunction) {
  98689. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  98690. var animation = animations_1[_i];
  98691. easingFunction.setEasingMode(easingMode);
  98692. animation.setEasingFunction(easingFunction);
  98693. }
  98694. }
  98695. //Stop any current animations before starting the new one - merging not yet supported.
  98696. this.stopAllAnimations();
  98697. this.rootMesh.animations = animations;
  98698. if (this._viewer.sceneManager.scene.beginAnimation) {
  98699. var animatable = this._viewer.sceneManager.scene.beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  98700. if (onAnimationEnd) {
  98701. onAnimationEnd();
  98702. }
  98703. });
  98704. this._animatables.push(animatable);
  98705. }
  98706. };
  98707. /**
  98708. * Sets key values on an Animation from first to last frame.
  98709. * @param animation The Babylon animation object to set keys on
  98710. * @param startValue The value of the first key
  98711. * @param endValue The value of the last key
  98712. * @param duration The duration of the animation, used to determine the end frame
  98713. */
  98714. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  98715. animation.setKeys([
  98716. {
  98717. frame: 0,
  98718. value: startValue
  98719. },
  98720. {
  98721. frame: this._frameRate * duration,
  98722. value: endValue
  98723. }
  98724. ]);
  98725. };
  98726. /**
  98727. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  98728. * @param easingFunctionID The enum of the easing funtion to create
  98729. * @return The newly created Babylon easing function object
  98730. */
  98731. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  98732. var easingFunction;
  98733. switch (easingFunctionID) {
  98734. case 1 /* CircleEase */:
  98735. easingFunction = new babylonjs_1.CircleEase();
  98736. break;
  98737. case 2 /* BackEase */:
  98738. easingFunction = new babylonjs_1.BackEase(0.3);
  98739. break;
  98740. case 3 /* BounceEase */:
  98741. easingFunction = new babylonjs_1.BounceEase();
  98742. break;
  98743. case 4 /* CubicEase */:
  98744. easingFunction = new babylonjs_1.CubicEase();
  98745. break;
  98746. case 5 /* ElasticEase */:
  98747. easingFunction = new babylonjs_1.ElasticEase();
  98748. break;
  98749. case 6 /* ExponentialEase */:
  98750. easingFunction = new babylonjs_1.ExponentialEase();
  98751. break;
  98752. case 7 /* PowerEase */:
  98753. easingFunction = new babylonjs_1.PowerEase();
  98754. break;
  98755. case 8 /* QuadraticEase */:
  98756. easingFunction = new babylonjs_1.QuadraticEase();
  98757. break;
  98758. case 9 /* QuarticEase */:
  98759. easingFunction = new babylonjs_1.QuarticEase();
  98760. break;
  98761. case 10 /* QuinticEase */:
  98762. easingFunction = new babylonjs_1.QuinticEase();
  98763. break;
  98764. case 11 /* SineEase */:
  98765. easingFunction = new babylonjs_1.SineEase();
  98766. break;
  98767. default:
  98768. babylonjs_1.Tools.Log("No ease function found");
  98769. break;
  98770. }
  98771. return easingFunction;
  98772. };
  98773. /**
  98774. * Stops and removes all animations that have been applied to the model
  98775. */
  98776. ViewerModel.prototype.stopAllAnimations = function () {
  98777. if (this.rootMesh) {
  98778. this.rootMesh.animations = [];
  98779. }
  98780. if (this.currentAnimation) {
  98781. this.currentAnimation.stop();
  98782. }
  98783. while (this._animatables.length) {
  98784. this._animatables[0].onAnimationEnd = null;
  98785. this._animatables[0].stop();
  98786. this._animatables.shift();
  98787. }
  98788. };
  98789. /**
  98790. * Will remove this model from the viewer (but NOT dispose it).
  98791. */
  98792. ViewerModel.prototype.remove = function () {
  98793. this.stopAllAnimations();
  98794. this._viewer.sceneManager.models.splice(this._viewer.sceneManager.models.indexOf(this), 1);
  98795. // hide it
  98796. this.rootMesh.isVisible = false;
  98797. this._viewer.onModelRemovedObservable.notifyObservers(this);
  98798. };
  98799. /**
  98800. * Dispose this model, including all of its associated assets.
  98801. */
  98802. ViewerModel.prototype.dispose = function () {
  98803. this.remove();
  98804. this.onAfterConfigure.clear();
  98805. this.onLoadedObservable.clear();
  98806. this.onLoadErrorObservable.clear();
  98807. this.onLoadProgressObservable.clear();
  98808. if (this.loader && this.loader.name === "gltf") {
  98809. this.loader.dispose();
  98810. }
  98811. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  98812. this.particleSystems.length = 0;
  98813. this.skeletons.forEach(function (s) { return s.dispose(); });
  98814. this.skeletons.length = 0;
  98815. this._animations.forEach(function (ag) { return ag.dispose(); });
  98816. this._animations.length = 0;
  98817. this.rootMesh.dispose(false, true);
  98818. };
  98819. return ViewerModel;
  98820. }());
  98821. exports.ViewerModel = ViewerModel;
  98822. /***/ }),
  98823. /* 5 */
  98824. /***/ (function(module, exports, __webpack_require__) {
  98825. "use strict";
  98826. Object.defineProperty(exports, "__esModule", { value: true });
  98827. var babylonjs_1 = __webpack_require__(0);
  98828. /**
  98829. * Receives Telemetry events and raises events to the API
  98830. */
  98831. var TelemetryManager = /** @class */ (function () {
  98832. function TelemetryManager() {
  98833. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  98834. this._event = this._eventEnabled;
  98835. }
  98836. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  98837. /**
  98838. * Receives a telemetry event
  98839. * @param event The name of the Telemetry event
  98840. * @param details An additional value, or an object containing a list of property/value pairs
  98841. */
  98842. get: function () {
  98843. return this._event;
  98844. },
  98845. enumerable: true,
  98846. configurable: true
  98847. });
  98848. /**
  98849. * Log a Telemetry event for errors raised on the WebGL context.
  98850. * @param engine The Babylon engine with the WebGL context.
  98851. */
  98852. TelemetryManager.prototype.flushWebGLErrors = function (viewer) {
  98853. var engine = viewer.engine;
  98854. if (!engine) {
  98855. return;
  98856. }
  98857. var logErrors = true;
  98858. while (logErrors) {
  98859. var gl = engine._gl;
  98860. if (gl && gl.getError) {
  98861. var error = gl.getError();
  98862. if (error === gl.NO_ERROR) {
  98863. logErrors = false;
  98864. }
  98865. else {
  98866. this.broadcast("WebGL Error", viewer, { error: error });
  98867. }
  98868. }
  98869. else {
  98870. logErrors = false;
  98871. }
  98872. }
  98873. };
  98874. Object.defineProperty(TelemetryManager.prototype, "enable", {
  98875. /**
  98876. * Enable or disable telemetry events
  98877. * @param enabled Boolan, true if events are enabled
  98878. */
  98879. set: function (enabled) {
  98880. if (enabled) {
  98881. this._event = this._eventEnabled;
  98882. }
  98883. else {
  98884. this._event = this._eventDisabled;
  98885. }
  98886. },
  98887. enumerable: true,
  98888. configurable: true
  98889. });
  98890. /**
  98891. * Called on event when disabled, typically do nothing here
  98892. */
  98893. TelemetryManager.prototype._eventDisabled = function () {
  98894. // nothing to do
  98895. };
  98896. /**
  98897. * Called on event when enabled
  98898. * @param event - The name of the Telemetry event
  98899. * @param details An additional value, or an object containing a list of property/value pairs
  98900. */
  98901. TelemetryManager.prototype._eventEnabled = function (event, viewer, details) {
  98902. var telemetryData = {
  98903. viewer: viewer,
  98904. event: event,
  98905. session: this.session,
  98906. date: new Date(),
  98907. now: window.performance ? window.performance.now() : Date.now(),
  98908. detail: null
  98909. };
  98910. if (typeof details === "object") {
  98911. for (var attr in details) {
  98912. if (details.hasOwnProperty(attr)) {
  98913. telemetryData[attr] = details[attr];
  98914. }
  98915. }
  98916. }
  98917. else if (details) {
  98918. telemetryData.detail = details;
  98919. }
  98920. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  98921. };
  98922. Object.defineProperty(TelemetryManager.prototype, "session", {
  98923. /**
  98924. * Returns the current session ID or creates one if it doesn't exixt
  98925. * @return The current session ID
  98926. */
  98927. get: function () {
  98928. if (!this._currentSessionId) {
  98929. //String + Timestamp + Random Integer
  98930. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  98931. }
  98932. return this._currentSessionId;
  98933. },
  98934. enumerable: true,
  98935. configurable: true
  98936. });
  98937. /**
  98938. * Disposes the telemetry manager
  98939. */
  98940. TelemetryManager.prototype.dispose = function () {
  98941. this.onEventBroadcastedObservable.clear();
  98942. delete this.onEventBroadcastedObservable;
  98943. };
  98944. return TelemetryManager;
  98945. }());
  98946. exports.TelemetryManager = TelemetryManager;
  98947. exports.telemetryManager = new TelemetryManager();
  98948. /***/ }),
  98949. /* 6 */
  98950. /***/ (function(module, exports, __webpack_require__) {
  98951. "use strict";
  98952. Object.defineProperty(exports, "__esModule", { value: true });
  98953. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  98954. var mappers_1 = __webpack_require__(3);
  98955. exports.mapperManager = mappers_1.mapperManager;
  98956. var globals_1 = __webpack_require__(7);
  98957. exports.viewerGlobals = globals_1.viewerGlobals;
  98958. var viewerManager_1 = __webpack_require__(8);
  98959. exports.viewerManager = viewerManager_1.viewerManager;
  98960. var defaultViewer_1 = __webpack_require__(9);
  98961. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  98962. var viewer_1 = __webpack_require__(10);
  98963. exports.AbstractViewer = viewer_1.AbstractViewer;
  98964. var telemetryManager_1 = __webpack_require__(5);
  98965. exports.telemetryManager = telemetryManager_1.telemetryManager;
  98966. var modelLoader_1 = __webpack_require__(19);
  98967. exports.ModelLoader = modelLoader_1.ModelLoader;
  98968. var viewerModel_1 = __webpack_require__(4);
  98969. exports.ViewerModel = viewerModel_1.ViewerModel;
  98970. exports.ModelState = viewerModel_1.ModelState;
  98971. /**
  98972. * BabylonJS Viewer
  98973. *
  98974. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  98975. */
  98976. var BABYLON = __webpack_require__(0);
  98977. exports.BABYLON = BABYLON;
  98978. // load needed modules.
  98979. __webpack_require__(20);
  98980. __webpack_require__(53);
  98981. var initializer_1 = __webpack_require__(54);
  98982. exports.InitTags = initializer_1.InitTags;
  98983. // promise polyfill, if needed!
  98984. BABYLON.PromisePolyfill.Apply();
  98985. initializer_1.initListeners();
  98986. //deprectaed, here for backwards compatibility
  98987. var disableInit = globals_1.viewerGlobals.disableInit;
  98988. exports.disableInit = disableInit;
  98989. /**
  98990. * Dispose all viewers currently registered
  98991. */
  98992. function disposeAll() {
  98993. viewerManager_1.viewerManager.dispose();
  98994. mappers_1.mapperManager.dispose();
  98995. telemetryManager_1.telemetryManager.dispose();
  98996. }
  98997. exports.disposeAll = disposeAll;
  98998. var Version = BABYLON.Engine.Version;
  98999. exports.Version = Version;
  99000. console.log("Babylon.js viewer (v" + Version + ")");
  99001. /***/ }),
  99002. /* 7 */
  99003. /***/ (function(module, exports, __webpack_require__) {
  99004. "use strict";
  99005. Object.defineProperty(exports, "__esModule", { value: true });
  99006. var ViewerGlobals = /** @class */ (function () {
  99007. function ViewerGlobals() {
  99008. this.disableInit = false;
  99009. this.disableWebGL2Support = false;
  99010. }
  99011. return ViewerGlobals;
  99012. }());
  99013. exports.ViewerGlobals = ViewerGlobals;
  99014. exports.viewerGlobals = new ViewerGlobals();
  99015. /***/ }),
  99016. /* 8 */
  99017. /***/ (function(module, exports, __webpack_require__) {
  99018. "use strict";
  99019. Object.defineProperty(exports, "__esModule", { value: true });
  99020. var babylonjs_1 = __webpack_require__(0);
  99021. /**
  99022. * The viewer manager is the container for all viewers currently registered on this page.
  99023. * It is possible to have more than one viewer on a single page.
  99024. */
  99025. var ViewerManager = /** @class */ (function () {
  99026. function ViewerManager() {
  99027. this._viewers = {};
  99028. this.onViewerAddedObservable = new babylonjs_1.Observable();
  99029. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  99030. }
  99031. /**
  99032. * Adding a new viewer to the viewer manager and start tracking it.
  99033. * @param viewer the viewer to add
  99034. */
  99035. ViewerManager.prototype.addViewer = function (viewer) {
  99036. this._viewers[viewer.getBaseId()] = viewer;
  99037. this._onViewerAdded(viewer);
  99038. };
  99039. /**
  99040. * remove a viewer from the viewer manager
  99041. * @param viewer the viewer to remove
  99042. */
  99043. ViewerManager.prototype.removeViewer = function (viewer) {
  99044. var id = viewer.getBaseId();
  99045. delete this._viewers[id];
  99046. this.onViewerRemovedObservable.notifyObservers(id);
  99047. };
  99048. /**
  99049. * Get a viewer by its baseId (if the container element has an ID, it is the this is. if not, a random id was assigned)
  99050. * @param id the id of the HTMl element (or the viewer's, if none provided)
  99051. */
  99052. ViewerManager.prototype.getViewerById = function (id) {
  99053. return this._viewers[id];
  99054. };
  99055. /**
  99056. * Get a viewer using a container element
  99057. * @param element the HTML element to search viewers associated with
  99058. */
  99059. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  99060. for (var id in this._viewers) {
  99061. if (this._viewers[id].containerElement === element) {
  99062. return this.getViewerById(id);
  99063. }
  99064. }
  99065. };
  99066. /**
  99067. * Get a promise that will fullfil when this viewer was initialized.
  99068. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  99069. * you will get the viewer after everything was already configured.
  99070. * @param id the viewer id to find
  99071. */
  99072. ViewerManager.prototype.getViewerPromiseById = function (id) {
  99073. var _this = this;
  99074. return new Promise(function (resolve, reject) {
  99075. var localViewer = _this.getViewerById(id);
  99076. if (localViewer) {
  99077. return resolve(localViewer);
  99078. }
  99079. var viewerFunction = function (viewer) {
  99080. if (viewer.getBaseId() === id) {
  99081. resolve(viewer);
  99082. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  99083. }
  99084. };
  99085. _this.onViewerAddedObservable.add(viewerFunction);
  99086. });
  99087. };
  99088. ViewerManager.prototype._onViewerAdded = function (viewer) {
  99089. this.onViewerAdded && this.onViewerAdded(viewer);
  99090. this.onViewerAddedObservable.notifyObservers(viewer);
  99091. };
  99092. /**
  99093. * dispose the manager and all of its associated viewers
  99094. */
  99095. ViewerManager.prototype.dispose = function () {
  99096. for (var id in this._viewers) {
  99097. this._viewers[id].dispose();
  99098. }
  99099. };
  99100. return ViewerManager;
  99101. }());
  99102. exports.ViewerManager = ViewerManager;
  99103. exports.viewerManager = new ViewerManager();
  99104. /***/ }),
  99105. /* 9 */
  99106. /***/ (function(module, exports, __webpack_require__) {
  99107. "use strict";
  99108. var __extends = (this && this.__extends) || (function () {
  99109. var extendStatics = Object.setPrototypeOf ||
  99110. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  99111. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  99112. return function (d, b) {
  99113. extendStatics(d, b);
  99114. function __() { this.constructor = d; }
  99115. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  99116. };
  99117. })();
  99118. Object.defineProperty(exports, "__esModule", { value: true });
  99119. var viewer_1 = __webpack_require__(10);
  99120. var babylonjs_1 = __webpack_require__(0);
  99121. /**
  99122. * The Default viewer is the default implementation of the AbstractViewer.
  99123. * It uses the templating system to render a new canvas and controls.
  99124. */
  99125. var DefaultViewer = /** @class */ (function (_super) {
  99126. __extends(DefaultViewer, _super);
  99127. /**
  99128. * Create a new default viewer
  99129. * @param containerElement the element in which the templates will be rendered
  99130. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  99131. */
  99132. function DefaultViewer(containerElement, initialConfiguration) {
  99133. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  99134. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  99135. _this.containerElement = containerElement;
  99136. _this._handlePointerDown = function (event) {
  99137. var pointerDown = event.event;
  99138. if (pointerDown.button !== 0)
  99139. return;
  99140. var element = event.event.srcElement;
  99141. if (!element) {
  99142. return;
  99143. }
  99144. var parentClasses = element.parentElement.classList;
  99145. switch (element.id) {
  99146. case "speed-button":
  99147. case "types-button":
  99148. if (parentClasses.contains("open")) {
  99149. parentClasses.remove("open");
  99150. }
  99151. else {
  99152. parentClasses.add("open");
  99153. }
  99154. break;
  99155. case "play-pause-button":
  99156. _this._togglePlayPause();
  99157. break;
  99158. case "label-option-button":
  99159. var label = element.dataset["value"];
  99160. if (label) {
  99161. _this._updateAnimationType(label);
  99162. }
  99163. break;
  99164. case "speed-option-button":
  99165. if (!_this._currentAnimation) {
  99166. return;
  99167. }
  99168. var speed = element.dataset["value"];
  99169. if (speed)
  99170. _this._updateAnimationSpeed(speed);
  99171. break;
  99172. case "progress-wrapper":
  99173. _this._resumePlay = !_this._isAnimationPaused;
  99174. if (_this._resumePlay) {
  99175. _this._togglePlayPause(true);
  99176. }
  99177. break;
  99178. case "fullscreen-button":
  99179. _this.toggleFullscreen();
  99180. default:
  99181. return;
  99182. }
  99183. };
  99184. /**
  99185. * Plays or Pauses animation
  99186. */
  99187. _this._togglePlayPause = function (noUiUpdate) {
  99188. if (!_this._currentAnimation) {
  99189. return;
  99190. }
  99191. if (_this._isAnimationPaused) {
  99192. _this._currentAnimation.restart();
  99193. }
  99194. else {
  99195. _this._currentAnimation.pause();
  99196. }
  99197. _this._isAnimationPaused = !_this._isAnimationPaused;
  99198. if (noUiUpdate)
  99199. return;
  99200. var navbar = _this.templateManager.getTemplate('navBar');
  99201. if (!navbar)
  99202. return;
  99203. navbar.updateParams({
  99204. paused: _this._isAnimationPaused,
  99205. });
  99206. };
  99207. /**
  99208. * Control progress bar position based on animation current frame
  99209. */
  99210. _this._updateProgressBar = function () {
  99211. var navbar = _this.templateManager.getTemplate('navBar');
  99212. if (!navbar)
  99213. return;
  99214. var progressSlider = navbar.parent.querySelector("input#progress-wrapper");
  99215. if (progressSlider && _this._currentAnimation) {
  99216. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  99217. var currentValue = progressSlider.valueAsNumber;
  99218. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  99219. progressSlider.value = '' + progress;
  99220. }
  99221. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  99222. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  99223. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  99224. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  99225. }
  99226. }
  99227. else {
  99228. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  99229. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  99230. _this._oldIdleRotationValue = 0;
  99231. }
  99232. }
  99233. }
  99234. };
  99235. /**
  99236. * Update Current Animation Speed
  99237. */
  99238. _this._updateAnimationSpeed = function (speed, paramsObject) {
  99239. var navbar = _this.templateManager.getTemplate('navBar');
  99240. if (!navbar)
  99241. return;
  99242. if (speed && _this._currentAnimation) {
  99243. _this._currentAnimation.speedRatio = parseFloat(speed);
  99244. if (!_this._isAnimationPaused) {
  99245. _this._currentAnimation.restart();
  99246. }
  99247. if (paramsObject) {
  99248. paramsObject.selectedSpeed = speed + "x";
  99249. }
  99250. else {
  99251. navbar.updateParams({
  99252. selectedSpeed: speed + "x",
  99253. });
  99254. }
  99255. }
  99256. };
  99257. /**
  99258. * Update Current Animation Type
  99259. */
  99260. _this._updateAnimationType = function (label, paramsObject) {
  99261. var navbar = _this.templateManager.getTemplate('navBar');
  99262. if (!navbar)
  99263. return;
  99264. if (label) {
  99265. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  99266. }
  99267. if (paramsObject) {
  99268. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  99269. paramsObject.selectedAnimationName = label;
  99270. }
  99271. else {
  99272. navbar.updateParams({
  99273. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  99274. selectedAnimationName: label
  99275. });
  99276. }
  99277. _this._updateAnimationSpeed("1.0", paramsObject);
  99278. };
  99279. /**
  99280. * Toggle fullscreen of the entire viewer
  99281. */
  99282. _this.toggleFullscreen = function () {
  99283. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  99284. var viewerElement = viewerTemplate && viewerTemplate.parent;
  99285. if (viewerElement) {
  99286. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  99287. if (!fullscreenElement) {
  99288. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  99289. requestFullScreen.call(viewerElement);
  99290. }
  99291. else {
  99292. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  99293. exitFullscreen.call(document);
  99294. }
  99295. }
  99296. };
  99297. _this._onModelLoaded = function (model) {
  99298. _this._configureTemplate(model);
  99299. // with a short timeout, making sure everything is there already.
  99300. var hideLoadingDelay = 20;
  99301. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  99302. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  99303. }
  99304. setTimeout(function () {
  99305. _this.sceneManager.scene.executeWhenReady(function () {
  99306. _this.hideLoadingScreen();
  99307. });
  99308. }, hideLoadingDelay);
  99309. return;
  99310. };
  99311. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  99312. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  99313. _this._configureLights(data.newConfiguration, data.model);
  99314. });
  99315. return _this;
  99316. }
  99317. /**
  99318. * This will be executed when the templates initialize.
  99319. */
  99320. DefaultViewer.prototype._onTemplatesLoaded = function () {
  99321. var _this = this;
  99322. this.showLoadingScreen();
  99323. // navbar
  99324. this._initNavbar();
  99325. // close overlay button
  99326. var closeButton = document.getElementById('close-button');
  99327. if (closeButton) {
  99328. closeButton.addEventListener('pointerdown', function () {
  99329. _this.hideOverlayScreen();
  99330. });
  99331. }
  99332. return _super.prototype._onTemplatesLoaded.call(this);
  99333. };
  99334. DefaultViewer.prototype._initNavbar = function () {
  99335. var _this = this;
  99336. var navbar = this.templateManager.getTemplate('navBar');
  99337. if (navbar) {
  99338. this.onFrameRenderedObservable.add(this._updateProgressBar);
  99339. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  99340. // an example how to trigger the help button. publiclly available
  99341. this.templateManager.eventManager.registerCallback("navBar", function () {
  99342. // do your thing
  99343. }, "pointerdown", "#help-button");
  99344. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  99345. var element = event.event.srcElement;
  99346. if (!_this._currentAnimation)
  99347. return;
  99348. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  99349. if (isNaN(gotoFrame))
  99350. return;
  99351. _this._currentAnimation.goToFrame(gotoFrame);
  99352. }, "input");
  99353. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  99354. if (_this._resumePlay) {
  99355. _this._togglePlayPause(true);
  99356. }
  99357. _this._resumePlay = false;
  99358. }, "pointerup", "#progress-wrapper");
  99359. }
  99360. };
  99361. /**
  99362. * Preparing the container element to present the viewer
  99363. */
  99364. DefaultViewer.prototype._prepareContainerElement = function () {
  99365. this.containerElement.style.position = 'relative';
  99366. this.containerElement.style.height = '100%';
  99367. this.containerElement.style.display = 'flex';
  99368. };
  99369. /**
  99370. * This function will configure the templates and update them after a model was loaded
  99371. * It is mainly responsible to changing the title and subtitle etc'.
  99372. * @param model the model to be used to configure the templates by
  99373. */
  99374. DefaultViewer.prototype._configureTemplate = function (model) {
  99375. var navbar = this.templateManager.getTemplate('navBar');
  99376. if (!navbar)
  99377. return;
  99378. var newParams = {};
  99379. var animationNames = model.getAnimationNames();
  99380. if (animationNames.length >= 1) {
  99381. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  99382. this._animationList = animationNames;
  99383. newParams.animations = this._animationList;
  99384. newParams.paused = this._isAnimationPaused;
  99385. var animationIndex = 0;
  99386. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  99387. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  99388. if (animationIndex === -1) {
  99389. animationIndex = 0;
  99390. }
  99391. }
  99392. this._updateAnimationType(animationNames[animationIndex], newParams);
  99393. }
  99394. if (model.configuration.thumbnail) {
  99395. newParams.logoImage = model.configuration.thumbnail;
  99396. }
  99397. navbar.updateParams(newParams);
  99398. };
  99399. /**
  99400. * This will load a new model to the default viewer
  99401. * overriding the AbstractViewer's loadModel.
  99402. * The scene will automatically be cleared of the old models, if exist.
  99403. * @param model the configuration object (or URL) to load.
  99404. */
  99405. DefaultViewer.prototype.loadModel = function (model) {
  99406. var _this = this;
  99407. if (!model) {
  99408. model = this.configuration.model;
  99409. }
  99410. this.showLoadingScreen();
  99411. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  99412. console.log(error);
  99413. _this.hideLoadingScreen();
  99414. _this.showOverlayScreen('error');
  99415. return Promise.reject(error);
  99416. });
  99417. };
  99418. /**
  99419. * Show the overlay and the defined sub-screen.
  99420. * Mainly used for help and errors
  99421. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  99422. */
  99423. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  99424. var _this = this;
  99425. var template = this.templateManager.getTemplate('overlay');
  99426. if (!template)
  99427. return Promise.resolve('Overlay template not found');
  99428. return template.show((function (template) {
  99429. var canvasRect = _this.containerElement.getBoundingClientRect();
  99430. template.parent.style.display = 'flex';
  99431. template.parent.style.width = canvasRect.width + "px";
  99432. template.parent.style.height = canvasRect.height + "px";
  99433. template.parent.style.opacity = "1";
  99434. var subTemplate = _this.templateManager.getTemplate(subScreen);
  99435. if (!subTemplate) {
  99436. return Promise.reject(subScreen + ' template not found');
  99437. }
  99438. return subTemplate.show((function (template) {
  99439. template.parent.style.display = 'flex';
  99440. return Promise.resolve(template);
  99441. }));
  99442. }));
  99443. };
  99444. /**
  99445. * Hide the overlay screen.
  99446. */
  99447. DefaultViewer.prototype.hideOverlayScreen = function () {
  99448. var template = this.templateManager.getTemplate('overlay');
  99449. if (!template)
  99450. return Promise.resolve('Overlay template not found');
  99451. return template.hide((function (template) {
  99452. template.parent.style.opacity = "0";
  99453. var onTransitionEnd = function () {
  99454. template.parent.removeEventListener("transitionend", onTransitionEnd);
  99455. template.parent.style.display = 'none';
  99456. };
  99457. template.parent.addEventListener("transitionend", onTransitionEnd);
  99458. var overlays = template.parent.querySelectorAll('.overlay');
  99459. if (overlays) {
  99460. for (var i = 0; i < overlays.length; ++i) {
  99461. var htmlElement = overlays.item(i);
  99462. htmlElement.style.display = 'none';
  99463. }
  99464. }
  99465. return Promise.resolve(template);
  99466. }));
  99467. };
  99468. /**
  99469. * show the viewer (in case it was hidden)
  99470. *
  99471. * @param visibilityFunction an optional function to execute in order to show the container
  99472. */
  99473. DefaultViewer.prototype.show = function (visibilityFunction) {
  99474. var template = this.templateManager.getTemplate('main');
  99475. //not possible, but yet:
  99476. if (!template)
  99477. return Promise.reject('Main template not found');
  99478. return template.show(visibilityFunction);
  99479. };
  99480. /**
  99481. * hide the viewer (in case it is visible)
  99482. *
  99483. * @param visibilityFunction an optional function to execute in order to hide the container
  99484. */
  99485. DefaultViewer.prototype.hide = function (visibilityFunction) {
  99486. var template = this.templateManager.getTemplate('main');
  99487. //not possible, but yet:
  99488. if (!template)
  99489. return Promise.reject('Main template not found');
  99490. return template.hide(visibilityFunction);
  99491. };
  99492. /**
  99493. * Show the loading screen.
  99494. * The loading screen can be configured using the configuration object
  99495. */
  99496. DefaultViewer.prototype.showLoadingScreen = function () {
  99497. var _this = this;
  99498. var template = this.templateManager.getTemplate('loadingScreen');
  99499. if (!template)
  99500. return Promise.resolve('Loading Screen template not found');
  99501. return template.show((function (template) {
  99502. var canvasRect = _this.containerElement.getBoundingClientRect();
  99503. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  99504. template.parent.style.display = 'flex';
  99505. template.parent.style.width = canvasRect.width + "px";
  99506. template.parent.style.height = canvasRect.height + "px";
  99507. template.parent.style.opacity = "1";
  99508. // from the configuration!!!
  99509. var color = "black";
  99510. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  99511. color = (_this.configuration.templates.loadingScreen.params &&
  99512. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  99513. }
  99514. template.parent.style.backgroundColor = color;
  99515. return Promise.resolve(template);
  99516. }));
  99517. };
  99518. /**
  99519. * Hide the loading screen
  99520. */
  99521. DefaultViewer.prototype.hideLoadingScreen = function () {
  99522. var template = this.templateManager.getTemplate('loadingScreen');
  99523. if (!template)
  99524. return Promise.resolve('Loading Screen template not found');
  99525. return template.hide((function (template) {
  99526. template.parent.style.opacity = "0";
  99527. var onTransitionEnd = function () {
  99528. template.parent.removeEventListener("transitionend", onTransitionEnd);
  99529. template.parent.style.display = 'none';
  99530. };
  99531. template.parent.addEventListener("transitionend", onTransitionEnd);
  99532. return Promise.resolve(template);
  99533. }));
  99534. };
  99535. /**
  99536. * An extension of the light configuration of the abstract viewer.
  99537. * @param lightsConfiguration the light configuration to use
  99538. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  99539. */
  99540. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  99541. var _this = this;
  99542. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  99543. // labs feature - flashlight
  99544. if (this._configuration.lab && this._configuration.lab.flashlight) {
  99545. var pointerPosition = babylonjs_1.Vector3.Zero();
  99546. var lightTarget_1;
  99547. var angle = 0.5;
  99548. var exponent = Math.PI / 2;
  99549. if (typeof this._configuration.lab.flashlight === "object") {
  99550. exponent = this._configuration.lab.flashlight.exponent || exponent;
  99551. angle = this._configuration.lab.flashlight.angle || angle;
  99552. }
  99553. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  99554. if (typeof this._configuration.lab.flashlight === "object") {
  99555. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  99556. if (this._configuration.lab.flashlight.diffuse) {
  99557. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  99558. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  99559. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  99560. }
  99561. if (this._configuration.lab.flashlight.specular) {
  99562. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  99563. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  99564. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  99565. }
  99566. }
  99567. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  99568. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  99569. if (eventData.type === 4 && eventData.pickInfo) {
  99570. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  99571. }
  99572. else {
  99573. lightTarget_1 = undefined;
  99574. }
  99575. });
  99576. var updateFlashlightFunction = function () {
  99577. if (_this.sceneManager.camera && flashlight) {
  99578. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  99579. if (lightTarget_1) {
  99580. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  99581. }
  99582. }
  99583. };
  99584. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  99585. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  99586. }
  99587. };
  99588. return DefaultViewer;
  99589. }(viewer_1.AbstractViewer));
  99590. exports.DefaultViewer = DefaultViewer;
  99591. /***/ }),
  99592. /* 10 */
  99593. /***/ (function(module, exports, __webpack_require__) {
  99594. "use strict";
  99595. Object.defineProperty(exports, "__esModule", { value: true });
  99596. var viewerManager_1 = __webpack_require__(8);
  99597. var sceneManager_1 = __webpack_require__(26);
  99598. var templateManager_1 = __webpack_require__(33);
  99599. var loader_1 = __webpack_require__(36);
  99600. var babylonjs_1 = __webpack_require__(0);
  99601. var deepmerge = __webpack_require__(1);
  99602. var modelLoader_1 = __webpack_require__(19);
  99603. var globals_1 = __webpack_require__(7);
  99604. var telemetryManager_1 = __webpack_require__(5);
  99605. /**
  99606. * The AbstractViewr is the center of Babylon's viewer.
  99607. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  99608. */
  99609. var AbstractViewer = /** @class */ (function () {
  99610. function AbstractViewer(containerElement, initialConfiguration) {
  99611. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  99612. var _this = this;
  99613. this.containerElement = containerElement;
  99614. /**
  99615. * A flag that controls whether or not the render loop should be executed
  99616. */
  99617. this.runRenderLoop = true;
  99618. /**
  99619. * is this viewer disposed?
  99620. */
  99621. this._isDisposed = false;
  99622. /**
  99623. * The resize function that will be registered with the window object
  99624. */
  99625. this._resize = function () {
  99626. // Only resize if Canvas is in the DOM
  99627. if (!_this.isCanvasInDOM()) {
  99628. return;
  99629. }
  99630. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  99631. return;
  99632. }
  99633. if (_this._configuration.engine && _this._configuration.engine.disableResize) {
  99634. return;
  99635. }
  99636. _this.engine.resize();
  99637. };
  99638. /**
  99639. * render loop that will be executed by the engine
  99640. */
  99641. this._render = function (force) {
  99642. if (force === void 0) { force = false; }
  99643. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  99644. if (_this.runRenderLoop || force) {
  99645. _this.engine.performanceMonitor.enable();
  99646. _this.sceneManager.scene.render();
  99647. _this.onFrameRenderedObservable.notifyObservers(_this);
  99648. }
  99649. else {
  99650. _this.engine.performanceMonitor.disable();
  99651. // update camera instead of rendering
  99652. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  99653. }
  99654. }
  99655. };
  99656. // if exists, use the container id. otherwise, generate a random string.
  99657. if (containerElement.id) {
  99658. this.baseId = containerElement.id;
  99659. }
  99660. else {
  99661. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  99662. }
  99663. this.onSceneInitObservable = new babylonjs_1.Observable();
  99664. this.onEngineInitObservable = new babylonjs_1.Observable();
  99665. this.onModelLoadedObservable = new babylonjs_1.Observable();
  99666. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  99667. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  99668. this.onModelAddedObservable = new babylonjs_1.Observable();
  99669. this.onModelRemovedObservable = new babylonjs_1.Observable();
  99670. this.onInitDoneObservable = new babylonjs_1.Observable();
  99671. this.onLoaderInitObservable = new babylonjs_1.Observable();
  99672. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  99673. this._registeredOnBeforeRenderFunctions = [];
  99674. this.modelLoader = new modelLoader_1.ModelLoader(this);
  99675. // add this viewer to the viewer manager
  99676. viewerManager_1.viewerManager.addViewer(this);
  99677. // create a new template manager for this viewer
  99678. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  99679. this.sceneManager = new sceneManager_1.SceneManager(this);
  99680. this._prepareContainerElement();
  99681. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  99682. // extend the configuration
  99683. this._configurationLoader = new loader_1.ConfigurationLoader();
  99684. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  99685. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  99686. if (_this._configuration.observers) {
  99687. _this._configureObservers(_this._configuration.observers);
  99688. }
  99689. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  99690. if (_this._configuration.loaderPlugins) {
  99691. Object.keys(_this._configuration.loaderPlugins).forEach((function (name) {
  99692. if (_this._configuration.loaderPlugins && _this._configuration.loaderPlugins[name]) {
  99693. _this.modelLoader.addPlugin(name);
  99694. }
  99695. }));
  99696. }
  99697. // initialize the templates
  99698. var templateConfiguration = _this._configuration.templates || {};
  99699. _this.templateManager.initTemplate(templateConfiguration);
  99700. // when done, execute onTemplatesLoaded()
  99701. _this.templateManager.onAllLoaded.add(function () {
  99702. var canvas = _this.templateManager.getCanvas();
  99703. if (canvas) {
  99704. _this._canvas = canvas;
  99705. }
  99706. _this._onTemplateLoaded();
  99707. });
  99708. });
  99709. this.onModelLoadedObservable.add(function (model) {
  99710. //this.updateConfiguration(this._configuration, model);
  99711. });
  99712. this.onSceneInitObservable.add(function () {
  99713. _this.updateConfiguration();
  99714. });
  99715. this.onInitDoneObservable.add(function () {
  99716. _this._isInit = true;
  99717. //this.sceneManager.scene.executeWhenReady(() => {
  99718. _this.engine.runRenderLoop(_this._render);
  99719. //});
  99720. });
  99721. }
  99722. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  99723. /**
  99724. * The (single) canvas of this viewer
  99725. */
  99726. get: function () {
  99727. return this._canvas;
  99728. },
  99729. enumerable: true,
  99730. configurable: true
  99731. });
  99732. /**
  99733. * get the baseId of this viewer
  99734. */
  99735. AbstractViewer.prototype.getBaseId = function () {
  99736. return this.baseId;
  99737. };
  99738. /**
  99739. * Do we have a canvas to render on, and is it a part of the scene
  99740. */
  99741. AbstractViewer.prototype.isCanvasInDOM = function () {
  99742. return !!this._canvas && !!this._canvas.parentElement;
  99743. };
  99744. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  99745. /**
  99746. * Is the engine currently set to rende even when the page is in background
  99747. */
  99748. get: function () {
  99749. return this.engine.renderEvenInBackground;
  99750. },
  99751. /**
  99752. * Set the viewer's background rendering flag.
  99753. */
  99754. set: function (value) {
  99755. this.engine.renderEvenInBackground = value;
  99756. },
  99757. enumerable: true,
  99758. configurable: true
  99759. });
  99760. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  99761. /**
  99762. * Get the configuration object. This is a reference only.
  99763. * The configuration can ONLY be updated using the updateConfiguration function.
  99764. * changing this object will have no direct effect on the scene.
  99765. */
  99766. get: function () {
  99767. return this._configuration;
  99768. },
  99769. enumerable: true,
  99770. configurable: true
  99771. });
  99772. /**
  99773. * force resizing the engine.
  99774. */
  99775. AbstractViewer.prototype.forceResize = function () {
  99776. this._resize();
  99777. };
  99778. /**
  99779. * Force a single render loop execution.
  99780. */
  99781. AbstractViewer.prototype.forceRender = function () {
  99782. this._render(true);
  99783. };
  99784. /**
  99785. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  99786. * @param callback optional callback that will be triggered when screenshot is done.
  99787. * @param width Optional screenshot width (default to 512).
  99788. * @param height Optional screenshot height (default to 512).
  99789. * @returns a promise with the screenshot data
  99790. */
  99791. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  99792. var _this = this;
  99793. if (width === void 0) { width = 0; }
  99794. if (height === void 0) { height = 0; }
  99795. width = width || this.canvas.clientWidth;
  99796. height = height || this.canvas.clientHeight;
  99797. // Create the screenshot
  99798. return new Promise(function (resolve, reject) {
  99799. try {
  99800. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  99801. if (callback) {
  99802. callback(data);
  99803. }
  99804. resolve(data);
  99805. });
  99806. }
  99807. catch (e) {
  99808. reject(e);
  99809. }
  99810. });
  99811. };
  99812. /**
  99813. * Update the current viewer configuration with new values.
  99814. * Only provided information will be updated, old configuration values will be kept.
  99815. * If this.configuration was manually changed, you can trigger this function with no parameters,
  99816. * and the entire configuration will be updated.
  99817. * @param newConfiguration the partial configuration to update
  99818. *
  99819. */
  99820. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  99821. var _this = this;
  99822. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  99823. // update this.configuration with the new data
  99824. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  99825. this.sceneManager.updateConfiguration(newConfiguration, this._configuration);
  99826. // observers in configuration
  99827. if (newConfiguration.observers) {
  99828. this._configureObservers(newConfiguration.observers);
  99829. }
  99830. if (newConfiguration.loaderPlugins) {
  99831. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  99832. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  99833. _this.modelLoader.addPlugin(name);
  99834. }
  99835. }));
  99836. }
  99837. };
  99838. /**
  99839. * this is used to register native functions using the configuration object.
  99840. * This will configure the observers.
  99841. * @param observersConfiguration observers configuration
  99842. */
  99843. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  99844. if (observersConfiguration.onEngineInit) {
  99845. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  99846. }
  99847. else {
  99848. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  99849. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  99850. }
  99851. }
  99852. if (observersConfiguration.onSceneInit) {
  99853. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  99854. }
  99855. else {
  99856. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  99857. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  99858. }
  99859. }
  99860. if (observersConfiguration.onModelLoaded) {
  99861. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  99862. }
  99863. else {
  99864. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  99865. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  99866. }
  99867. }
  99868. };
  99869. /**
  99870. * Dispoe the entire viewer including the scene and the engine
  99871. */
  99872. AbstractViewer.prototype.dispose = function () {
  99873. if (this._isDisposed) {
  99874. return;
  99875. }
  99876. window.removeEventListener('resize', this._resize);
  99877. //observers
  99878. this.onEngineInitObservable.clear();
  99879. this.onInitDoneObservable.clear();
  99880. this.onLoaderInitObservable.clear();
  99881. this.onModelLoadedObservable.clear();
  99882. this.onModelLoadErrorObservable.clear();
  99883. this.onModelLoadProgressObservable.clear();
  99884. this.onSceneInitObservable.clear();
  99885. this.onFrameRenderedObservable.clear();
  99886. this.onModelAddedObservable.clear();
  99887. this.onModelRemovedObservable.clear();
  99888. if (this.sceneManager.scene.activeCamera) {
  99889. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  99890. }
  99891. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  99892. this.sceneManager.dispose();
  99893. this.modelLoader.dispose();
  99894. this.engine.dispose();
  99895. this.templateManager.dispose();
  99896. viewerManager_1.viewerManager.removeViewer(this);
  99897. this._isDisposed = true;
  99898. };
  99899. /**
  99900. * This function will execute when the HTML templates finished initializing.
  99901. * It should initialize the engine and continue execution.
  99902. *
  99903. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  99904. */
  99905. AbstractViewer.prototype._onTemplatesLoaded = function () {
  99906. return Promise.resolve(this);
  99907. };
  99908. /**
  99909. * This will force the creation of an engine and a scene.
  99910. * It will also load a model if preconfigured.
  99911. * But first - it will load the extendible onTemplateLoaded()!
  99912. */
  99913. AbstractViewer.prototype._onTemplateLoaded = function () {
  99914. var _this = this;
  99915. return this._onTemplatesLoaded().then(function () {
  99916. var autoLoad = typeof _this._configuration.model === 'string' || (_this._configuration.model && _this._configuration.model.url);
  99917. return _this._initEngine().then(function (engine) {
  99918. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  99919. }).then(function () {
  99920. _this._initTelemetryEvents();
  99921. if (autoLoad) {
  99922. return _this.loadModel(_this._configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  99923. }
  99924. else {
  99925. return _this.sceneManager.scene || _this.sceneManager.initScene(_this._configuration.scene);
  99926. }
  99927. }).then(function () {
  99928. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  99929. }).catch(function (e) {
  99930. babylonjs_1.Tools.Warn(e.toString());
  99931. return _this;
  99932. });
  99933. });
  99934. };
  99935. /**
  99936. * Initialize the engine. Retruns a promise in case async calls are needed.
  99937. *
  99938. * @protected
  99939. * @returns {Promise<Engine>}
  99940. * @memberof Viewer
  99941. */
  99942. AbstractViewer.prototype._initEngine = function () {
  99943. // init custom shaders
  99944. this._injectCustomShaders();
  99945. var canvasElement = this.templateManager.getCanvas();
  99946. if (!canvasElement) {
  99947. return Promise.reject('Canvas element not found!');
  99948. }
  99949. var config = this._configuration.engine || {};
  99950. // TDO enable further configuration
  99951. // check for webgl2 support, force-disable if needed.
  99952. if (globals_1.viewerGlobals.disableWebGL2Support) {
  99953. config.engineOptions = config.engineOptions || {};
  99954. config.engineOptions.disableWebGL2Support = true;
  99955. }
  99956. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  99957. // Disable manifest checking
  99958. babylonjs_1.Database.IDBStorageEnabled = false;
  99959. if (!config.disableResize) {
  99960. window.addEventListener('resize', this._resize);
  99961. }
  99962. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  99963. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  99964. this.engine.setHardwareScalingLevel(scale);
  99965. }
  99966. return Promise.resolve(this.engine);
  99967. };
  99968. /**
  99969. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  99970. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  99971. *
  99972. * @param modelConfig model configuration to use when loading the model.
  99973. * @param clearScene should the scene be cleared before loading this model
  99974. * @returns a ViewerModel object that is not yet fully loaded.
  99975. */
  99976. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  99977. var _this = this;
  99978. if (clearScene === void 0) { clearScene = true; }
  99979. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  99980. if (!modelUrl) {
  99981. throw new Error("no model url provided");
  99982. }
  99983. if (clearScene) {
  99984. }
  99985. var configuration;
  99986. if (typeof modelConfig === 'string') {
  99987. configuration = {
  99988. url: modelConfig
  99989. };
  99990. }
  99991. else {
  99992. configuration = modelConfig;
  99993. }
  99994. //merge the configuration for future models:
  99995. if (this._configuration.model && typeof this._configuration.model === 'object') {
  99996. deepmerge(this._configuration.model, configuration);
  99997. }
  99998. else {
  99999. this._configuration.model = configuration;
  100000. }
  100001. this._isLoading = true;
  100002. var model = this.modelLoader.load(configuration);
  100003. this.lastUsedLoader = model.loader;
  100004. model.onLoadErrorObservable.add(function (errorObject) {
  100005. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  100006. });
  100007. model.onLoadProgressObservable.add(function (progressEvent) {
  100008. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  100009. });
  100010. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  100011. model.onLoadedObservable.add(function () {
  100012. _this._isLoading = false;
  100013. });
  100014. return model;
  100015. };
  100016. /**
  100017. * load a model using the provided configuration.
  100018. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  100019. * If you want to attach to the observables of the model, use initModle instead.
  100020. *
  100021. * @param modelConfig the model configuration or URL to load.
  100022. * @param clearScene Should the scene be cleared before loading the model
  100023. * @returns a Promise the fulfills when the model finished loading successfully.
  100024. */
  100025. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  100026. var _this = this;
  100027. if (clearScene === void 0) { clearScene = true; }
  100028. if (this._isLoading) {
  100029. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  100030. return Promise.reject("another model is curently being loaded.");
  100031. }
  100032. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  100033. if (!scene)
  100034. return _this.sceneManager.initScene(_this._configuration.scene, _this._configuration.optimizer);
  100035. return scene;
  100036. }).then(function () {
  100037. var model = _this.initModel(modelConfig, clearScene);
  100038. return new Promise(function (resolve, reject) {
  100039. // at this point, configuration.model is an object, not a string
  100040. model.onLoadedObservable.add(function () {
  100041. resolve(model);
  100042. });
  100043. model.onLoadErrorObservable.add(function (error) {
  100044. reject(error);
  100045. });
  100046. });
  100047. });
  100048. };
  100049. AbstractViewer.prototype._initTelemetryEvents = function () {
  100050. var _this = this;
  100051. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this, this.engine.getCaps());
  100052. telemetryManager_1.telemetryManager.broadcast("Platform Details", this, {
  100053. userAgent: navigator.userAgent,
  100054. platform: navigator.platform
  100055. });
  100056. telemetryManager_1.telemetryManager.flushWebGLErrors(this);
  100057. var trackFPS = function () {
  100058. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this, { fps: _this.engine.getFps() });
  100059. };
  100060. trackFPS();
  100061. // Track the FPS again after 60 seconds
  100062. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  100063. };
  100064. /**
  100065. * Injects all the spectre shader in the babylon shader store
  100066. */
  100067. AbstractViewer.prototype._injectCustomShaders = function () {
  100068. var customShaders = this._configuration.customShaders;
  100069. // Inject all the spectre shader in the babylon shader store.
  100070. if (!customShaders) {
  100071. return;
  100072. }
  100073. if (customShaders.shaders) {
  100074. Object.keys(customShaders.shaders).forEach(function (key) {
  100075. // typescript considers a callback "unsafe", so... '!'
  100076. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  100077. });
  100078. }
  100079. if (customShaders.includes) {
  100080. Object.keys(customShaders.includes).forEach(function (key) {
  100081. // typescript considers a callback "unsafe", so... '!'
  100082. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  100083. });
  100084. }
  100085. };
  100086. return AbstractViewer;
  100087. }());
  100088. exports.AbstractViewer = AbstractViewer;
  100089. /***/ }),
  100090. /* 11 */
  100091. /***/ (function(module, exports, __webpack_require__) {
  100092. "use strict";
  100093. Object.defineProperty(exports, "__esModule", { value: true });
  100094. /**
  100095. * WebGL Pixel Formats
  100096. */
  100097. var PixelFormat;
  100098. (function (PixelFormat) {
  100099. PixelFormat[PixelFormat["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
  100100. PixelFormat[PixelFormat["ALPHA"] = 6406] = "ALPHA";
  100101. PixelFormat[PixelFormat["RGB"] = 6407] = "RGB";
  100102. PixelFormat[PixelFormat["RGBA"] = 6408] = "RGBA";
  100103. PixelFormat[PixelFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  100104. PixelFormat[PixelFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  100105. })(PixelFormat = exports.PixelFormat || (exports.PixelFormat = {}));
  100106. /**
  100107. * WebGL Pixel Types
  100108. */
  100109. var PixelType;
  100110. (function (PixelType) {
  100111. PixelType[PixelType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  100112. PixelType[PixelType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  100113. PixelType[PixelType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  100114. PixelType[PixelType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  100115. })(PixelType = exports.PixelType || (exports.PixelType = {}));
  100116. /**
  100117. * WebGL Texture Magnification Filter
  100118. */
  100119. var TextureMagFilter;
  100120. (function (TextureMagFilter) {
  100121. TextureMagFilter[TextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  100122. TextureMagFilter[TextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  100123. })(TextureMagFilter = exports.TextureMagFilter || (exports.TextureMagFilter = {}));
  100124. /**
  100125. * WebGL Texture Minification Filter
  100126. */
  100127. var TextureMinFilter;
  100128. (function (TextureMinFilter) {
  100129. TextureMinFilter[TextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  100130. TextureMinFilter[TextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  100131. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  100132. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  100133. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  100134. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  100135. })(TextureMinFilter = exports.TextureMinFilter || (exports.TextureMinFilter = {}));
  100136. /**
  100137. * WebGL Texture Wrap Modes
  100138. */
  100139. var TextureWrapMode;
  100140. (function (TextureWrapMode) {
  100141. TextureWrapMode[TextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  100142. TextureWrapMode[TextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  100143. TextureWrapMode[TextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  100144. })(TextureWrapMode = exports.TextureWrapMode || (exports.TextureWrapMode = {}));
  100145. /**
  100146. * A minimal WebGL cubemap descriptor
  100147. */
  100148. var TextureCube = /** @class */ (function () {
  100149. /**
  100150. * constructor
  100151. * @param internalFormat WebGL pixel format for the texture on the GPU
  100152. * @param type WebGL pixel type of the supplied data and texture on the GPU
  100153. * @param source An array containing mipmap levels of faces, where each mipmap level is an array of faces and each face is a TextureSource object
  100154. */
  100155. function TextureCube(internalFormat, type, source) {
  100156. if (source === void 0) { source = []; }
  100157. this.internalFormat = internalFormat;
  100158. this.type = type;
  100159. this.source = source;
  100160. }
  100161. Object.defineProperty(TextureCube.prototype, "Width", {
  100162. /**
  100163. * Returns the width of a face of the texture or 0 if not available
  100164. */
  100165. get: function () {
  100166. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  100167. },
  100168. enumerable: true,
  100169. configurable: true
  100170. });
  100171. Object.defineProperty(TextureCube.prototype, "Height", {
  100172. /**
  100173. * Returns the height of a face of the texture or 0 if not available
  100174. */
  100175. get: function () {
  100176. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  100177. },
  100178. enumerable: true,
  100179. configurable: true
  100180. });
  100181. return TextureCube;
  100182. }());
  100183. exports.TextureCube = TextureCube;
  100184. /**
  100185. * A static class providing methods to aid working with Bablyon textures.
  100186. */
  100187. var TextureUtils = /** @class */ (function () {
  100188. function TextureUtils() {
  100189. }
  100190. /**
  100191. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  100192. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  100193. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  100194. * @param scene A Babylon Scene instance
  100195. * @param textureCube A Spectre TextureCube object
  100196. * @param parameters WebGL texture sampling parameters
  100197. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  100198. * @param environment Specifies that the texture will be used as an environment
  100199. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  100200. * @return Babylon cube texture
  100201. */
  100202. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  100203. if (environment === void 0) { environment = false; }
  100204. if (singleLod === void 0) { singleLod = false; }
  100205. if (!textureCube)
  100206. throw new Error("no texture cube provided");
  100207. var parameters;
  100208. if (environment) {
  100209. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  100210. }
  100211. else {
  100212. parameters = {
  100213. magFilter: 9728 /* NEAREST */,
  100214. minFilter: 9728 /* NEAREST */,
  100215. wrapS: 33071 /* CLAMP_TO_EDGE */,
  100216. wrapT: 33071 /* CLAMP_TO_EDGE */
  100217. };
  100218. }
  100219. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  100220. var babylonTexture = textureCube[key];
  100221. if (!babylonTexture) {
  100222. //initialize babylon texture
  100223. babylonTexture = new BABYLON.CubeTexture('', scene);
  100224. if (environment) {
  100225. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  100226. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  100227. }
  100228. babylonTexture.gammaSpace = false;
  100229. var internalTexture_1 = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  100230. var glTexture_1 = internalTexture_1._webGLTexture;
  100231. //babylon properties
  100232. internalTexture_1.isCube = true;
  100233. internalTexture_1.generateMipMaps = false;
  100234. babylonTexture._texture = internalTexture_1;
  100235. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  100236. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  100237. var texturesUploaded_1 = 0;
  100238. var textureComplete = function () {
  100239. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  100240. };
  100241. var uploadFace = function (i, level, face) {
  100242. if (!glTexture_1)
  100243. return;
  100244. if (i === 0 && level === 0) {
  100245. internalTexture_1.width = face.width;
  100246. internalTexture_1.height = face.height;
  100247. }
  100248. var gl = (scene.getEngine())._gl;
  100249. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  100250. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  100251. if (face instanceof HTMLElement || face instanceof ImageData) {
  100252. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  100253. }
  100254. else {
  100255. var textureData = face;
  100256. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  100257. }
  100258. texturesUploaded_1++;
  100259. if (textureComplete()) {
  100260. //generate mipmaps
  100261. if (automaticMipmaps) {
  100262. var w = face.width;
  100263. var h = face.height;
  100264. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  100265. if (isPot) {
  100266. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  100267. }
  100268. }
  100269. // Upload Separate lods in case there is no support for texture lod.
  100270. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  100271. var mipSlices = 3;
  100272. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  100273. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  100274. var lod = textureCube[lodKey];
  100275. //initialize lod texture if it doesn't already exist
  100276. if (lod == null && textureCube.Width) {
  100277. //compute LOD from even spacing in smoothness (matching shader calculation)
  100278. var smoothness = i_1 / (mipSlices - 1);
  100279. var roughness = 1 - smoothness;
  100280. var kMinimumVariance = 0.0005;
  100281. var alphaG = roughness * roughness + kMinimumVariance;
  100282. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  100283. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (BABYLON.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  100284. var maxLODIndex = textureCube.source.length - 1;
  100285. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  100286. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  100287. if (i_1 === 0) {
  100288. internalTexture_1._lodTextureLow = lod;
  100289. }
  100290. else if (i_1 === 1) {
  100291. internalTexture_1._lodTextureMid = lod;
  100292. }
  100293. else {
  100294. internalTexture_1._lodTextureHigh = lod;
  100295. }
  100296. textureCube[lodKey] = lod;
  100297. }
  100298. }
  100299. }
  100300. internalTexture_1.isReady = true;
  100301. }
  100302. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  100303. scene.getEngine().resetTextureCache();
  100304. };
  100305. var _loop_1 = function (i) {
  100306. var faces = textureCube.source[i];
  100307. var _loop_2 = function (j) {
  100308. var face = faces[j];
  100309. if (face instanceof HTMLImageElement && !face.complete) {
  100310. face.addEventListener('load', function () {
  100311. uploadFace(j, i, face);
  100312. }, false);
  100313. }
  100314. else {
  100315. uploadFace(j, i, face);
  100316. }
  100317. };
  100318. for (var j = 0; j < faces.length; j++) {
  100319. _loop_2(j);
  100320. }
  100321. };
  100322. for (var i = 0; i <= maxMipLevel_1; i++) {
  100323. _loop_1(i);
  100324. }
  100325. scene.getEngine().resetTextureCache();
  100326. babylonTexture.isReady = function () {
  100327. return textureComplete();
  100328. };
  100329. textureCube[key] = babylonTexture;
  100330. }
  100331. return babylonTexture;
  100332. };
  100333. /**
  100334. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  100335. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  100336. * @param parameters Spectre SamplingParameters to apply
  100337. */
  100338. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  100339. var scene = babylonTexture.getScene();
  100340. if (!scene)
  100341. return;
  100342. var gl = (scene.getEngine())._gl;
  100343. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  100344. var internalTexture = babylonTexture._texture;
  100345. if (!internalTexture)
  100346. return;
  100347. var glTexture = internalTexture._webGLTexture;
  100348. gl.bindTexture(target, glTexture);
  100349. if (parameters.magFilter != null)
  100350. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  100351. if (parameters.minFilter != null)
  100352. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  100353. if (parameters.wrapS != null)
  100354. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  100355. if (parameters.wrapT != null)
  100356. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  100357. //set babylon wrap modes from sampling parameter
  100358. switch (parameters.wrapS) {
  100359. case 10497 /* REPEAT */:
  100360. babylonTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  100361. break;
  100362. case 33071 /* CLAMP_TO_EDGE */:
  100363. babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100364. break;
  100365. case 33648 /* MIRRORED_REPEAT */:
  100366. babylonTexture.wrapU = BABYLON.Texture.MIRROR_ADDRESSMODE;
  100367. break;
  100368. default: babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100369. }
  100370. switch (parameters.wrapT) {
  100371. case 10497 /* REPEAT */:
  100372. babylonTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  100373. break;
  100374. case 33071 /* CLAMP_TO_EDGE */:
  100375. babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100376. break;
  100377. case 33648 /* MIRRORED_REPEAT */:
  100378. babylonTexture.wrapV = BABYLON.Texture.MIRROR_ADDRESSMODE;
  100379. break;
  100380. default: babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100381. }
  100382. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  100383. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  100384. if (anisotropicExt) {
  100385. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  100386. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  100387. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  100388. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  100389. }
  100390. }
  100391. gl.bindTexture(target, null);
  100392. scene.getEngine().resetTextureCache();
  100393. };
  100394. /**
  100395. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  100396. */
  100397. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  100398. /**
  100399. * Controls anisotropic filtering for deserialized textures.
  100400. */
  100401. TextureUtils.MaxAnisotropy = 4;
  100402. TextureUtils._EnvironmentSampling = {
  100403. magFilter: 9729 /* LINEAR */,
  100404. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  100405. wrapS: 33071 /* CLAMP_TO_EDGE */,
  100406. wrapT: 33071 /* CLAMP_TO_EDGE */,
  100407. maxAnisotropy: 1
  100408. };
  100409. TextureUtils._EnvironmentSingleMipSampling = {
  100410. magFilter: 9729 /* LINEAR */,
  100411. minFilter: 9729 /* LINEAR */,
  100412. wrapS: 33071 /* CLAMP_TO_EDGE */,
  100413. wrapT: 33071 /* CLAMP_TO_EDGE */,
  100414. maxAnisotropy: 1
  100415. };
  100416. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  100417. /**
  100418. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  100419. */
  100420. TextureUtils.EnvironmentLODScale = 0.8;
  100421. /**
  100422. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  100423. */
  100424. TextureUtils.EnvironmentLODOffset = 1.0;
  100425. return TextureUtils;
  100426. }());
  100427. exports.TextureUtils = TextureUtils;
  100428. /***/ }),
  100429. /* 12 */
  100430. /***/ (function(module, exports) {
  100431. module.exports = "<style>@font-face{font-family:babylon;src:url({{babylonFont}}) format('woff');font-weight:400;font-style:normal}.icon{font-family:babylon}</style> {{#if fillScreen}} <style>body,html{width:100%;height:100%;margin:0;padding:0}</style> {{/if}} <fill-container></fill-container>";
  100432. /***/ }),
  100433. /* 13 */
  100434. /***/ (function(module, exports) {
  100435. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  100436. /***/ }),
  100437. /* 14 */
  100438. /***/ (function(module, exports) {
  100439. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  100440. /***/ }),
  100441. /* 15 */
  100442. /***/ (function(module, exports) {
  100443. module.exports = "<style>viewer{position:relative;overflow:hidden;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas touch-action=none> </canvas> <nav-bar></nav-bar>";
  100444. /***/ }),
  100445. /* 16 */
  100446. /***/ (function(module, exports) {
  100447. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}.overlay-item{width:100%;height:100%;display:none;align-items:center;justify-content:center;background-color:rgba(121,121,121,.3)}error.overlay-item{background-color:rgba(121,121,121,1)}div#close-button{position:absolute;top:10px;right:10px;width:30px;height:30px;cursor:pointer}div#close-button img{width:100%}</style> <div id=close-button> <img src={{closeImage}} alt={{closeText}}> </div> <help class=overlay-item></help> <error class=overlay-item></error> <share class=overlay-item></share>";
  100448. /***/ }),
  100449. /* 17 */
  100450. /***/ (function(module, exports) {
  100451. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  100452. /***/ }),
  100453. /* 18 */
  100454. /***/ (function(module, exports) {
  100455. module.exports = "Error loading the model";
  100456. /***/ }),
  100457. /* 19 */
  100458. /***/ (function(module, exports, __webpack_require__) {
  100459. "use strict";
  100460. Object.defineProperty(exports, "__esModule", { value: true });
  100461. var babylonjs_1 = __webpack_require__(0);
  100462. var babylonjs_loaders_1 = __webpack_require__(20);
  100463. var viewerModel_1 = __webpack_require__(4);
  100464. var _1 = __webpack_require__(49);
  100465. /**
  100466. * An instance of the class is in charge of loading the model correctly.
  100467. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  100468. *
  100469. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  100470. */
  100471. var ModelLoader = /** @class */ (function () {
  100472. /**
  100473. * Create a new Model loader
  100474. * @param _viewer the viewer using this model loader
  100475. */
  100476. function ModelLoader(_viewer) {
  100477. this._viewer = _viewer;
  100478. this._disposed = false;
  100479. this._loaders = [];
  100480. this._loadId = 0;
  100481. this._plugins = [];
  100482. }
  100483. /**
  100484. * Adds a new plugin to the loader process.
  100485. *
  100486. * @param plugin the plugin name or the plugin itself
  100487. */
  100488. ModelLoader.prototype.addPlugin = function (plugin) {
  100489. var actualPlugin = {};
  100490. if (typeof plugin === 'string') {
  100491. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  100492. if (loadedPlugin) {
  100493. actualPlugin = loadedPlugin;
  100494. }
  100495. }
  100496. else {
  100497. actualPlugin = plugin;
  100498. }
  100499. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  100500. this._plugins.push(actualPlugin);
  100501. }
  100502. };
  100503. /**
  100504. * Load a model using predefined configuration
  100505. * @param modelConfiguration the modelConfiguration to use to load the model
  100506. */
  100507. ModelLoader.prototype.load = function (modelConfiguration) {
  100508. var _this = this;
  100509. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  100510. model.loadId = this._loadId++;
  100511. if (!modelConfiguration.url) {
  100512. model.state = viewerModel_1.ModelState.ERROR;
  100513. babylonjs_1.Tools.Error("No URL provided");
  100514. return model;
  100515. }
  100516. var base;
  100517. var filename;
  100518. if (modelConfiguration.file) {
  100519. base = "file:";
  100520. filename = modelConfiguration.file;
  100521. }
  100522. else {
  100523. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  100524. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  100525. }
  100526. var plugin = modelConfiguration.loader;
  100527. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.sceneManager.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  100528. meshes.forEach(function (mesh) {
  100529. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  100530. model.addMesh(mesh);
  100531. });
  100532. model.particleSystems = particleSystems;
  100533. model.skeletons = skeletons;
  100534. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  100535. var animationGroup = animationGroups_1[_i];
  100536. model.addAnimationGroup(animationGroup);
  100537. }
  100538. _this._checkAndRun("onLoaded", model);
  100539. _this._viewer.sceneManager.scene.executeWhenReady(function () {
  100540. model.onLoadedObservable.notifyObservers(model);
  100541. });
  100542. }, function (progressEvent) {
  100543. _this._checkAndRun("onProgress", progressEvent);
  100544. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  100545. }, function (scene, m, exception) {
  100546. model.state = viewerModel_1.ModelState.ERROR;
  100547. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  100548. _this._checkAndRun("onError", m, exception);
  100549. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  100550. }, plugin);
  100551. if (model.loader.name === "gltf") {
  100552. var gltfLoader_1 = model.loader;
  100553. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  100554. gltfLoader_1.compileMaterials = true;
  100555. if (!modelConfiguration.file) {
  100556. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  100557. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  100558. };
  100559. }
  100560. // if ground is set to "mirror":
  100561. if (this._viewer.configuration.ground && typeof this._viewer.configuration.ground === 'object' && this._viewer.configuration.ground.mirror) {
  100562. gltfLoader_1.useClipPlane = true;
  100563. }
  100564. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  100565. gltfLoader_1[functionName].add(function (payload) {
  100566. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  100567. });
  100568. });
  100569. gltfLoader_1.onParsedObservable.add(function (data) {
  100570. if (data && data.json && data.json['asset']) {
  100571. model.loadInfo = data.json['asset'];
  100572. }
  100573. });
  100574. gltfLoader_1.onCompleteObservable.add(function () {
  100575. model.loaderDone = true;
  100576. });
  100577. }
  100578. else {
  100579. model.loaderDone = true;
  100580. }
  100581. this._checkAndRun("onInit", model.loader, model);
  100582. this._loaders.push(model.loader);
  100583. return model;
  100584. };
  100585. ModelLoader.prototype.cancelLoad = function (model) {
  100586. var loader = model.loader || this._loaders[model.loadId];
  100587. // ATM only available in the GLTF Loader
  100588. if (loader && loader.name === "gltf") {
  100589. var gltfLoader = loader;
  100590. gltfLoader.dispose();
  100591. model.state = viewerModel_1.ModelState.CANCELED;
  100592. }
  100593. else {
  100594. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  100595. }
  100596. };
  100597. /**
  100598. * dispose the model loader.
  100599. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  100600. */
  100601. ModelLoader.prototype.dispose = function () {
  100602. this._loaders.forEach(function (loader) {
  100603. if (loader.name === "gltf") {
  100604. loader.dispose();
  100605. }
  100606. });
  100607. this._loaders.length = 0;
  100608. this._disposed = true;
  100609. };
  100610. ModelLoader.prototype._checkAndRun = function (functionName) {
  100611. var _this = this;
  100612. var payload = [];
  100613. for (var _i = 1; _i < arguments.length; _i++) {
  100614. payload[_i - 1] = arguments[_i];
  100615. }
  100616. if (this._disposed)
  100617. return;
  100618. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  100619. try {
  100620. plugin[functionName].apply(_this, payload);
  100621. }
  100622. catch (e) { }
  100623. });
  100624. };
  100625. return ModelLoader;
  100626. }());
  100627. exports.ModelLoader = ModelLoader;
  100628. /***/ }),
  100629. /* 20 */
  100630. /***/ (function(module, exports, __webpack_require__) {
  100631. (function universalModuleDefinition(root, factory) {
  100632. var amdDependencies = [];
  100633. var BABYLON = root.BABYLON || this.BABYLON;
  100634. if(true) {
  100635. BABYLON = BABYLON || __webpack_require__(0);
  100636. module.exports = factory(BABYLON);
  100637. } else if(typeof define === 'function' && define.amd) {
  100638. amdDependencies.push("babylonjs");
  100639. define("babylonjs-loaders", amdDependencies, factory);
  100640. } else if(typeof exports === 'object') {
  100641. BABYLON = BABYLON || require("babylonjs");
  100642. exports["babylonjs-loaders"] = factory(BABYLON);
  100643. } else {
  100644. root["BABYLON"] = factory(BABYLON);
  100645. }
  100646. })(this, function(BABYLON) {
  100647. BABYLON = BABYLON || this.BABYLON;
  100648. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  100649. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  100650. var BABYLON;
  100651. (function (BABYLON) {
  100652. var STLFileLoader = /** @class */ (function () {
  100653. function STLFileLoader() {
  100654. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  100655. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  100656. this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  100657. this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  100658. this.name = "stl";
  100659. // force data to come in as an ArrayBuffer
  100660. // we'll convert to string if it looks like it's an ASCII .stl
  100661. this.extensions = {
  100662. ".stl": { isBinary: true },
  100663. };
  100664. }
  100665. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  100666. var matches;
  100667. if (this.isBinary(data)) {
  100668. // binary .stl
  100669. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  100670. this.parseBinary(babylonMesh, data);
  100671. if (meshes) {
  100672. meshes.push(babylonMesh);
  100673. }
  100674. return true;
  100675. }
  100676. // ASCII .stl
  100677. // convert to string
  100678. var array_buffer = new Uint8Array(data);
  100679. var str = '';
  100680. for (var i = 0; i < data.byteLength; i++) {
  100681. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  100682. }
  100683. data = str;
  100684. while (matches = this.solidPattern.exec(data)) {
  100685. var meshName = matches[1];
  100686. var meshNameFromEnd = matches[3];
  100687. if (meshName != meshNameFromEnd) {
  100688. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  100689. return false;
  100690. }
  100691. // check meshesNames
  100692. if (meshesNames && meshName) {
  100693. if (meshesNames instanceof Array) {
  100694. if (!meshesNames.indexOf(meshName)) {
  100695. continue;
  100696. }
  100697. }
  100698. else {
  100699. if (meshName !== meshesNames) {
  100700. continue;
  100701. }
  100702. }
  100703. }
  100704. // stl mesh name can be empty as well
  100705. meshName = meshName || "stlmesh";
  100706. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  100707. this.parseASCII(babylonMesh, matches[2]);
  100708. if (meshes) {
  100709. meshes.push(babylonMesh);
  100710. }
  100711. }
  100712. return true;
  100713. };
  100714. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  100715. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  100716. if (result) {
  100717. scene.createDefaultCameraOrLight();
  100718. }
  100719. return result;
  100720. };
  100721. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100722. var container = new BABYLON.AssetContainer(scene);
  100723. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100724. container.removeAllFromScene();
  100725. return container;
  100726. };
  100727. STLFileLoader.prototype.isBinary = function (data) {
  100728. // check if file size is correct for binary stl
  100729. var faceSize, nFaces, reader;
  100730. reader = new DataView(data);
  100731. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  100732. nFaces = reader.getUint32(80, true);
  100733. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  100734. return true;
  100735. }
  100736. // check characters higher than ASCII to confirm binary
  100737. var fileLength = reader.byteLength;
  100738. for (var index = 0; index < fileLength; index++) {
  100739. if (reader.getUint8(index) > 127) {
  100740. return true;
  100741. }
  100742. }
  100743. return false;
  100744. };
  100745. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  100746. var reader = new DataView(data);
  100747. var faces = reader.getUint32(80, true);
  100748. var dataOffset = 84;
  100749. var faceLength = 12 * 4 + 2;
  100750. var offset = 0;
  100751. var positions = new Float32Array(faces * 3 * 3);
  100752. var normals = new Float32Array(faces * 3 * 3);
  100753. var indices = new Uint32Array(faces * 3);
  100754. var indicesCount = 0;
  100755. for (var face = 0; face < faces; face++) {
  100756. var start = dataOffset + face * faceLength;
  100757. var normalX = reader.getFloat32(start, true);
  100758. var normalY = reader.getFloat32(start + 4, true);
  100759. var normalZ = reader.getFloat32(start + 8, true);
  100760. for (var i = 1; i <= 3; i++) {
  100761. var vertexstart = start + i * 12;
  100762. // ordering is intentional to match ascii import
  100763. positions[offset] = reader.getFloat32(vertexstart, true);
  100764. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  100765. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  100766. normals[offset] = normalX;
  100767. normals[offset + 2] = normalY;
  100768. normals[offset + 1] = normalZ;
  100769. offset += 3;
  100770. }
  100771. indices[indicesCount] = indicesCount++;
  100772. indices[indicesCount] = indicesCount++;
  100773. indices[indicesCount] = indicesCount++;
  100774. }
  100775. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100776. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100777. mesh.setIndices(indices);
  100778. mesh.computeWorldMatrix(true);
  100779. };
  100780. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  100781. var positions = [];
  100782. var normals = [];
  100783. var indices = [];
  100784. var indicesCount = 0;
  100785. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  100786. var matches;
  100787. while (matches = this.facetsPattern.exec(solidData)) {
  100788. var facet = matches[1];
  100789. //one normal per face
  100790. var normalMatches = this.normalPattern.exec(facet);
  100791. this.normalPattern.lastIndex = 0;
  100792. if (!normalMatches) {
  100793. continue;
  100794. }
  100795. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  100796. var vertexMatch;
  100797. while (vertexMatch = this.vertexPattern.exec(facet)) {
  100798. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  100799. normals.push(normal[0], normal[1], normal[2]);
  100800. }
  100801. indices.push(indicesCount++, indicesCount++, indicesCount++);
  100802. this.vertexPattern.lastIndex = 0;
  100803. }
  100804. this.facetsPattern.lastIndex = 0;
  100805. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100806. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100807. mesh.setIndices(indices);
  100808. mesh.computeWorldMatrix(true);
  100809. };
  100810. return STLFileLoader;
  100811. }());
  100812. BABYLON.STLFileLoader = STLFileLoader;
  100813. if (BABYLON.SceneLoader) {
  100814. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  100815. }
  100816. })(BABYLON || (BABYLON = {}));
  100817. //# sourceMappingURL=babylon.stlFileLoader.js.map
  100818. var BABYLON;
  100819. (function (BABYLON) {
  100820. /**
  100821. * Class reading and parsing the MTL file bundled with the obj file.
  100822. */
  100823. var MTLFileLoader = /** @class */ (function () {
  100824. function MTLFileLoader() {
  100825. // All material loaded from the mtl will be set here
  100826. this.materials = [];
  100827. }
  100828. /**
  100829. * This function will read the mtl file and create each material described inside
  100830. * This function could be improve by adding :
  100831. * -some component missing (Ni, Tf...)
  100832. * -including the specific options available
  100833. *
  100834. * @param scene
  100835. * @param data
  100836. * @param rootUrl
  100837. */
  100838. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  100839. if (data instanceof ArrayBuffer) {
  100840. return;
  100841. }
  100842. //Split the lines from the file
  100843. var lines = data.split('\n');
  100844. //Space char
  100845. var delimiter_pattern = /\s+/;
  100846. //Array with RGB colors
  100847. var color;
  100848. //New material
  100849. var material = null;
  100850. //Look at each line
  100851. for (var i = 0; i < lines.length; i++) {
  100852. var line = lines[i].trim();
  100853. // Blank line or comment
  100854. if (line.length === 0 || line.charAt(0) === '#') {
  100855. continue;
  100856. }
  100857. //Get the first parameter (keyword)
  100858. var pos = line.indexOf(' ');
  100859. var key = (pos >= 0) ? line.substring(0, pos) : line;
  100860. key = key.toLowerCase();
  100861. //Get the data following the key
  100862. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  100863. //This mtl keyword will create the new material
  100864. if (key === "newmtl") {
  100865. //Check if it is the first material.
  100866. // Materials specifications are described after this keyword.
  100867. if (material) {
  100868. //Add the previous material in the material array.
  100869. this.materials.push(material);
  100870. }
  100871. //Create a new material.
  100872. // value is the name of the material read in the mtl file
  100873. material = new BABYLON.StandardMaterial(value, scene);
  100874. }
  100875. else if (key === "kd" && material) {
  100876. // Diffuse color (color under white light) using RGB values
  100877. //value = "r g b"
  100878. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100879. //color = [r,g,b]
  100880. //Set tghe color into the material
  100881. material.diffuseColor = BABYLON.Color3.FromArray(color);
  100882. }
  100883. else if (key === "ka" && material) {
  100884. // Ambient color (color under shadow) using RGB values
  100885. //value = "r g b"
  100886. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100887. //color = [r,g,b]
  100888. //Set tghe color into the material
  100889. material.ambientColor = BABYLON.Color3.FromArray(color);
  100890. }
  100891. else if (key === "ks" && material) {
  100892. // Specular color (color when light is reflected from shiny surface) using RGB values
  100893. //value = "r g b"
  100894. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100895. //color = [r,g,b]
  100896. //Set the color into the material
  100897. material.specularColor = BABYLON.Color3.FromArray(color);
  100898. }
  100899. else if (key === "ke" && material) {
  100900. // Emissive color using RGB values
  100901. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100902. material.emissiveColor = BABYLON.Color3.FromArray(color);
  100903. }
  100904. else if (key === "ns" && material) {
  100905. //value = "Integer"
  100906. material.specularPower = parseFloat(value);
  100907. }
  100908. else if (key === "d" && material) {
  100909. //d is dissolve for current material. It mean alpha for BABYLON
  100910. material.alpha = parseFloat(value);
  100911. //Texture
  100912. //This part can be improved by adding the possible options of texture
  100913. }
  100914. else if (key === "map_ka" && material) {
  100915. // ambient texture map with a loaded image
  100916. //We must first get the folder of the image
  100917. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100918. }
  100919. else if (key === "map_kd" && material) {
  100920. // Diffuse texture map with a loaded image
  100921. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100922. }
  100923. else if (key === "map_ks" && material) {
  100924. // Specular texture map with a loaded image
  100925. //We must first get the folder of the image
  100926. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100927. }
  100928. else if (key === "map_ns") {
  100929. //Specular
  100930. //Specular highlight component
  100931. //We must first get the folder of the image
  100932. //
  100933. //Not supported by BABYLON
  100934. //
  100935. // continue;
  100936. }
  100937. else if (key === "map_bump" && material) {
  100938. //The bump texture
  100939. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100940. }
  100941. else if (key === "map_d" && material) {
  100942. // The dissolve of the material
  100943. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100944. //Options for illumination
  100945. }
  100946. else if (key === "illum") {
  100947. //Illumination
  100948. if (value === "0") {
  100949. //That mean Kd == Kd
  100950. }
  100951. else if (value === "1") {
  100952. //Color on and Ambient on
  100953. }
  100954. else if (value === "2") {
  100955. //Highlight on
  100956. }
  100957. else if (value === "3") {
  100958. //Reflection on and Ray trace on
  100959. }
  100960. else if (value === "4") {
  100961. //Transparency: Glass on, Reflection: Ray trace on
  100962. }
  100963. else if (value === "5") {
  100964. //Reflection: Fresnel on and Ray trace on
  100965. }
  100966. else if (value === "6") {
  100967. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  100968. }
  100969. else if (value === "7") {
  100970. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  100971. }
  100972. else if (value === "8") {
  100973. //Reflection on and Ray trace off
  100974. }
  100975. else if (value === "9") {
  100976. //Transparency: Glass on, Reflection: Ray trace off
  100977. }
  100978. else if (value === "10") {
  100979. //Casts shadows onto invisible surfaces
  100980. }
  100981. }
  100982. else {
  100983. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  100984. }
  100985. }
  100986. //At the end of the file, add the last material
  100987. if (material) {
  100988. this.materials.push(material);
  100989. }
  100990. };
  100991. /**
  100992. * Gets the texture for the material.
  100993. *
  100994. * If the material is imported from input file,
  100995. * We sanitize the url to ensure it takes the textre from aside the material.
  100996. *
  100997. * @param rootUrl The root url to load from
  100998. * @param value The value stored in the mtl
  100999. * @return The Texture
  101000. */
  101001. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  101002. if (!value) {
  101003. return null;
  101004. }
  101005. var url = rootUrl;
  101006. // Load from input file.
  101007. if (rootUrl === "file:") {
  101008. var lastDelimiter = value.lastIndexOf("\\");
  101009. if (lastDelimiter === -1) {
  101010. lastDelimiter = value.lastIndexOf("/");
  101011. }
  101012. if (lastDelimiter > -1) {
  101013. url += value.substr(lastDelimiter + 1);
  101014. }
  101015. else {
  101016. url += value;
  101017. }
  101018. }
  101019. // Not from input file.
  101020. else {
  101021. url += value;
  101022. }
  101023. return new BABYLON.Texture(url, scene);
  101024. };
  101025. return MTLFileLoader;
  101026. }());
  101027. BABYLON.MTLFileLoader = MTLFileLoader;
  101028. var OBJFileLoader = /** @class */ (function () {
  101029. function OBJFileLoader() {
  101030. this.name = "obj";
  101031. this.extensions = ".obj";
  101032. this.obj = /^o/;
  101033. this.group = /^g/;
  101034. this.mtllib = /^mtllib /;
  101035. this.usemtl = /^usemtl /;
  101036. this.smooth = /^s /;
  101037. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  101038. // vn float float float
  101039. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  101040. // vt float float
  101041. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  101042. // f vertex vertex vertex ...
  101043. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  101044. // f vertex/uvs vertex/uvs vertex/uvs ...
  101045. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  101046. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  101047. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  101048. // f vertex//normal vertex//normal vertex//normal ...
  101049. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  101050. }
  101051. /**
  101052. * Calls synchronously the MTL file attached to this obj.
  101053. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  101054. * Without this function materials are not displayed in the first frame (but displayed after).
  101055. * In consequence it is impossible to get material information in your HTML file
  101056. *
  101057. * @param url The URL of the MTL file
  101058. * @param rootUrl
  101059. * @param onSuccess Callback function to be called when the MTL file is loaded
  101060. * @private
  101061. */
  101062. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  101063. //The complete path to the mtl file
  101064. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  101065. // Loads through the babylon tools to allow fileInput search.
  101066. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  101067. };
  101068. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  101069. //get the meshes from OBJ file
  101070. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  101071. //Push meshes from OBJ file into the variable mesh of this function
  101072. if (meshes) {
  101073. loadedMeshes.forEach(function (mesh) {
  101074. meshes.push(mesh);
  101075. });
  101076. }
  101077. return true;
  101078. };
  101079. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  101080. //Get the 3D model
  101081. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  101082. };
  101083. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  101084. var container = new BABYLON.AssetContainer(scene);
  101085. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  101086. container.removeAllFromScene();
  101087. return container;
  101088. };
  101089. /**
  101090. * Read the OBJ file and create an Array of meshes.
  101091. * Each mesh contains all information given by the OBJ and the MTL file.
  101092. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  101093. *
  101094. * @param meshesNames
  101095. * @param scene BABYLON.Scene The scene where are displayed the data
  101096. * @param data String The content of the obj file
  101097. * @param rootUrl String The path to the folder
  101098. * @returns Array<AbstractMesh>
  101099. * @private
  101100. */
  101101. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  101102. var positions = []; //values for the positions of vertices
  101103. var normals = []; //Values for the normals
  101104. var uvs = []; //Values for the textures
  101105. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  101106. var handledMesh; //The current mesh of meshes array
  101107. var indicesForBabylon = []; //The list of indices for VertexData
  101108. var wrappedPositionForBabylon = []; //The list of position in vectors
  101109. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  101110. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  101111. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  101112. var curPositionInIndices = 0;
  101113. var hasMeshes = false; //Meshes are defined in the file
  101114. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  101115. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  101116. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  101117. var triangles = []; //Indices from new triangles coming from polygons
  101118. var materialNameFromObj = ""; //The name of the current material
  101119. var fileToLoad = ""; //The name of the mtlFile to load
  101120. var materialsFromMTLFile = new MTLFileLoader();
  101121. var objMeshName = ""; //The name of the current obj mesh
  101122. var increment = 1; //Id for meshes created by the multimaterial
  101123. var isFirstMaterial = true;
  101124. /**
  101125. * Search for obj in the given array.
  101126. * This function is called to check if a couple of data already exists in an array.
  101127. *
  101128. * If found, returns the index of the founded tuple index. Returns -1 if not found
  101129. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  101130. * @param obj Array<number>
  101131. * @returns {boolean}
  101132. */
  101133. var isInArray = function (arr, obj) {
  101134. if (!arr[obj[0]])
  101135. arr[obj[0]] = { normals: [], idx: [] };
  101136. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  101137. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  101138. };
  101139. var isInArrayUV = function (arr, obj) {
  101140. if (!arr[obj[0]])
  101141. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  101142. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  101143. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  101144. return arr[obj[0]].idx[idx];
  101145. }
  101146. return -1;
  101147. };
  101148. /**
  101149. * This function set the data for each triangle.
  101150. * Data are position, normals and uvs
  101151. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  101152. * If the tuple already exist, add only their indice
  101153. *
  101154. * @param indicePositionFromObj Integer The index in positions array
  101155. * @param indiceUvsFromObj Integer The index in uvs array
  101156. * @param indiceNormalFromObj Integer The index in normals array
  101157. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  101158. * @param textureVectorFromOBJ Vector3 The value of uvs
  101159. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  101160. */
  101161. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  101162. //Check if this tuple already exists in the list of tuples
  101163. var _index;
  101164. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  101165. _index = isInArrayUV(tuplePosNorm, [
  101166. indicePositionFromObj,
  101167. indiceNormalFromObj,
  101168. indiceUvsFromObj
  101169. ]);
  101170. }
  101171. else {
  101172. _index = isInArray(tuplePosNorm, [
  101173. indicePositionFromObj,
  101174. indiceNormalFromObj
  101175. ]);
  101176. }
  101177. //If it not exists
  101178. if (_index == -1) {
  101179. //Add an new indice.
  101180. //The array of indices is only an array with his length equal to the number of triangles - 1.
  101181. //We add vertices data in this order
  101182. indicesForBabylon.push(wrappedPositionForBabylon.length);
  101183. //Push the position of vertice for Babylon
  101184. //Each element is a BABYLON.Vector3(x,y,z)
  101185. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  101186. //Push the uvs for Babylon
  101187. //Each element is a BABYLON.Vector3(u,v)
  101188. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  101189. //Push the normals for Babylon
  101190. //Each element is a BABYLON.Vector3(x,y,z)
  101191. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  101192. //Add the tuple in the comparison list
  101193. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  101194. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  101195. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  101196. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  101197. }
  101198. else {
  101199. //The tuple already exists
  101200. //Add the index of the already existing tuple
  101201. //At this index we can get the value of position, normal and uvs of vertex
  101202. indicesForBabylon.push(_index);
  101203. }
  101204. };
  101205. /**
  101206. * Transform BABYLON.Vector() object onto 3 digits in an array
  101207. */
  101208. var unwrapData = function () {
  101209. //Every array has the same length
  101210. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  101211. //Push the x, y, z values of each element in the unwrapped array
  101212. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  101213. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  101214. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  101215. }
  101216. // Reset arrays for the next new meshes
  101217. wrappedPositionForBabylon = [];
  101218. wrappedNormalsForBabylon = [];
  101219. wrappedUvsForBabylon = [];
  101220. tuplePosNorm = [];
  101221. curPositionInIndices = 0;
  101222. };
  101223. /**
  101224. * Create triangles from polygons by recursion
  101225. * The best to understand how it works is to draw it in the same time you get the recursion.
  101226. * It is important to notice that a triangle is a polygon
  101227. * We get 4 patterns of face defined in OBJ File :
  101228. * facePattern1 = ["1","2","3","4","5","6"]
  101229. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  101230. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  101231. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  101232. * Each pattern is divided by the same method
  101233. * @param face Array[String] The indices of elements
  101234. * @param v Integer The variable to increment
  101235. */
  101236. var getTriangles = function (face, v) {
  101237. //Work for each element of the array
  101238. if (v + 1 < face.length) {
  101239. //Add on the triangle variable the indexes to obtain triangles
  101240. triangles.push(face[0], face[v], face[v + 1]);
  101241. //Incrementation for recursion
  101242. v += 1;
  101243. //Recursion
  101244. getTriangles(face, v);
  101245. }
  101246. //Result obtained after 2 iterations:
  101247. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  101248. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  101249. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  101250. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  101251. };
  101252. /**
  101253. * Create triangles and push the data for each polygon for the pattern 1
  101254. * In this pattern we get vertice positions
  101255. * @param face
  101256. * @param v
  101257. */
  101258. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  101259. //Get the indices of triangles for each polygon
  101260. getTriangles(face, v);
  101261. //For each element in the triangles array.
  101262. //This var could contains 1 to an infinity of triangles
  101263. for (var k = 0; k < triangles.length; k++) {
  101264. // Set position indice
  101265. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  101266. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  101267. positions[indicePositionFromObj], //Get the vectors data
  101268. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  101269. );
  101270. }
  101271. //Reset variable for the next line
  101272. triangles = [];
  101273. };
  101274. /**
  101275. * Create triangles and push the data for each polygon for the pattern 2
  101276. * In this pattern we get vertice positions and uvsu
  101277. * @param face
  101278. * @param v
  101279. */
  101280. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  101281. //Get the indices of triangles for each polygon
  101282. getTriangles(face, v);
  101283. for (var k = 0; k < triangles.length; k++) {
  101284. //triangle[k] = "1/1"
  101285. //Split the data for getting position and uv
  101286. var point = triangles[k].split("/"); // ["1", "1"]
  101287. //Set position indice
  101288. var indicePositionFromObj = parseInt(point[0]) - 1;
  101289. //Set uv indice
  101290. var indiceUvsFromObj = parseInt(point[1]) - 1;
  101291. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  101292. positions[indicePositionFromObj], //Get the values for each element
  101293. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  101294. );
  101295. }
  101296. //Reset variable for the next line
  101297. triangles = [];
  101298. };
  101299. /**
  101300. * Create triangles and push the data for each polygon for the pattern 3
  101301. * In this pattern we get vertice positions, uvs and normals
  101302. * @param face
  101303. * @param v
  101304. */
  101305. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  101306. //Get the indices of triangles for each polygon
  101307. getTriangles(face, v);
  101308. for (var k = 0; k < triangles.length; k++) {
  101309. //triangle[k] = "1/1/1"
  101310. //Split the data for getting position, uv, and normals
  101311. var point = triangles[k].split("/"); // ["1", "1", "1"]
  101312. // Set position indice
  101313. var indicePositionFromObj = parseInt(point[0]) - 1;
  101314. // Set uv indice
  101315. var indiceUvsFromObj = parseInt(point[1]) - 1;
  101316. // Set normal indice
  101317. var indiceNormalFromObj = parseInt(point[2]) - 1;
  101318. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  101319. );
  101320. }
  101321. //Reset variable for the next line
  101322. triangles = [];
  101323. };
  101324. /**
  101325. * Create triangles and push the data for each polygon for the pattern 4
  101326. * In this pattern we get vertice positions and normals
  101327. * @param face
  101328. * @param v
  101329. */
  101330. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  101331. getTriangles(face, v);
  101332. for (var k = 0; k < triangles.length; k++) {
  101333. //triangle[k] = "1//1"
  101334. //Split the data for getting position and normals
  101335. var point = triangles[k].split("//"); // ["1", "1"]
  101336. // We check indices, and normals
  101337. var indicePositionFromObj = parseInt(point[0]) - 1;
  101338. var indiceNormalFromObj = parseInt(point[1]) - 1;
  101339. setData(indicePositionFromObj, 1, //Default value for uv
  101340. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  101341. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  101342. }
  101343. //Reset variable for the next line
  101344. triangles = [];
  101345. };
  101346. var addPreviousObjMesh = function () {
  101347. //Check if it is not the first mesh. Otherwise we don't have data.
  101348. if (meshesFromObj.length > 0) {
  101349. //Get the previous mesh for applying the data about the faces
  101350. //=> in obj file, faces definition append after the name of the mesh
  101351. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  101352. //Set the data into Array for the mesh
  101353. unwrapData();
  101354. // Reverse tab. Otherwise face are displayed in the wrong sens
  101355. indicesForBabylon.reverse();
  101356. //Set the information for the mesh
  101357. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  101358. handledMesh.indices = indicesForBabylon.slice();
  101359. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  101360. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  101361. handledMesh.uvs = unwrappedUVForBabylon.slice();
  101362. //Reset the array for the next mesh
  101363. indicesForBabylon = [];
  101364. unwrappedPositionsForBabylon = [];
  101365. unwrappedNormalsForBabylon = [];
  101366. unwrappedUVForBabylon = [];
  101367. }
  101368. };
  101369. //Main function
  101370. //Split the file into lines
  101371. var lines = data.split('\n');
  101372. //Look at each line
  101373. for (var i = 0; i < lines.length; i++) {
  101374. var line = lines[i].trim();
  101375. var result;
  101376. //Comment or newLine
  101377. if (line.length === 0 || line.charAt(0) === '#') {
  101378. continue;
  101379. //Get information about one position possible for the vertices
  101380. }
  101381. else if ((result = this.vertexPattern.exec(line)) !== null) {
  101382. //Create a Vector3 with the position x, y, z
  101383. //Value of result:
  101384. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  101385. //Add the Vector in the list of positions
  101386. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  101387. }
  101388. else if ((result = this.normalPattern.exec(line)) !== null) {
  101389. //Create a Vector3 with the normals x, y, z
  101390. //Value of result
  101391. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  101392. //Add the Vector in the list of normals
  101393. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  101394. }
  101395. else if ((result = this.uvPattern.exec(line)) !== null) {
  101396. //Create a Vector2 with the normals u, v
  101397. //Value of result
  101398. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  101399. //Add the Vector in the list of uvs
  101400. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  101401. //Identify patterns of faces
  101402. //Face could be defined in different type of pattern
  101403. }
  101404. else if ((result = this.facePattern3.exec(line)) !== null) {
  101405. //Value of result:
  101406. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  101407. //Set the data for this face
  101408. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  101409. 1);
  101410. }
  101411. else if ((result = this.facePattern4.exec(line)) !== null) {
  101412. //Value of result:
  101413. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  101414. //Set the data for this face
  101415. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  101416. 1);
  101417. }
  101418. else if ((result = this.facePattern2.exec(line)) !== null) {
  101419. //Value of result:
  101420. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  101421. //Set the data for this face
  101422. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  101423. 1);
  101424. }
  101425. else if ((result = this.facePattern1.exec(line)) !== null) {
  101426. //Value of result
  101427. //["f 1 2 3", "1 2 3"...]
  101428. //Set the data for this face
  101429. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  101430. 1);
  101431. //Define a mesh or an object
  101432. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  101433. }
  101434. else if (this.group.test(line) || this.obj.test(line)) {
  101435. //Create a new mesh corresponding to the name of the group.
  101436. //Definition of the mesh
  101437. var objMesh =
  101438. //Set the name of the current obj mesh
  101439. {
  101440. name: line.substring(2).trim(),
  101441. indices: undefined,
  101442. positions: undefined,
  101443. normals: undefined,
  101444. uvs: undefined,
  101445. materialName: ""
  101446. };
  101447. addPreviousObjMesh();
  101448. //Push the last mesh created with only the name
  101449. meshesFromObj.push(objMesh);
  101450. //Set this variable to indicate that now meshesFromObj has objects defined inside
  101451. hasMeshes = true;
  101452. isFirstMaterial = true;
  101453. increment = 1;
  101454. //Keyword for applying a material
  101455. }
  101456. else if (this.usemtl.test(line)) {
  101457. //Get the name of the material
  101458. materialNameFromObj = line.substring(7).trim();
  101459. //If this new material is in the same mesh
  101460. if (!isFirstMaterial) {
  101461. //Set the data for the previous mesh
  101462. addPreviousObjMesh();
  101463. //Create a new mesh
  101464. var objMesh =
  101465. //Set the name of the current obj mesh
  101466. {
  101467. name: objMeshName + "_mm" + increment.toString(),
  101468. indices: undefined,
  101469. positions: undefined,
  101470. normals: undefined,
  101471. uvs: undefined,
  101472. materialName: materialNameFromObj
  101473. };
  101474. increment++;
  101475. //If meshes are already defined
  101476. meshesFromObj.push(objMesh);
  101477. }
  101478. //Set the material name if the previous line define a mesh
  101479. if (hasMeshes && isFirstMaterial) {
  101480. //Set the material name to the previous mesh (1 material per mesh)
  101481. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  101482. isFirstMaterial = false;
  101483. }
  101484. //Keyword for loading the mtl file
  101485. }
  101486. else if (this.mtllib.test(line)) {
  101487. //Get the name of mtl file
  101488. fileToLoad = line.substring(7).trim();
  101489. //Apply smoothing
  101490. }
  101491. else if (this.smooth.test(line)) {
  101492. // smooth shading => apply smoothing
  101493. //Toda y I don't know it work with babylon and with obj.
  101494. //With the obj file an integer is set
  101495. }
  101496. else {
  101497. //If there is another possibility
  101498. console.log("Unhandled expression at line : " + line);
  101499. }
  101500. }
  101501. //At the end of the file, add the last mesh into the meshesFromObj array
  101502. if (hasMeshes) {
  101503. //Set the data for the last mesh
  101504. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  101505. //Reverse indices for displaying faces in the good sens
  101506. indicesForBabylon.reverse();
  101507. //Get the good array
  101508. unwrapData();
  101509. //Set array
  101510. handledMesh.indices = indicesForBabylon;
  101511. handledMesh.positions = unwrappedPositionsForBabylon;
  101512. handledMesh.normals = unwrappedNormalsForBabylon;
  101513. handledMesh.uvs = unwrappedUVForBabylon;
  101514. }
  101515. //If any o or g keyword found, create a mesj with a random id
  101516. if (!hasMeshes) {
  101517. // reverse tab of indices
  101518. indicesForBabylon.reverse();
  101519. //Get positions normals uvs
  101520. unwrapData();
  101521. //Set data for one mesh
  101522. meshesFromObj.push({
  101523. name: BABYLON.Geometry.RandomId(),
  101524. indices: indicesForBabylon,
  101525. positions: unwrappedPositionsForBabylon,
  101526. normals: unwrappedNormalsForBabylon,
  101527. uvs: unwrappedUVForBabylon,
  101528. materialName: materialNameFromObj
  101529. });
  101530. }
  101531. //Create a BABYLON.Mesh list
  101532. var babylonMeshesArray = []; //The mesh for babylon
  101533. var materialToUse = new Array();
  101534. //Set data for each mesh
  101535. for (var j = 0; j < meshesFromObj.length; j++) {
  101536. //check meshesNames (stlFileLoader)
  101537. if (meshesNames && meshesFromObj[j].name) {
  101538. if (meshesNames instanceof Array) {
  101539. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  101540. continue;
  101541. }
  101542. }
  101543. else {
  101544. if (meshesFromObj[j].name !== meshesNames) {
  101545. continue;
  101546. }
  101547. }
  101548. }
  101549. //Get the current mesh
  101550. //Set the data with VertexBuffer for each mesh
  101551. handledMesh = meshesFromObj[j];
  101552. //Create a BABYLON.Mesh with the name of the obj mesh
  101553. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  101554. //Push the name of the material to an array
  101555. //This is indispensable for the importMesh function
  101556. materialToUse.push(meshesFromObj[j].materialName);
  101557. var vertexData = new BABYLON.VertexData(); //The container for the values
  101558. //Set the data for the babylonMesh
  101559. vertexData.positions = handledMesh.positions;
  101560. vertexData.normals = handledMesh.normals;
  101561. vertexData.uvs = handledMesh.uvs;
  101562. vertexData.indices = handledMesh.indices;
  101563. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  101564. vertexData.applyToMesh(babylonMesh);
  101565. if (OBJFileLoader.INVERT_Y) {
  101566. babylonMesh.scaling.y *= -1;
  101567. }
  101568. //Push the mesh into an array
  101569. babylonMeshesArray.push(babylonMesh);
  101570. }
  101571. //load the materials
  101572. //Check if we have a file to load
  101573. if (fileToLoad !== "") {
  101574. //Load the file synchronously
  101575. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  101576. //Create materials thanks MTLLoader function
  101577. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  101578. //Look at each material loaded in the mtl file
  101579. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  101580. //Three variables to get all meshes with the same material
  101581. var startIndex = 0;
  101582. var _indices = [];
  101583. var _index;
  101584. //The material from MTL file is used in the meshes loaded
  101585. //Push the indice in an array
  101586. //Check if the material is not used for another mesh
  101587. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  101588. _indices.push(_index);
  101589. startIndex = _index + 1;
  101590. }
  101591. //If the material is not used dispose it
  101592. if (_index == -1 && _indices.length == 0) {
  101593. //If the material is not needed, remove it
  101594. materialsFromMTLFile.materials[n].dispose();
  101595. }
  101596. else {
  101597. for (var o = 0; o < _indices.length; o++) {
  101598. //Apply the material to the BABYLON.Mesh for each mesh with the material
  101599. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  101600. }
  101601. }
  101602. }
  101603. });
  101604. }
  101605. //Return an array with all BABYLON.Mesh
  101606. return babylonMeshesArray;
  101607. };
  101608. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  101609. OBJFileLoader.INVERT_Y = false;
  101610. return OBJFileLoader;
  101611. }());
  101612. BABYLON.OBJFileLoader = OBJFileLoader;
  101613. if (BABYLON.SceneLoader) {
  101614. //Add this loader into the register plugin
  101615. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  101616. }
  101617. })(BABYLON || (BABYLON = {}));
  101618. //# sourceMappingURL=babylon.objFileLoader.js.map
  101619. var BABYLON;
  101620. (function (BABYLON) {
  101621. /**
  101622. * Mode that determines the coordinate system to use.
  101623. */
  101624. var GLTFLoaderCoordinateSystemMode;
  101625. (function (GLTFLoaderCoordinateSystemMode) {
  101626. /**
  101627. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  101628. */
  101629. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  101630. /**
  101631. * Sets the useRightHandedSystem flag on the scene.
  101632. */
  101633. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  101634. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  101635. /**
  101636. * Mode that determines what animations will start.
  101637. */
  101638. var GLTFLoaderAnimationStartMode;
  101639. (function (GLTFLoaderAnimationStartMode) {
  101640. /**
  101641. * No animation will start.
  101642. */
  101643. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  101644. /**
  101645. * The first animation will start.
  101646. */
  101647. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  101648. /**
  101649. * All animations will start.
  101650. */
  101651. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  101652. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  101653. /**
  101654. * Loader state.
  101655. */
  101656. var GLTFLoaderState;
  101657. (function (GLTFLoaderState) {
  101658. /**
  101659. * The asset is loading.
  101660. */
  101661. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  101662. /**
  101663. * The asset is ready for rendering.
  101664. */
  101665. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  101666. /**
  101667. * The asset is completely loaded.
  101668. */
  101669. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  101670. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  101671. /**
  101672. * File loader for loading glTF files into a scene.
  101673. */
  101674. var GLTFFileLoader = /** @class */ (function () {
  101675. function GLTFFileLoader() {
  101676. // #region Common options
  101677. /**
  101678. * Raised when the asset has been parsed
  101679. */
  101680. this.onParsedObservable = new BABYLON.Observable();
  101681. // #endregion
  101682. // #region V2 options
  101683. /**
  101684. * The coordinate system mode. Defaults to AUTO.
  101685. */
  101686. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  101687. /**
  101688. * The animation start mode. Defaults to FIRST.
  101689. */
  101690. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  101691. /**
  101692. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  101693. */
  101694. this.compileMaterials = false;
  101695. /**
  101696. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  101697. */
  101698. this.useClipPlane = false;
  101699. /**
  101700. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  101701. */
  101702. this.compileShadowGenerators = false;
  101703. /**
  101704. * Defines if the Alpha blended materials are only applied as coverage.
  101705. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  101706. * If true, no extra effects are applied to transparent pixels.
  101707. */
  101708. this.transparencyAsCoverage = false;
  101709. /** @hidden */
  101710. this._normalizeAnimationGroupsToBeginAtZero = true;
  101711. /**
  101712. * Function called before loading a url referenced by the asset.
  101713. */
  101714. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  101715. /**
  101716. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101717. */
  101718. this.onMeshLoadedObservable = new BABYLON.Observable();
  101719. /**
  101720. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  101721. */
  101722. this.onTextureLoadedObservable = new BABYLON.Observable();
  101723. /**
  101724. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  101725. */
  101726. this.onMaterialLoadedObservable = new BABYLON.Observable();
  101727. /**
  101728. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  101729. */
  101730. this.onCameraLoadedObservable = new BABYLON.Observable();
  101731. /**
  101732. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  101733. * For assets with LODs, raised when all of the LODs are complete.
  101734. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  101735. */
  101736. this.onCompleteObservable = new BABYLON.Observable();
  101737. /**
  101738. * Observable raised after the loader is disposed.
  101739. */
  101740. this.onDisposeObservable = new BABYLON.Observable();
  101741. /**
  101742. * Observable raised after a loader extension is created.
  101743. * Set additional options for a loader extension in this event.
  101744. */
  101745. this.onExtensionLoadedObservable = new BABYLON.Observable();
  101746. // #endregion
  101747. this._loader = null;
  101748. /**
  101749. * Name of the loader ("gltf")
  101750. */
  101751. this.name = "gltf";
  101752. /**
  101753. * Supported file extensions of the loader (.gltf, .glb)
  101754. */
  101755. this.extensions = {
  101756. ".gltf": { isBinary: false },
  101757. ".glb": { isBinary: true }
  101758. };
  101759. }
  101760. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  101761. /**
  101762. * Raised when the asset has been parsed
  101763. */
  101764. set: function (callback) {
  101765. if (this._onParsedObserver) {
  101766. this.onParsedObservable.remove(this._onParsedObserver);
  101767. }
  101768. this._onParsedObserver = this.onParsedObservable.add(callback);
  101769. },
  101770. enumerable: true,
  101771. configurable: true
  101772. });
  101773. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  101774. /**
  101775. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101776. */
  101777. set: function (callback) {
  101778. if (this._onMeshLoadedObserver) {
  101779. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  101780. }
  101781. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  101782. },
  101783. enumerable: true,
  101784. configurable: true
  101785. });
  101786. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  101787. /**
  101788. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  101789. */
  101790. set: function (callback) {
  101791. if (this._onTextureLoadedObserver) {
  101792. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  101793. }
  101794. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  101795. },
  101796. enumerable: true,
  101797. configurable: true
  101798. });
  101799. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  101800. /**
  101801. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  101802. */
  101803. set: function (callback) {
  101804. if (this._onMaterialLoadedObserver) {
  101805. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  101806. }
  101807. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  101808. },
  101809. enumerable: true,
  101810. configurable: true
  101811. });
  101812. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  101813. /**
  101814. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  101815. */
  101816. set: function (callback) {
  101817. if (this._onCameraLoadedObserver) {
  101818. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  101819. }
  101820. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  101821. },
  101822. enumerable: true,
  101823. configurable: true
  101824. });
  101825. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  101826. /**
  101827. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  101828. */
  101829. set: function (callback) {
  101830. if (this._onCompleteObserver) {
  101831. this.onCompleteObservable.remove(this._onCompleteObserver);
  101832. }
  101833. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  101834. },
  101835. enumerable: true,
  101836. configurable: true
  101837. });
  101838. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  101839. /**
  101840. * Callback raised after the loader is disposed.
  101841. */
  101842. set: function (callback) {
  101843. if (this._onDisposeObserver) {
  101844. this.onDisposeObservable.remove(this._onDisposeObserver);
  101845. }
  101846. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  101847. },
  101848. enumerable: true,
  101849. configurable: true
  101850. });
  101851. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  101852. /**
  101853. * Callback raised after a loader extension is created.
  101854. */
  101855. set: function (callback) {
  101856. if (this._onExtensionLoadedObserver) {
  101857. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  101858. }
  101859. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  101860. },
  101861. enumerable: true,
  101862. configurable: true
  101863. });
  101864. /**
  101865. * Returns a promise that resolves when the asset is completely loaded.
  101866. * @returns a promise that resolves when the asset is completely loaded.
  101867. */
  101868. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  101869. var _this = this;
  101870. return new Promise(function (resolve) {
  101871. _this.onCompleteObservable.add(function () {
  101872. resolve();
  101873. }, undefined, undefined, undefined, true);
  101874. });
  101875. };
  101876. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  101877. /**
  101878. * The loader state or null if the loader is not active.
  101879. */
  101880. get: function () {
  101881. return this._loader ? this._loader.state : null;
  101882. },
  101883. enumerable: true,
  101884. configurable: true
  101885. });
  101886. /**
  101887. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  101888. */
  101889. GLTFFileLoader.prototype.dispose = function () {
  101890. if (this._loader) {
  101891. this._loader.dispose();
  101892. this._loader = null;
  101893. }
  101894. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  101895. this.onMeshLoadedObservable.clear();
  101896. this.onTextureLoadedObservable.clear();
  101897. this.onMaterialLoadedObservable.clear();
  101898. this.onCameraLoadedObservable.clear();
  101899. this.onCompleteObservable.clear();
  101900. this.onExtensionLoadedObservable.clear();
  101901. this.onDisposeObservable.notifyObservers(this);
  101902. this.onDisposeObservable.clear();
  101903. };
  101904. /**
  101905. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  101906. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  101907. * @param scene the scene the meshes should be added to
  101908. * @param data the glTF data to load
  101909. * @param rootUrl root url to load from
  101910. * @param onProgress event that fires when loading progress has occured
  101911. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  101912. */
  101913. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  101914. var _this = this;
  101915. return Promise.resolve().then(function () {
  101916. var loaderData = _this._parse(data);
  101917. _this._loader = _this._getLoader(loaderData);
  101918. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  101919. });
  101920. };
  101921. /**
  101922. * Imports all objects from the loaded glTF data and adds them to the scene
  101923. * @param scene the scene the objects should be added to
  101924. * @param data the glTF data to load
  101925. * @param rootUrl root url to load from
  101926. * @param onProgress event that fires when loading progress has occured
  101927. * @returns a promise which completes when objects have been loaded to the scene
  101928. */
  101929. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  101930. var _this = this;
  101931. return Promise.resolve().then(function () {
  101932. var loaderData = _this._parse(data);
  101933. _this._loader = _this._getLoader(loaderData);
  101934. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  101935. });
  101936. };
  101937. /**
  101938. * Load into an asset container.
  101939. * @param scene The scene to load into
  101940. * @param data The data to import
  101941. * @param rootUrl The root url for scene and resources
  101942. * @param onProgress The callback when the load progresses
  101943. * @returns The loaded asset container
  101944. */
  101945. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  101946. var _this = this;
  101947. return Promise.resolve().then(function () {
  101948. var loaderData = _this._parse(data);
  101949. _this._loader = _this._getLoader(loaderData);
  101950. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  101951. var container = new BABYLON.AssetContainer(scene);
  101952. Array.prototype.push.apply(container.meshes, result.meshes);
  101953. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  101954. Array.prototype.push.apply(container.skeletons, result.skeletons);
  101955. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  101956. container.removeAllFromScene();
  101957. return container;
  101958. });
  101959. });
  101960. };
  101961. /**
  101962. * If the data string can be loaded directly.
  101963. * @param data string contianing the file data
  101964. * @returns if the data can be loaded directly
  101965. */
  101966. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  101967. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  101968. };
  101969. /**
  101970. * Instantiates a glTF file loader plugin.
  101971. * @returns the created plugin
  101972. */
  101973. GLTFFileLoader.prototype.createPlugin = function () {
  101974. return new GLTFFileLoader();
  101975. };
  101976. GLTFFileLoader.prototype._parse = function (data) {
  101977. var parsedData;
  101978. if (data instanceof ArrayBuffer) {
  101979. parsedData = GLTFFileLoader._parseBinary(data);
  101980. }
  101981. else {
  101982. parsedData = {
  101983. json: JSON.parse(data),
  101984. bin: null
  101985. };
  101986. }
  101987. this.onParsedObservable.notifyObservers(parsedData);
  101988. this.onParsedObservable.clear();
  101989. return parsedData;
  101990. };
  101991. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  101992. var _this = this;
  101993. var loaderVersion = { major: 2, minor: 0 };
  101994. var asset = loaderData.json.asset || {};
  101995. var version = GLTFFileLoader._parseVersion(asset.version);
  101996. if (!version) {
  101997. throw new Error("Invalid version: " + asset.version);
  101998. }
  101999. if (asset.minVersion !== undefined) {
  102000. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  102001. if (!minVersion) {
  102002. throw new Error("Invalid minimum version: " + asset.minVersion);
  102003. }
  102004. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  102005. throw new Error("Incompatible minimum version: " + asset.minVersion);
  102006. }
  102007. }
  102008. var createLoaders = {
  102009. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  102010. 2: GLTFFileLoader.CreateGLTFLoaderV2
  102011. };
  102012. var createLoader = createLoaders[version.major];
  102013. if (!createLoader) {
  102014. throw new Error("Unsupported version: " + asset.version);
  102015. }
  102016. var loader = createLoader();
  102017. loader.coordinateSystemMode = this.coordinateSystemMode;
  102018. loader.animationStartMode = this.animationStartMode;
  102019. loader.compileMaterials = this.compileMaterials;
  102020. loader.useClipPlane = this.useClipPlane;
  102021. loader.compileShadowGenerators = this.compileShadowGenerators;
  102022. loader.transparencyAsCoverage = this.transparencyAsCoverage;
  102023. loader._normalizeAnimationGroupsToBeginAtZero = this._normalizeAnimationGroupsToBeginAtZero;
  102024. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  102025. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  102026. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  102027. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  102028. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  102029. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  102030. loader.onCompleteObservable.add(function () {
  102031. _this.onMeshLoadedObservable.clear();
  102032. _this.onTextureLoadedObservable.clear();
  102033. _this.onMaterialLoadedObservable.clear();
  102034. _this.onCameraLoadedObservable.clear();
  102035. _this.onExtensionLoadedObservable.clear();
  102036. _this.onCompleteObservable.notifyObservers(_this);
  102037. _this.onCompleteObservable.clear();
  102038. });
  102039. return loader;
  102040. };
  102041. GLTFFileLoader._parseBinary = function (data) {
  102042. var Binary = {
  102043. Magic: 0x46546C67
  102044. };
  102045. var binaryReader = new BinaryReader(data);
  102046. var magic = binaryReader.readUint32();
  102047. if (magic !== Binary.Magic) {
  102048. throw new Error("Unexpected magic: " + magic);
  102049. }
  102050. var version = binaryReader.readUint32();
  102051. switch (version) {
  102052. case 1: return GLTFFileLoader._parseV1(binaryReader);
  102053. case 2: return GLTFFileLoader._parseV2(binaryReader);
  102054. }
  102055. throw new Error("Unsupported version: " + version);
  102056. };
  102057. GLTFFileLoader._parseV1 = function (binaryReader) {
  102058. var ContentFormat = {
  102059. JSON: 0
  102060. };
  102061. var length = binaryReader.readUint32();
  102062. if (length != binaryReader.getLength()) {
  102063. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  102064. }
  102065. var contentLength = binaryReader.readUint32();
  102066. var contentFormat = binaryReader.readUint32();
  102067. var content;
  102068. switch (contentFormat) {
  102069. case ContentFormat.JSON: {
  102070. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  102071. break;
  102072. }
  102073. default: {
  102074. throw new Error("Unexpected content format: " + contentFormat);
  102075. }
  102076. }
  102077. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  102078. var body = binaryReader.readUint8Array(bytesRemaining);
  102079. return {
  102080. json: content,
  102081. bin: body
  102082. };
  102083. };
  102084. GLTFFileLoader._parseV2 = function (binaryReader) {
  102085. var ChunkFormat = {
  102086. JSON: 0x4E4F534A,
  102087. BIN: 0x004E4942
  102088. };
  102089. var length = binaryReader.readUint32();
  102090. if (length !== binaryReader.getLength()) {
  102091. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  102092. }
  102093. // JSON chunk
  102094. var chunkLength = binaryReader.readUint32();
  102095. var chunkFormat = binaryReader.readUint32();
  102096. if (chunkFormat !== ChunkFormat.JSON) {
  102097. throw new Error("First chunk format is not JSON");
  102098. }
  102099. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  102100. // Look for BIN chunk
  102101. var bin = null;
  102102. while (binaryReader.getPosition() < binaryReader.getLength()) {
  102103. var chunkLength_1 = binaryReader.readUint32();
  102104. var chunkFormat_1 = binaryReader.readUint32();
  102105. switch (chunkFormat_1) {
  102106. case ChunkFormat.JSON: {
  102107. throw new Error("Unexpected JSON chunk");
  102108. }
  102109. case ChunkFormat.BIN: {
  102110. bin = binaryReader.readUint8Array(chunkLength_1);
  102111. break;
  102112. }
  102113. default: {
  102114. // ignore unrecognized chunkFormat
  102115. binaryReader.skipBytes(chunkLength_1);
  102116. break;
  102117. }
  102118. }
  102119. }
  102120. return {
  102121. json: json,
  102122. bin: bin
  102123. };
  102124. };
  102125. GLTFFileLoader._parseVersion = function (version) {
  102126. if (version === "1.0" || version === "1.0.1") {
  102127. return {
  102128. major: 1,
  102129. minor: 0
  102130. };
  102131. }
  102132. var match = (version + "").match(/^(\d+)\.(\d+)/);
  102133. if (!match) {
  102134. return null;
  102135. }
  102136. return {
  102137. major: parseInt(match[1]),
  102138. minor: parseInt(match[2])
  102139. };
  102140. };
  102141. GLTFFileLoader._compareVersion = function (a, b) {
  102142. if (a.major > b.major)
  102143. return 1;
  102144. if (a.major < b.major)
  102145. return -1;
  102146. if (a.minor > b.minor)
  102147. return 1;
  102148. if (a.minor < b.minor)
  102149. return -1;
  102150. return 0;
  102151. };
  102152. GLTFFileLoader._decodeBufferToText = function (buffer) {
  102153. var result = "";
  102154. var length = buffer.byteLength;
  102155. for (var i = 0; i < length; i++) {
  102156. result += String.fromCharCode(buffer[i]);
  102157. }
  102158. return result;
  102159. };
  102160. // #endregion
  102161. // #region V1 options
  102162. /**
  102163. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  102164. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  102165. * Defaults to true.
  102166. */
  102167. GLTFFileLoader.IncrementalLoading = true;
  102168. /**
  102169. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  102170. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  102171. */
  102172. GLTFFileLoader.HomogeneousCoordinates = false;
  102173. return GLTFFileLoader;
  102174. }());
  102175. BABYLON.GLTFFileLoader = GLTFFileLoader;
  102176. var BinaryReader = /** @class */ (function () {
  102177. function BinaryReader(arrayBuffer) {
  102178. this._arrayBuffer = arrayBuffer;
  102179. this._dataView = new DataView(arrayBuffer);
  102180. this._byteOffset = 0;
  102181. }
  102182. BinaryReader.prototype.getPosition = function () {
  102183. return this._byteOffset;
  102184. };
  102185. BinaryReader.prototype.getLength = function () {
  102186. return this._arrayBuffer.byteLength;
  102187. };
  102188. BinaryReader.prototype.readUint32 = function () {
  102189. var value = this._dataView.getUint32(this._byteOffset, true);
  102190. this._byteOffset += 4;
  102191. return value;
  102192. };
  102193. BinaryReader.prototype.readUint8Array = function (length) {
  102194. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  102195. this._byteOffset += length;
  102196. return value;
  102197. };
  102198. BinaryReader.prototype.skipBytes = function (length) {
  102199. this._byteOffset += length;
  102200. };
  102201. return BinaryReader;
  102202. }());
  102203. if (BABYLON.SceneLoader) {
  102204. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  102205. }
  102206. })(BABYLON || (BABYLON = {}));
  102207. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  102208. var BABYLON;
  102209. (function (BABYLON) {
  102210. var GLTF1;
  102211. (function (GLTF1) {
  102212. /**
  102213. * Enums
  102214. */
  102215. var EComponentType;
  102216. (function (EComponentType) {
  102217. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  102218. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  102219. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  102220. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  102221. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  102222. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  102223. var EShaderType;
  102224. (function (EShaderType) {
  102225. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  102226. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  102227. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  102228. var EParameterType;
  102229. (function (EParameterType) {
  102230. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  102231. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  102232. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  102233. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  102234. EParameterType[EParameterType["INT"] = 5124] = "INT";
  102235. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  102236. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  102237. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  102238. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  102239. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  102240. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  102241. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  102242. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  102243. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  102244. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  102245. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  102246. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  102247. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  102248. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  102249. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  102250. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  102251. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  102252. var ETextureWrapMode;
  102253. (function (ETextureWrapMode) {
  102254. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  102255. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  102256. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  102257. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  102258. var ETextureFilterType;
  102259. (function (ETextureFilterType) {
  102260. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  102261. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  102262. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  102263. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  102264. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  102265. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  102266. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  102267. var ETextureFormat;
  102268. (function (ETextureFormat) {
  102269. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  102270. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  102271. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  102272. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  102273. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  102274. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  102275. var ECullingType;
  102276. (function (ECullingType) {
  102277. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  102278. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  102279. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  102280. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  102281. var EBlendingFunction;
  102282. (function (EBlendingFunction) {
  102283. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  102284. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  102285. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  102286. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  102287. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  102288. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  102289. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  102290. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  102291. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  102292. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  102293. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  102294. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  102295. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  102296. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  102297. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  102298. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  102299. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102300. })(BABYLON || (BABYLON = {}));
  102301. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  102302. var BABYLON;
  102303. (function (BABYLON) {
  102304. var GLTF1;
  102305. (function (GLTF1) {
  102306. /**
  102307. * Tokenizer. Used for shaders compatibility
  102308. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  102309. */
  102310. var ETokenType;
  102311. (function (ETokenType) {
  102312. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  102313. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  102314. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  102315. })(ETokenType || (ETokenType = {}));
  102316. var Tokenizer = /** @class */ (function () {
  102317. function Tokenizer(toParse) {
  102318. this._pos = 0;
  102319. this.currentToken = ETokenType.UNKNOWN;
  102320. this.currentIdentifier = "";
  102321. this.currentString = "";
  102322. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  102323. this._toParse = toParse;
  102324. this._maxPos = toParse.length;
  102325. }
  102326. Tokenizer.prototype.getNextToken = function () {
  102327. if (this.isEnd())
  102328. return ETokenType.END_OF_INPUT;
  102329. this.currentString = this.read();
  102330. this.currentToken = ETokenType.UNKNOWN;
  102331. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  102332. this.currentToken = ETokenType.IDENTIFIER;
  102333. this.currentIdentifier = this.currentString;
  102334. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  102335. this.currentIdentifier += this.currentString;
  102336. this.forward();
  102337. }
  102338. }
  102339. return this.currentToken;
  102340. };
  102341. Tokenizer.prototype.peek = function () {
  102342. return this._toParse[this._pos];
  102343. };
  102344. Tokenizer.prototype.read = function () {
  102345. return this._toParse[this._pos++];
  102346. };
  102347. Tokenizer.prototype.forward = function () {
  102348. this._pos++;
  102349. };
  102350. Tokenizer.prototype.isEnd = function () {
  102351. return this._pos >= this._maxPos;
  102352. };
  102353. return Tokenizer;
  102354. }());
  102355. /**
  102356. * Values
  102357. */
  102358. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  102359. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  102360. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  102361. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  102362. /**
  102363. * Parse
  102364. */
  102365. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  102366. for (var buf in parsedBuffers) {
  102367. var parsedBuffer = parsedBuffers[buf];
  102368. gltfRuntime.buffers[buf] = parsedBuffer;
  102369. gltfRuntime.buffersCount++;
  102370. }
  102371. };
  102372. var parseShaders = function (parsedShaders, gltfRuntime) {
  102373. for (var sha in parsedShaders) {
  102374. var parsedShader = parsedShaders[sha];
  102375. gltfRuntime.shaders[sha] = parsedShader;
  102376. gltfRuntime.shaderscount++;
  102377. }
  102378. };
  102379. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  102380. for (var object in parsedObjects) {
  102381. var parsedObject = parsedObjects[object];
  102382. gltfRuntime[runtimeProperty][object] = parsedObject;
  102383. }
  102384. };
  102385. /**
  102386. * Utils
  102387. */
  102388. var normalizeUVs = function (buffer) {
  102389. if (!buffer) {
  102390. return;
  102391. }
  102392. for (var i = 0; i < buffer.length / 2; i++) {
  102393. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  102394. }
  102395. };
  102396. var getAttribute = function (attributeParameter) {
  102397. if (attributeParameter.semantic === "NORMAL") {
  102398. return "normal";
  102399. }
  102400. else if (attributeParameter.semantic === "POSITION") {
  102401. return "position";
  102402. }
  102403. else if (attributeParameter.semantic === "JOINT") {
  102404. return "matricesIndices";
  102405. }
  102406. else if (attributeParameter.semantic === "WEIGHT") {
  102407. return "matricesWeights";
  102408. }
  102409. else if (attributeParameter.semantic === "COLOR") {
  102410. return "color";
  102411. }
  102412. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  102413. var channel = Number(attributeParameter.semantic.split("_")[1]);
  102414. return "uv" + (channel === 0 ? "" : channel + 1);
  102415. }
  102416. return null;
  102417. };
  102418. /**
  102419. * Loads and creates animations
  102420. */
  102421. var loadAnimations = function (gltfRuntime) {
  102422. for (var anim in gltfRuntime.animations) {
  102423. var animation = gltfRuntime.animations[anim];
  102424. if (!animation.channels || !animation.samplers) {
  102425. continue;
  102426. }
  102427. var lastAnimation = null;
  102428. for (var i = 0; i < animation.channels.length; i++) {
  102429. // Get parameters and load buffers
  102430. var channel = animation.channels[i];
  102431. var sampler = animation.samplers[channel.sampler];
  102432. if (!sampler) {
  102433. continue;
  102434. }
  102435. var inputData = null;
  102436. var outputData = null;
  102437. if (animation.parameters) {
  102438. inputData = animation.parameters[sampler.input];
  102439. outputData = animation.parameters[sampler.output];
  102440. }
  102441. else {
  102442. inputData = sampler.input;
  102443. outputData = sampler.output;
  102444. }
  102445. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  102446. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  102447. var targetID = channel.target.id;
  102448. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  102449. if (targetNode === null) {
  102450. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  102451. }
  102452. if (targetNode === null) {
  102453. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  102454. continue;
  102455. }
  102456. var isBone = targetNode instanceof BABYLON.Bone;
  102457. // Get target path (position, rotation or scaling)
  102458. var targetPath = channel.target.path;
  102459. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  102460. if (targetPathIndex !== -1) {
  102461. targetPath = babylonAnimationPaths[targetPathIndex];
  102462. }
  102463. // Determine animation type
  102464. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  102465. if (!isBone) {
  102466. if (targetPath === "rotationQuaternion") {
  102467. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  102468. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  102469. }
  102470. else {
  102471. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  102472. }
  102473. }
  102474. // Create animation and key frames
  102475. var babylonAnimation = null;
  102476. var keys = [];
  102477. var arrayOffset = 0;
  102478. var modifyKey = false;
  102479. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  102480. babylonAnimation = lastAnimation;
  102481. modifyKey = true;
  102482. }
  102483. if (!modifyKey) {
  102484. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  102485. }
  102486. // For each frame
  102487. for (var j = 0; j < bufferInput.length; j++) {
  102488. var value = null;
  102489. if (targetPath === "rotationQuaternion") { // VEC4
  102490. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  102491. arrayOffset += 4;
  102492. }
  102493. else { // Position and scaling are VEC3
  102494. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  102495. arrayOffset += 3;
  102496. }
  102497. if (isBone) {
  102498. var bone = targetNode;
  102499. var translation = BABYLON.Vector3.Zero();
  102500. var rotationQuaternion = new BABYLON.Quaternion();
  102501. var scaling = BABYLON.Vector3.Zero();
  102502. // Warning on decompose
  102503. var mat = bone.getBaseMatrix();
  102504. if (modifyKey && lastAnimation) {
  102505. mat = lastAnimation.getKeys()[j].value;
  102506. }
  102507. mat.decompose(scaling, rotationQuaternion, translation);
  102508. if (targetPath === "position") {
  102509. translation = value;
  102510. }
  102511. else if (targetPath === "rotationQuaternion") {
  102512. rotationQuaternion = value;
  102513. }
  102514. else {
  102515. scaling = value;
  102516. }
  102517. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  102518. }
  102519. if (!modifyKey) {
  102520. keys.push({
  102521. frame: bufferInput[j],
  102522. value: value
  102523. });
  102524. }
  102525. else if (lastAnimation) {
  102526. lastAnimation.getKeys()[j].value = value;
  102527. }
  102528. }
  102529. // Finish
  102530. if (!modifyKey && babylonAnimation) {
  102531. babylonAnimation.setKeys(keys);
  102532. targetNode.animations.push(babylonAnimation);
  102533. }
  102534. lastAnimation = babylonAnimation;
  102535. gltfRuntime.scene.stopAnimation(targetNode);
  102536. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  102537. }
  102538. }
  102539. };
  102540. /**
  102541. * Returns the bones transformation matrix
  102542. */
  102543. var configureBoneTransformation = function (node) {
  102544. var mat = null;
  102545. if (node.translation || node.rotation || node.scale) {
  102546. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  102547. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  102548. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  102549. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  102550. }
  102551. else {
  102552. mat = BABYLON.Matrix.FromArray(node.matrix);
  102553. }
  102554. return mat;
  102555. };
  102556. /**
  102557. * Returns the parent bone
  102558. */
  102559. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  102560. // Try to find
  102561. for (var i = 0; i < newSkeleton.bones.length; i++) {
  102562. if (newSkeleton.bones[i].name === jointName) {
  102563. return newSkeleton.bones[i];
  102564. }
  102565. }
  102566. // Not found, search in gltf nodes
  102567. var nodes = gltfRuntime.nodes;
  102568. for (var nde in nodes) {
  102569. var node = nodes[nde];
  102570. if (!node.jointName) {
  102571. continue;
  102572. }
  102573. var children = node.children;
  102574. for (var i = 0; i < children.length; i++) {
  102575. var child = gltfRuntime.nodes[children[i]];
  102576. if (!child.jointName) {
  102577. continue;
  102578. }
  102579. if (child.jointName === jointName) {
  102580. var mat = configureBoneTransformation(node);
  102581. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  102582. bone.id = nde;
  102583. return bone;
  102584. }
  102585. }
  102586. }
  102587. return null;
  102588. };
  102589. /**
  102590. * Returns the appropriate root node
  102591. */
  102592. var getNodeToRoot = function (nodesToRoot, id) {
  102593. for (var i = 0; i < nodesToRoot.length; i++) {
  102594. var nodeToRoot = nodesToRoot[i];
  102595. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  102596. var child = nodeToRoot.node.children[j];
  102597. if (child === id) {
  102598. return nodeToRoot.bone;
  102599. }
  102600. }
  102601. }
  102602. return null;
  102603. };
  102604. /**
  102605. * Returns the node with the joint name
  102606. */
  102607. var getJointNode = function (gltfRuntime, jointName) {
  102608. var nodes = gltfRuntime.nodes;
  102609. var node = nodes[jointName];
  102610. if (node) {
  102611. return {
  102612. node: node,
  102613. id: jointName
  102614. };
  102615. }
  102616. for (var nde in nodes) {
  102617. node = nodes[nde];
  102618. if (node.jointName === jointName) {
  102619. return {
  102620. node: node,
  102621. id: nde
  102622. };
  102623. }
  102624. }
  102625. return null;
  102626. };
  102627. /**
  102628. * Checks if a nodes is in joints
  102629. */
  102630. var nodeIsInJoints = function (skins, id) {
  102631. for (var i = 0; i < skins.jointNames.length; i++) {
  102632. if (skins.jointNames[i] === id) {
  102633. return true;
  102634. }
  102635. }
  102636. return false;
  102637. };
  102638. /**
  102639. * Fills the nodes to root for bones and builds hierarchy
  102640. */
  102641. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  102642. // Creates nodes for root
  102643. for (var nde in gltfRuntime.nodes) {
  102644. var node = gltfRuntime.nodes[nde];
  102645. var id = nde;
  102646. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  102647. continue;
  102648. }
  102649. // Create node to root bone
  102650. var mat = configureBoneTransformation(node);
  102651. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  102652. bone.id = id;
  102653. nodesToRoot.push({ bone: bone, node: node, id: id });
  102654. }
  102655. // Parenting
  102656. for (var i = 0; i < nodesToRoot.length; i++) {
  102657. var nodeToRoot = nodesToRoot[i];
  102658. var children = nodeToRoot.node.children;
  102659. for (var j = 0; j < children.length; j++) {
  102660. var child = null;
  102661. for (var k = 0; k < nodesToRoot.length; k++) {
  102662. if (nodesToRoot[k].id === children[j]) {
  102663. child = nodesToRoot[k];
  102664. break;
  102665. }
  102666. }
  102667. if (child) {
  102668. child.bone._parent = nodeToRoot.bone;
  102669. nodeToRoot.bone.children.push(child.bone);
  102670. }
  102671. }
  102672. }
  102673. };
  102674. /**
  102675. * Imports a skeleton
  102676. */
  102677. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  102678. if (!newSkeleton) {
  102679. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  102680. }
  102681. if (!skins.babylonSkeleton) {
  102682. return newSkeleton;
  102683. }
  102684. // Find the root bones
  102685. var nodesToRoot = [];
  102686. var nodesToRootToAdd = [];
  102687. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  102688. newSkeleton.bones = [];
  102689. // Joints
  102690. for (var i = 0; i < skins.jointNames.length; i++) {
  102691. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102692. if (!jointNode) {
  102693. continue;
  102694. }
  102695. var node = jointNode.node;
  102696. if (!node) {
  102697. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  102698. continue;
  102699. }
  102700. var id = jointNode.id;
  102701. // Optimize, if the bone already exists...
  102702. var existingBone = gltfRuntime.scene.getBoneByID(id);
  102703. if (existingBone) {
  102704. newSkeleton.bones.push(existingBone);
  102705. continue;
  102706. }
  102707. // Search for parent bone
  102708. var foundBone = false;
  102709. var parentBone = null;
  102710. for (var j = 0; j < i; j++) {
  102711. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  102712. if (!jointNode_1) {
  102713. continue;
  102714. }
  102715. var joint = jointNode_1.node;
  102716. if (!joint) {
  102717. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  102718. continue;
  102719. }
  102720. var children = joint.children;
  102721. if (!children) {
  102722. continue;
  102723. }
  102724. foundBone = false;
  102725. for (var k = 0; k < children.length; k++) {
  102726. if (children[k] === id) {
  102727. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  102728. foundBone = true;
  102729. break;
  102730. }
  102731. }
  102732. if (foundBone) {
  102733. break;
  102734. }
  102735. }
  102736. // Create bone
  102737. var mat = configureBoneTransformation(node);
  102738. if (!parentBone && nodesToRoot.length > 0) {
  102739. parentBone = getNodeToRoot(nodesToRoot, id);
  102740. if (parentBone) {
  102741. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  102742. nodesToRootToAdd.push(parentBone);
  102743. }
  102744. }
  102745. }
  102746. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  102747. bone.id = id;
  102748. }
  102749. // Polish
  102750. var bones = newSkeleton.bones;
  102751. newSkeleton.bones = [];
  102752. for (var i = 0; i < skins.jointNames.length; i++) {
  102753. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102754. if (!jointNode) {
  102755. continue;
  102756. }
  102757. for (var j = 0; j < bones.length; j++) {
  102758. if (bones[j].id === jointNode.id) {
  102759. newSkeleton.bones.push(bones[j]);
  102760. break;
  102761. }
  102762. }
  102763. }
  102764. newSkeleton.prepare();
  102765. // Finish
  102766. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  102767. newSkeleton.bones.push(nodesToRootToAdd[i]);
  102768. }
  102769. return newSkeleton;
  102770. };
  102771. /**
  102772. * Imports a mesh and its geometries
  102773. */
  102774. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  102775. if (!newMesh) {
  102776. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102777. newMesh.id = id;
  102778. }
  102779. if (!node.babylonNode) {
  102780. return newMesh;
  102781. }
  102782. var subMaterials = [];
  102783. var vertexData = null;
  102784. var verticesStarts = new Array();
  102785. var verticesCounts = new Array();
  102786. var indexStarts = new Array();
  102787. var indexCounts = new Array();
  102788. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102789. var meshID = meshes[meshIndex];
  102790. var mesh = gltfRuntime.meshes[meshID];
  102791. if (!mesh) {
  102792. continue;
  102793. }
  102794. // Positions, normals and UVs
  102795. for (var i = 0; i < mesh.primitives.length; i++) {
  102796. // Temporary vertex data
  102797. var tempVertexData = new BABYLON.VertexData();
  102798. var primitive = mesh.primitives[i];
  102799. if (primitive.mode !== 4) {
  102800. // continue;
  102801. }
  102802. var attributes = primitive.attributes;
  102803. var accessor = null;
  102804. var buffer = null;
  102805. // Set positions, normal and uvs
  102806. for (var semantic in attributes) {
  102807. // Link accessor and buffer view
  102808. accessor = gltfRuntime.accessors[attributes[semantic]];
  102809. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102810. if (semantic === "NORMAL") {
  102811. tempVertexData.normals = new Float32Array(buffer.length);
  102812. tempVertexData.normals.set(buffer);
  102813. }
  102814. else if (semantic === "POSITION") {
  102815. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  102816. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  102817. for (var j = 0; j < buffer.length; j += 4) {
  102818. tempVertexData.positions[j] = buffer[j];
  102819. tempVertexData.positions[j + 1] = buffer[j + 1];
  102820. tempVertexData.positions[j + 2] = buffer[j + 2];
  102821. }
  102822. }
  102823. else {
  102824. tempVertexData.positions = new Float32Array(buffer.length);
  102825. tempVertexData.positions.set(buffer);
  102826. }
  102827. verticesCounts.push(tempVertexData.positions.length);
  102828. }
  102829. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  102830. var channel = Number(semantic.split("_")[1]);
  102831. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  102832. var uvs = new Float32Array(buffer.length);
  102833. uvs.set(buffer);
  102834. normalizeUVs(uvs);
  102835. tempVertexData.set(uvs, uvKind);
  102836. }
  102837. else if (semantic === "JOINT") {
  102838. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  102839. tempVertexData.matricesIndices.set(buffer);
  102840. }
  102841. else if (semantic === "WEIGHT") {
  102842. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  102843. tempVertexData.matricesWeights.set(buffer);
  102844. }
  102845. else if (semantic === "COLOR") {
  102846. tempVertexData.colors = new Float32Array(buffer.length);
  102847. tempVertexData.colors.set(buffer);
  102848. }
  102849. }
  102850. // Indices
  102851. accessor = gltfRuntime.accessors[primitive.indices];
  102852. if (accessor) {
  102853. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102854. tempVertexData.indices = new Int32Array(buffer.length);
  102855. tempVertexData.indices.set(buffer);
  102856. indexCounts.push(tempVertexData.indices.length);
  102857. }
  102858. else {
  102859. // Set indices on the fly
  102860. var indices = [];
  102861. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  102862. indices.push(j);
  102863. }
  102864. tempVertexData.indices = new Int32Array(indices);
  102865. indexCounts.push(tempVertexData.indices.length);
  102866. }
  102867. if (!vertexData) {
  102868. vertexData = tempVertexData;
  102869. }
  102870. else {
  102871. vertexData.merge(tempVertexData);
  102872. }
  102873. // Sub material
  102874. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  102875. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  102876. // Update vertices start and index start
  102877. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  102878. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  102879. }
  102880. }
  102881. var material;
  102882. if (subMaterials.length > 1) {
  102883. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  102884. material.subMaterials = subMaterials;
  102885. }
  102886. else {
  102887. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  102888. }
  102889. if (subMaterials.length === 1) {
  102890. material = subMaterials[0];
  102891. }
  102892. if (!newMesh.material) {
  102893. newMesh.material = material;
  102894. }
  102895. // Apply geometry
  102896. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  102897. newMesh.computeWorldMatrix(true);
  102898. // Apply submeshes
  102899. newMesh.subMeshes = [];
  102900. var index = 0;
  102901. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102902. var meshID = meshes[meshIndex];
  102903. var mesh = gltfRuntime.meshes[meshID];
  102904. if (!mesh) {
  102905. continue;
  102906. }
  102907. for (var i = 0; i < mesh.primitives.length; i++) {
  102908. if (mesh.primitives[i].mode !== 4) {
  102909. //continue;
  102910. }
  102911. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  102912. index++;
  102913. }
  102914. }
  102915. // Finish
  102916. return newMesh;
  102917. };
  102918. /**
  102919. * Configure node transformation from position, rotation and scaling
  102920. */
  102921. var configureNode = function (newNode, position, rotation, scaling) {
  102922. if (newNode.position) {
  102923. newNode.position = position;
  102924. }
  102925. if (newNode.rotationQuaternion || newNode.rotation) {
  102926. newNode.rotationQuaternion = rotation;
  102927. }
  102928. if (newNode.scaling) {
  102929. newNode.scaling = scaling;
  102930. }
  102931. };
  102932. /**
  102933. * Configures node from transformation matrix
  102934. */
  102935. var configureNodeFromMatrix = function (newNode, node, parent) {
  102936. if (node.matrix) {
  102937. var position = new BABYLON.Vector3(0, 0, 0);
  102938. var rotation = new BABYLON.Quaternion();
  102939. var scaling = new BABYLON.Vector3(0, 0, 0);
  102940. var mat = BABYLON.Matrix.FromArray(node.matrix);
  102941. mat.decompose(scaling, rotation, position);
  102942. configureNode(newNode, position, rotation, scaling);
  102943. }
  102944. else if (node.translation && node.rotation && node.scale) {
  102945. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  102946. }
  102947. newNode.computeWorldMatrix(true);
  102948. };
  102949. /**
  102950. * Imports a node
  102951. */
  102952. var importNode = function (gltfRuntime, node, id, parent) {
  102953. var lastNode = null;
  102954. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  102955. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  102956. return null;
  102957. }
  102958. }
  102959. // Meshes
  102960. if (node.skin) {
  102961. if (node.meshes) {
  102962. var skin = gltfRuntime.skins[node.skin];
  102963. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  102964. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  102965. if (newMesh.skeleton === null) {
  102966. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  102967. if (!skin.babylonSkeleton) {
  102968. skin.babylonSkeleton = newMesh.skeleton;
  102969. }
  102970. }
  102971. lastNode = newMesh;
  102972. }
  102973. }
  102974. else if (node.meshes) {
  102975. /**
  102976. * Improve meshes property
  102977. */
  102978. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  102979. lastNode = newMesh;
  102980. }
  102981. // Lights
  102982. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  102983. var light = gltfRuntime.lights[node.light];
  102984. if (light) {
  102985. if (light.type === "ambient") {
  102986. var ambienLight = light[light.type];
  102987. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102988. hemiLight.name = node.name || "";
  102989. if (ambienLight.color) {
  102990. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  102991. }
  102992. lastNode = hemiLight;
  102993. }
  102994. else if (light.type === "directional") {
  102995. var directionalLight = light[light.type];
  102996. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102997. dirLight.name = node.name || "";
  102998. if (directionalLight.color) {
  102999. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  103000. }
  103001. lastNode = dirLight;
  103002. }
  103003. else if (light.type === "point") {
  103004. var pointLight = light[light.type];
  103005. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  103006. ptLight.name = node.name || "";
  103007. if (pointLight.color) {
  103008. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  103009. }
  103010. lastNode = ptLight;
  103011. }
  103012. else if (light.type === "spot") {
  103013. var spotLight = light[light.type];
  103014. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  103015. spLight.name = node.name || "";
  103016. if (spotLight.color) {
  103017. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  103018. }
  103019. if (spotLight.fallOfAngle) {
  103020. spLight.angle = spotLight.fallOfAngle;
  103021. }
  103022. if (spotLight.fallOffExponent) {
  103023. spLight.exponent = spotLight.fallOffExponent;
  103024. }
  103025. lastNode = spLight;
  103026. }
  103027. }
  103028. }
  103029. // Cameras
  103030. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  103031. var camera = gltfRuntime.cameras[node.camera];
  103032. if (camera) {
  103033. if (camera.type === "orthographic") {
  103034. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  103035. orthoCamera.name = node.name || "";
  103036. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  103037. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  103038. lastNode = orthoCamera;
  103039. }
  103040. else if (camera.type === "perspective") {
  103041. var perspectiveCamera = camera[camera.type];
  103042. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  103043. persCamera.name = node.name || "";
  103044. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  103045. if (!perspectiveCamera.aspectRatio) {
  103046. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  103047. }
  103048. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  103049. persCamera.maxZ = perspectiveCamera.zfar;
  103050. persCamera.minZ = perspectiveCamera.znear;
  103051. }
  103052. lastNode = persCamera;
  103053. }
  103054. }
  103055. }
  103056. // Empty node
  103057. if (!node.jointName) {
  103058. if (node.babylonNode) {
  103059. return node.babylonNode;
  103060. }
  103061. else if (lastNode === null) {
  103062. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  103063. node.babylonNode = dummy;
  103064. lastNode = dummy;
  103065. }
  103066. }
  103067. if (lastNode !== null) {
  103068. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  103069. configureNodeFromMatrix(lastNode, node, parent);
  103070. }
  103071. else {
  103072. var translation = node.translation || [0, 0, 0];
  103073. var rotation = node.rotation || [0, 0, 0, 1];
  103074. var scale = node.scale || [1, 1, 1];
  103075. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  103076. }
  103077. lastNode.updateCache(true);
  103078. node.babylonNode = lastNode;
  103079. }
  103080. return lastNode;
  103081. };
  103082. /**
  103083. * Traverses nodes and creates them
  103084. */
  103085. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  103086. if (meshIncluded === void 0) { meshIncluded = false; }
  103087. var node = gltfRuntime.nodes[id];
  103088. var newNode = null;
  103089. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  103090. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  103091. meshIncluded = true;
  103092. }
  103093. else {
  103094. meshIncluded = false;
  103095. }
  103096. }
  103097. else {
  103098. meshIncluded = true;
  103099. }
  103100. if (!node.jointName && meshIncluded) {
  103101. newNode = importNode(gltfRuntime, node, id, parent);
  103102. if (newNode !== null) {
  103103. newNode.id = id;
  103104. newNode.parent = parent;
  103105. }
  103106. }
  103107. if (node.children) {
  103108. for (var i = 0; i < node.children.length; i++) {
  103109. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  103110. }
  103111. }
  103112. };
  103113. /**
  103114. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  103115. */
  103116. var postLoad = function (gltfRuntime) {
  103117. // Nodes
  103118. var currentScene = gltfRuntime.currentScene;
  103119. if (currentScene) {
  103120. for (var i = 0; i < currentScene.nodes.length; i++) {
  103121. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103122. }
  103123. }
  103124. else {
  103125. for (var thing in gltfRuntime.scenes) {
  103126. currentScene = gltfRuntime.scenes[thing];
  103127. for (var i = 0; i < currentScene.nodes.length; i++) {
  103128. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103129. }
  103130. }
  103131. }
  103132. // Set animations
  103133. loadAnimations(gltfRuntime);
  103134. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  103135. var skeleton = gltfRuntime.scene.skeletons[i];
  103136. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  103137. }
  103138. };
  103139. /**
  103140. * onBind shaderrs callback to set uniforms and matrices
  103141. */
  103142. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  103143. var materialValues = material.values || technique.parameters;
  103144. for (var unif in unTreatedUniforms) {
  103145. var uniform = unTreatedUniforms[unif];
  103146. var type = uniform.type;
  103147. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  103148. if (uniform.semantic && !uniform.source && !uniform.node) {
  103149. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  103150. }
  103151. else if (uniform.semantic && (uniform.source || uniform.node)) {
  103152. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  103153. if (source === null) {
  103154. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  103155. }
  103156. if (source === null) {
  103157. continue;
  103158. }
  103159. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  103160. }
  103161. }
  103162. else {
  103163. var value = materialValues[technique.uniforms[unif]];
  103164. if (!value) {
  103165. continue;
  103166. }
  103167. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  103168. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  103169. if (texture === null || texture === undefined) {
  103170. continue;
  103171. }
  103172. shaderMaterial.getEffect().setTexture(unif, texture);
  103173. }
  103174. else {
  103175. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  103176. }
  103177. }
  103178. }
  103179. onSuccess(shaderMaterial);
  103180. };
  103181. /**
  103182. * Prepare uniforms to send the only one time
  103183. * Loads the appropriate textures
  103184. */
  103185. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  103186. var materialValues = material.values || technique.parameters;
  103187. var techniqueUniforms = technique.uniforms;
  103188. /**
  103189. * Prepare values here (not matrices)
  103190. */
  103191. for (var unif in unTreatedUniforms) {
  103192. var uniform = unTreatedUniforms[unif];
  103193. var type = uniform.type;
  103194. var value = materialValues[techniqueUniforms[unif]];
  103195. if (value === undefined) {
  103196. // In case the value is the same for all materials
  103197. value = uniform.value;
  103198. }
  103199. if (!value) {
  103200. continue;
  103201. }
  103202. var onLoadTexture = function (uniformName) {
  103203. return function (texture) {
  103204. if (uniform.value && uniformName) {
  103205. // Static uniform
  103206. shaderMaterial.setTexture(uniformName, texture);
  103207. delete unTreatedUniforms[uniformName];
  103208. }
  103209. };
  103210. };
  103211. // Texture (sampler2D)
  103212. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  103213. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  103214. }
  103215. // Others
  103216. else {
  103217. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  103218. // Static uniform
  103219. delete unTreatedUniforms[unif];
  103220. }
  103221. }
  103222. }
  103223. };
  103224. /**
  103225. * Shader compilation failed
  103226. */
  103227. var onShaderCompileError = function (program, shaderMaterial, onError) {
  103228. return function (effect, error) {
  103229. shaderMaterial.dispose(true);
  103230. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  103231. };
  103232. };
  103233. /**
  103234. * Shader compilation success
  103235. */
  103236. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  103237. return function (_) {
  103238. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  103239. shaderMaterial.onBind = function (mesh) {
  103240. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  103241. };
  103242. };
  103243. };
  103244. /**
  103245. * Returns the appropriate uniform if already handled by babylon
  103246. */
  103247. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  103248. for (var unif in technique.uniforms) {
  103249. var uniform = technique.uniforms[unif];
  103250. var uniformParameter = technique.parameters[uniform];
  103251. if (tokenizer.currentIdentifier === unif) {
  103252. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  103253. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  103254. if (transformIndex !== -1) {
  103255. delete unTreatedUniforms[unif];
  103256. return babylonTransforms[transformIndex];
  103257. }
  103258. }
  103259. }
  103260. }
  103261. return tokenizer.currentIdentifier;
  103262. };
  103263. /**
  103264. * All shaders loaded. Create materials one by one
  103265. */
  103266. var importMaterials = function (gltfRuntime) {
  103267. // Create materials
  103268. for (var mat in gltfRuntime.materials) {
  103269. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  103270. }
  103271. };
  103272. /**
  103273. * Implementation of the base glTF spec
  103274. */
  103275. var GLTFLoaderBase = /** @class */ (function () {
  103276. function GLTFLoaderBase() {
  103277. }
  103278. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  103279. var gltfRuntime = {
  103280. extensions: {},
  103281. accessors: {},
  103282. buffers: {},
  103283. bufferViews: {},
  103284. meshes: {},
  103285. lights: {},
  103286. cameras: {},
  103287. nodes: {},
  103288. images: {},
  103289. textures: {},
  103290. shaders: {},
  103291. programs: {},
  103292. samplers: {},
  103293. techniques: {},
  103294. materials: {},
  103295. animations: {},
  103296. skins: {},
  103297. extensionsUsed: [],
  103298. scenes: {},
  103299. buffersCount: 0,
  103300. shaderscount: 0,
  103301. scene: scene,
  103302. rootUrl: rootUrl,
  103303. loadedBufferCount: 0,
  103304. loadedBufferViews: {},
  103305. loadedShaderCount: 0,
  103306. importOnlyMeshes: false,
  103307. dummyNodes: []
  103308. };
  103309. // Parse
  103310. if (parsedData.extensions) {
  103311. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  103312. }
  103313. if (parsedData.extensionsUsed) {
  103314. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  103315. }
  103316. if (parsedData.buffers) {
  103317. parseBuffers(parsedData.buffers, gltfRuntime);
  103318. }
  103319. if (parsedData.bufferViews) {
  103320. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  103321. }
  103322. if (parsedData.accessors) {
  103323. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  103324. }
  103325. if (parsedData.meshes) {
  103326. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  103327. }
  103328. if (parsedData.lights) {
  103329. parseObject(parsedData.lights, "lights", gltfRuntime);
  103330. }
  103331. if (parsedData.cameras) {
  103332. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  103333. }
  103334. if (parsedData.nodes) {
  103335. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  103336. }
  103337. if (parsedData.images) {
  103338. parseObject(parsedData.images, "images", gltfRuntime);
  103339. }
  103340. if (parsedData.textures) {
  103341. parseObject(parsedData.textures, "textures", gltfRuntime);
  103342. }
  103343. if (parsedData.shaders) {
  103344. parseShaders(parsedData.shaders, gltfRuntime);
  103345. }
  103346. if (parsedData.programs) {
  103347. parseObject(parsedData.programs, "programs", gltfRuntime);
  103348. }
  103349. if (parsedData.samplers) {
  103350. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  103351. }
  103352. if (parsedData.techniques) {
  103353. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  103354. }
  103355. if (parsedData.materials) {
  103356. parseObject(parsedData.materials, "materials", gltfRuntime);
  103357. }
  103358. if (parsedData.animations) {
  103359. parseObject(parsedData.animations, "animations", gltfRuntime);
  103360. }
  103361. if (parsedData.skins) {
  103362. parseObject(parsedData.skins, "skins", gltfRuntime);
  103363. }
  103364. if (parsedData.scenes) {
  103365. gltfRuntime.scenes = parsedData.scenes;
  103366. }
  103367. if (parsedData.scene && parsedData.scenes) {
  103368. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  103369. }
  103370. return gltfRuntime;
  103371. };
  103372. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103373. var buffer = gltfRuntime.buffers[id];
  103374. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  103375. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  103376. }
  103377. else {
  103378. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  103379. if (request) {
  103380. onError(request.status + " " + request.statusText);
  103381. }
  103382. });
  103383. }
  103384. };
  103385. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103386. var texture = gltfRuntime.textures[id];
  103387. if (!texture || !texture.source) {
  103388. onError("");
  103389. return;
  103390. }
  103391. if (texture.babylonTexture) {
  103392. onSuccess(null);
  103393. return;
  103394. }
  103395. var source = gltfRuntime.images[texture.source];
  103396. if (BABYLON.Tools.IsBase64(source.uri)) {
  103397. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  103398. }
  103399. else {
  103400. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  103401. if (request) {
  103402. onError(request.status + " " + request.statusText);
  103403. }
  103404. });
  103405. }
  103406. };
  103407. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103408. var texture = gltfRuntime.textures[id];
  103409. if (texture.babylonTexture) {
  103410. onSuccess(texture.babylonTexture);
  103411. return;
  103412. }
  103413. var sampler = gltfRuntime.samplers[texture.sampler];
  103414. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  103415. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  103416. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  103417. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  103418. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  103419. var blob = new Blob([buffer]);
  103420. var blobURL = URL.createObjectURL(blob);
  103421. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  103422. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  103423. if (sampler.wrapS !== undefined) {
  103424. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  103425. }
  103426. if (sampler.wrapT !== undefined) {
  103427. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  103428. }
  103429. newTexture.name = id;
  103430. texture.babylonTexture = newTexture;
  103431. onSuccess(newTexture);
  103432. };
  103433. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103434. var shader = gltfRuntime.shaders[id];
  103435. if (BABYLON.Tools.IsBase64(shader.uri)) {
  103436. var shaderString = atob(shader.uri.split(",")[1]);
  103437. if (onSuccess) {
  103438. onSuccess(shaderString);
  103439. }
  103440. }
  103441. else {
  103442. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  103443. if (request && onError) {
  103444. onError(request.status + " " + request.statusText);
  103445. }
  103446. });
  103447. }
  103448. };
  103449. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103450. var material = gltfRuntime.materials[id];
  103451. if (!material.technique) {
  103452. if (onError) {
  103453. onError("No technique found.");
  103454. }
  103455. return;
  103456. }
  103457. var technique = gltfRuntime.techniques[material.technique];
  103458. if (!technique) {
  103459. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  103460. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  103461. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103462. onSuccess(defaultMaterial);
  103463. return;
  103464. }
  103465. var program = gltfRuntime.programs[technique.program];
  103466. var states = technique.states;
  103467. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  103468. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  103469. var newVertexShader = "";
  103470. var newPixelShader = "";
  103471. var vertexTokenizer = new Tokenizer(vertexShader);
  103472. var pixelTokenizer = new Tokenizer(pixelShader);
  103473. var unTreatedUniforms = {};
  103474. var uniforms = [];
  103475. var attributes = [];
  103476. var samplers = [];
  103477. // Fill uniform, sampler2D and attributes
  103478. for (var unif in technique.uniforms) {
  103479. var uniform = technique.uniforms[unif];
  103480. var uniformParameter = technique.parameters[uniform];
  103481. unTreatedUniforms[unif] = uniformParameter;
  103482. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  103483. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  103484. if (transformIndex !== -1) {
  103485. uniforms.push(babylonTransforms[transformIndex]);
  103486. delete unTreatedUniforms[unif];
  103487. }
  103488. else {
  103489. uniforms.push(unif);
  103490. }
  103491. }
  103492. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  103493. samplers.push(unif);
  103494. }
  103495. else {
  103496. uniforms.push(unif);
  103497. }
  103498. }
  103499. for (var attr in technique.attributes) {
  103500. var attribute = technique.attributes[attr];
  103501. var attributeParameter = technique.parameters[attribute];
  103502. if (attributeParameter.semantic) {
  103503. attributes.push(getAttribute(attributeParameter));
  103504. }
  103505. }
  103506. // Configure vertex shader
  103507. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  103508. var tokenType = vertexTokenizer.currentToken;
  103509. if (tokenType !== ETokenType.IDENTIFIER) {
  103510. newVertexShader += vertexTokenizer.currentString;
  103511. continue;
  103512. }
  103513. var foundAttribute = false;
  103514. for (var attr in technique.attributes) {
  103515. var attribute = technique.attributes[attr];
  103516. var attributeParameter = technique.parameters[attribute];
  103517. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  103518. newVertexShader += getAttribute(attributeParameter);
  103519. foundAttribute = true;
  103520. break;
  103521. }
  103522. }
  103523. if (foundAttribute) {
  103524. continue;
  103525. }
  103526. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  103527. }
  103528. // Configure pixel shader
  103529. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  103530. var tokenType = pixelTokenizer.currentToken;
  103531. if (tokenType !== ETokenType.IDENTIFIER) {
  103532. newPixelShader += pixelTokenizer.currentString;
  103533. continue;
  103534. }
  103535. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  103536. }
  103537. // Create shader material
  103538. var shaderPath = {
  103539. vertex: program.vertexShader + id,
  103540. fragment: program.fragmentShader + id
  103541. };
  103542. var options = {
  103543. attributes: attributes,
  103544. uniforms: uniforms,
  103545. samplers: samplers,
  103546. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  103547. };
  103548. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  103549. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  103550. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  103551. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  103552. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  103553. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103554. if (states && states.functions) {
  103555. var functions = states.functions;
  103556. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  103557. shaderMaterial.backFaceCulling = false;
  103558. }
  103559. var blendFunc = functions.blendFuncSeparate;
  103560. if (blendFunc) {
  103561. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103562. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  103563. }
  103564. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103565. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  103566. }
  103567. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103568. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  103569. }
  103570. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103571. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  103572. }
  103573. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103574. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  103575. }
  103576. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103577. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  103578. }
  103579. }
  103580. }
  103581. };
  103582. return GLTFLoaderBase;
  103583. }());
  103584. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  103585. /**
  103586. * glTF V1 Loader
  103587. */
  103588. var GLTFLoader = /** @class */ (function () {
  103589. function GLTFLoader() {
  103590. // #region Stubs for IGLTFLoader interface
  103591. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  103592. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  103593. this.compileMaterials = false;
  103594. this.useClipPlane = false;
  103595. this.compileShadowGenerators = false;
  103596. this.transparencyAsCoverage = false;
  103597. this._normalizeAnimationGroupsToBeginAtZero = true;
  103598. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  103599. this.onMeshLoadedObservable = new BABYLON.Observable();
  103600. this.onTextureLoadedObservable = new BABYLON.Observable();
  103601. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103602. this.onCameraLoadedObservable = new BABYLON.Observable();
  103603. this.onCompleteObservable = new BABYLON.Observable();
  103604. this.onDisposeObservable = new BABYLON.Observable();
  103605. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103606. this.state = null;
  103607. }
  103608. GLTFLoader.RegisterExtension = function (extension) {
  103609. if (GLTFLoader.Extensions[extension.name]) {
  103610. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  103611. return;
  103612. }
  103613. GLTFLoader.Extensions[extension.name] = extension;
  103614. };
  103615. GLTFLoader.prototype.dispose = function () { };
  103616. // #endregion
  103617. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  103618. var _this = this;
  103619. scene.useRightHandedSystem = true;
  103620. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103621. gltfRuntime.importOnlyMeshes = true;
  103622. if (meshesNames === "") {
  103623. gltfRuntime.importMeshesNames = [];
  103624. }
  103625. else if (typeof meshesNames === "string") {
  103626. gltfRuntime.importMeshesNames = [meshesNames];
  103627. }
  103628. else if (meshesNames && !(meshesNames instanceof Array)) {
  103629. gltfRuntime.importMeshesNames = [meshesNames];
  103630. }
  103631. else {
  103632. gltfRuntime.importMeshesNames = [];
  103633. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  103634. }
  103635. // Create nodes
  103636. _this._createNodes(gltfRuntime);
  103637. var meshes = new Array();
  103638. var skeletons = new Array();
  103639. // Fill arrays of meshes and skeletons
  103640. for (var nde in gltfRuntime.nodes) {
  103641. var node = gltfRuntime.nodes[nde];
  103642. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  103643. meshes.push(node.babylonNode);
  103644. }
  103645. }
  103646. for (var skl in gltfRuntime.skins) {
  103647. var skin = gltfRuntime.skins[skl];
  103648. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  103649. skeletons.push(skin.babylonSkeleton);
  103650. }
  103651. }
  103652. // Load buffers, shaders, materials, etc.
  103653. _this._loadBuffersAsync(gltfRuntime, function () {
  103654. _this._loadShadersAsync(gltfRuntime, function () {
  103655. importMaterials(gltfRuntime);
  103656. postLoad(gltfRuntime);
  103657. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103658. onSuccess(meshes, skeletons);
  103659. }
  103660. });
  103661. }, onProgress);
  103662. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103663. onSuccess(meshes, skeletons);
  103664. }
  103665. }, onError);
  103666. return true;
  103667. };
  103668. /**
  103669. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  103670. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  103671. * @param scene the scene the meshes should be added to
  103672. * @param data gltf data containing information of the meshes in a loaded file
  103673. * @param rootUrl root url to load from
  103674. * @param onProgress event that fires when loading progress has occured
  103675. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  103676. */
  103677. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103678. var _this = this;
  103679. return new Promise(function (resolve, reject) {
  103680. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  103681. resolve({
  103682. meshes: meshes,
  103683. particleSystems: [],
  103684. skeletons: skeletons,
  103685. animationGroups: []
  103686. });
  103687. }, onProgress, function (message) {
  103688. reject(new Error(message));
  103689. });
  103690. });
  103691. };
  103692. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  103693. var _this = this;
  103694. scene.useRightHandedSystem = true;
  103695. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103696. // Load runtime extensios
  103697. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  103698. // Create nodes
  103699. _this._createNodes(gltfRuntime);
  103700. // Load buffers, shaders, materials, etc.
  103701. _this._loadBuffersAsync(gltfRuntime, function () {
  103702. _this._loadShadersAsync(gltfRuntime, function () {
  103703. importMaterials(gltfRuntime);
  103704. postLoad(gltfRuntime);
  103705. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  103706. onSuccess();
  103707. }
  103708. });
  103709. });
  103710. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  103711. onSuccess();
  103712. }
  103713. }, onError);
  103714. }, onError);
  103715. };
  103716. /**
  103717. * Imports all objects from a loaded gltf file and adds them to the scene
  103718. * @param scene the scene the objects should be added to
  103719. * @param data gltf data containing information of the meshes in a loaded file
  103720. * @param rootUrl root url to load from
  103721. * @param onProgress event that fires when loading progress has occured
  103722. * @returns a promise which completes when objects have been loaded to the scene
  103723. */
  103724. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103725. var _this = this;
  103726. return new Promise(function (resolve, reject) {
  103727. _this._loadAsync(scene, data, rootUrl, function () {
  103728. resolve();
  103729. }, onProgress, function (message) {
  103730. reject(new Error(message));
  103731. });
  103732. });
  103733. };
  103734. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  103735. var hasShaders = false;
  103736. var processShader = function (sha, shader) {
  103737. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  103738. if (shaderString instanceof ArrayBuffer) {
  103739. return;
  103740. }
  103741. gltfRuntime.loadedShaderCount++;
  103742. if (shaderString) {
  103743. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  103744. }
  103745. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  103746. onload();
  103747. }
  103748. }, function () {
  103749. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  103750. });
  103751. };
  103752. for (var sha in gltfRuntime.shaders) {
  103753. hasShaders = true;
  103754. var shader = gltfRuntime.shaders[sha];
  103755. if (shader) {
  103756. processShader.bind(this, sha, shader)();
  103757. }
  103758. else {
  103759. BABYLON.Tools.Error("No shader named: " + sha);
  103760. }
  103761. }
  103762. if (!hasShaders) {
  103763. onload();
  103764. }
  103765. };
  103766. ;
  103767. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  103768. var hasBuffers = false;
  103769. var processBuffer = function (buf, buffer) {
  103770. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  103771. gltfRuntime.loadedBufferCount++;
  103772. if (bufferView) {
  103773. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  103774. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  103775. }
  103776. gltfRuntime.loadedBufferViews[buf] = bufferView;
  103777. }
  103778. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  103779. onLoad();
  103780. }
  103781. }, function () {
  103782. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  103783. });
  103784. };
  103785. for (var buf in gltfRuntime.buffers) {
  103786. hasBuffers = true;
  103787. var buffer = gltfRuntime.buffers[buf];
  103788. if (buffer) {
  103789. processBuffer.bind(this, buf, buffer)();
  103790. }
  103791. else {
  103792. BABYLON.Tools.Error("No buffer named: " + buf);
  103793. }
  103794. }
  103795. if (!hasBuffers) {
  103796. onLoad();
  103797. }
  103798. };
  103799. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  103800. var currentScene = gltfRuntime.currentScene;
  103801. if (currentScene) {
  103802. // Only one scene even if multiple scenes are defined
  103803. for (var i = 0; i < currentScene.nodes.length; i++) {
  103804. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103805. }
  103806. }
  103807. else {
  103808. // Load all scenes
  103809. for (var thing in gltfRuntime.scenes) {
  103810. currentScene = gltfRuntime.scenes[thing];
  103811. for (var i = 0; i < currentScene.nodes.length; i++) {
  103812. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103813. }
  103814. }
  103815. }
  103816. };
  103817. GLTFLoader.Extensions = {};
  103818. return GLTFLoader;
  103819. }());
  103820. GLTF1.GLTFLoader = GLTFLoader;
  103821. ;
  103822. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  103823. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103824. })(BABYLON || (BABYLON = {}));
  103825. //# sourceMappingURL=babylon.glTFLoader.js.map
  103826. var BABYLON;
  103827. (function (BABYLON) {
  103828. var GLTF1;
  103829. (function (GLTF1) {
  103830. /**
  103831. * Utils functions for GLTF
  103832. */
  103833. var GLTFUtils = /** @class */ (function () {
  103834. function GLTFUtils() {
  103835. }
  103836. /**
  103837. * Sets the given "parameter" matrix
  103838. * @param scene: the {BABYLON.Scene} object
  103839. * @param source: the source node where to pick the matrix
  103840. * @param parameter: the GLTF technique parameter
  103841. * @param uniformName: the name of the shader's uniform
  103842. * @param shaderMaterial: the shader material
  103843. */
  103844. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  103845. var mat = null;
  103846. if (parameter.semantic === "MODEL") {
  103847. mat = source.getWorldMatrix();
  103848. }
  103849. else if (parameter.semantic === "PROJECTION") {
  103850. mat = scene.getProjectionMatrix();
  103851. }
  103852. else if (parameter.semantic === "VIEW") {
  103853. mat = scene.getViewMatrix();
  103854. }
  103855. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  103856. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  103857. }
  103858. else if (parameter.semantic === "MODELVIEW") {
  103859. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  103860. }
  103861. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  103862. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  103863. }
  103864. else if (parameter.semantic === "MODELINVERSE") {
  103865. mat = source.getWorldMatrix().invert();
  103866. }
  103867. else if (parameter.semantic === "VIEWINVERSE") {
  103868. mat = scene.getViewMatrix().invert();
  103869. }
  103870. else if (parameter.semantic === "PROJECTIONINVERSE") {
  103871. mat = scene.getProjectionMatrix().invert();
  103872. }
  103873. else if (parameter.semantic === "MODELVIEWINVERSE") {
  103874. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  103875. }
  103876. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  103877. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  103878. }
  103879. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  103880. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  103881. }
  103882. else {
  103883. debugger;
  103884. }
  103885. if (mat) {
  103886. switch (parameter.type) {
  103887. case GLTF1.EParameterType.FLOAT_MAT2:
  103888. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  103889. break;
  103890. case GLTF1.EParameterType.FLOAT_MAT3:
  103891. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  103892. break;
  103893. case GLTF1.EParameterType.FLOAT_MAT4:
  103894. shaderMaterial.setMatrix(uniformName, mat);
  103895. break;
  103896. default: break;
  103897. }
  103898. }
  103899. };
  103900. /**
  103901. * Sets the given "parameter" matrix
  103902. * @param shaderMaterial: the shader material
  103903. * @param uniform: the name of the shader's uniform
  103904. * @param value: the value of the uniform
  103905. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  103906. */
  103907. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  103908. switch (type) {
  103909. case GLTF1.EParameterType.FLOAT:
  103910. shaderMaterial.setFloat(uniform, value);
  103911. return true;
  103912. case GLTF1.EParameterType.FLOAT_VEC2:
  103913. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  103914. return true;
  103915. case GLTF1.EParameterType.FLOAT_VEC3:
  103916. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  103917. return true;
  103918. case GLTF1.EParameterType.FLOAT_VEC4:
  103919. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  103920. return true;
  103921. default: return false;
  103922. }
  103923. };
  103924. /**
  103925. * Returns the wrap mode of the texture
  103926. * @param mode: the mode value
  103927. */
  103928. GLTFUtils.GetWrapMode = function (mode) {
  103929. switch (mode) {
  103930. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  103931. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  103932. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103933. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103934. }
  103935. };
  103936. /**
  103937. * Returns the byte stride giving an accessor
  103938. * @param accessor: the GLTF accessor objet
  103939. */
  103940. GLTFUtils.GetByteStrideFromType = function (accessor) {
  103941. // Needs this function since "byteStride" isn't requiered in glTF format
  103942. var type = accessor.type;
  103943. switch (type) {
  103944. case "VEC2": return 2;
  103945. case "VEC3": return 3;
  103946. case "VEC4": return 4;
  103947. case "MAT2": return 4;
  103948. case "MAT3": return 9;
  103949. case "MAT4": return 16;
  103950. default: return 1;
  103951. }
  103952. };
  103953. /**
  103954. * Returns the texture filter mode giving a mode value
  103955. * @param mode: the filter mode value
  103956. */
  103957. GLTFUtils.GetTextureFilterMode = function (mode) {
  103958. switch (mode) {
  103959. case GLTF1.ETextureFilterType.LINEAR:
  103960. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  103961. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  103962. case GLTF1.ETextureFilterType.NEAREST:
  103963. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  103964. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  103965. }
  103966. };
  103967. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  103968. var byteOffset = bufferView.byteOffset + byteOffset;
  103969. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  103970. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  103971. throw new Error("Buffer access is out of range");
  103972. }
  103973. var buffer = loadedBufferView.buffer;
  103974. byteOffset += loadedBufferView.byteOffset;
  103975. switch (componentType) {
  103976. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  103977. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  103978. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  103979. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  103980. default: return new Float32Array(buffer, byteOffset, byteLength);
  103981. }
  103982. };
  103983. /**
  103984. * Returns a buffer from its accessor
  103985. * @param gltfRuntime: the GLTF runtime
  103986. * @param accessor: the GLTF accessor
  103987. */
  103988. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  103989. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  103990. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  103991. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  103992. };
  103993. /**
  103994. * Decodes a buffer view into a string
  103995. * @param view: the buffer view
  103996. */
  103997. GLTFUtils.DecodeBufferToText = function (view) {
  103998. var result = "";
  103999. var length = view.byteLength;
  104000. for (var i = 0; i < length; ++i) {
  104001. result += String.fromCharCode(view[i]);
  104002. }
  104003. return result;
  104004. };
  104005. /**
  104006. * Returns the default material of gltf. Related to
  104007. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  104008. * @param scene: the Babylon.js scene
  104009. */
  104010. GLTFUtils.GetDefaultMaterial = function (scene) {
  104011. if (!GLTFUtils._DefaultMaterial) {
  104012. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  104013. "precision highp float;",
  104014. "",
  104015. "uniform mat4 worldView;",
  104016. "uniform mat4 projection;",
  104017. "",
  104018. "attribute vec3 position;",
  104019. "",
  104020. "void main(void)",
  104021. "{",
  104022. " gl_Position = projection * worldView * vec4(position, 1.0);",
  104023. "}"
  104024. ].join("\n");
  104025. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  104026. "precision highp float;",
  104027. "",
  104028. "uniform vec4 u_emission;",
  104029. "",
  104030. "void main(void)",
  104031. "{",
  104032. " gl_FragColor = u_emission;",
  104033. "}"
  104034. ].join("\n");
  104035. var shaderPath = {
  104036. vertex: "GLTFDefaultMaterial",
  104037. fragment: "GLTFDefaultMaterial"
  104038. };
  104039. var options = {
  104040. attributes: ["position"],
  104041. uniforms: ["worldView", "projection", "u_emission"],
  104042. samplers: new Array(),
  104043. needAlphaBlending: false
  104044. };
  104045. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  104046. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  104047. }
  104048. return GLTFUtils._DefaultMaterial;
  104049. };
  104050. // The GLTF default material
  104051. GLTFUtils._DefaultMaterial = null;
  104052. return GLTFUtils;
  104053. }());
  104054. GLTF1.GLTFUtils = GLTFUtils;
  104055. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104056. })(BABYLON || (BABYLON = {}));
  104057. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  104058. var BABYLON;
  104059. (function (BABYLON) {
  104060. var GLTF1;
  104061. (function (GLTF1) {
  104062. var GLTFLoaderExtension = /** @class */ (function () {
  104063. function GLTFLoaderExtension(name) {
  104064. this._name = name;
  104065. }
  104066. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  104067. get: function () {
  104068. return this._name;
  104069. },
  104070. enumerable: true,
  104071. configurable: true
  104072. });
  104073. /**
  104074. * Defines an override for loading the runtime
  104075. * Return true to stop further extensions from loading the runtime
  104076. */
  104077. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104078. return false;
  104079. };
  104080. /**
  104081. * Defines an onverride for creating gltf runtime
  104082. * Return true to stop further extensions from creating the runtime
  104083. */
  104084. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104085. return false;
  104086. };
  104087. /**
  104088. * Defines an override for loading buffers
  104089. * Return true to stop further extensions from loading this buffer
  104090. */
  104091. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104092. return false;
  104093. };
  104094. /**
  104095. * Defines an override for loading texture buffers
  104096. * Return true to stop further extensions from loading this texture data
  104097. */
  104098. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104099. return false;
  104100. };
  104101. /**
  104102. * Defines an override for creating textures
  104103. * Return true to stop further extensions from loading this texture
  104104. */
  104105. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104106. return false;
  104107. };
  104108. /**
  104109. * Defines an override for loading shader strings
  104110. * Return true to stop further extensions from loading this shader data
  104111. */
  104112. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104113. return false;
  104114. };
  104115. /**
  104116. * Defines an override for loading materials
  104117. * Return true to stop further extensions from loading this material
  104118. */
  104119. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104120. return false;
  104121. };
  104122. // ---------
  104123. // Utilities
  104124. // ---------
  104125. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104126. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104127. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  104128. }, function () {
  104129. setTimeout(function () {
  104130. if (!onSuccess) {
  104131. return;
  104132. }
  104133. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  104134. });
  104135. });
  104136. };
  104137. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104138. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104139. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  104140. }, function () {
  104141. setTimeout(function () {
  104142. onSuccess();
  104143. });
  104144. });
  104145. };
  104146. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104147. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104148. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  104149. }, function () {
  104150. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  104151. });
  104152. };
  104153. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  104154. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  104155. if (buffer) {
  104156. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104157. }
  104158. }, onError);
  104159. };
  104160. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104161. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104162. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  104163. }, function () {
  104164. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  104165. });
  104166. };
  104167. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104168. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104169. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  104170. }, function () {
  104171. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  104172. });
  104173. };
  104174. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104175. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104176. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  104177. }, function () {
  104178. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  104179. });
  104180. };
  104181. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104182. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104183. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104184. }, function () {
  104185. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104186. });
  104187. };
  104188. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  104189. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  104190. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  104191. if (func(loaderExtension)) {
  104192. return;
  104193. }
  104194. }
  104195. defaultFunc();
  104196. };
  104197. return GLTFLoaderExtension;
  104198. }());
  104199. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  104200. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104201. })(BABYLON || (BABYLON = {}));
  104202. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  104203. var BABYLON;
  104204. (function (BABYLON) {
  104205. var GLTF1;
  104206. (function (GLTF1) {
  104207. var BinaryExtensionBufferName = "binary_glTF";
  104208. ;
  104209. ;
  104210. var GLTFBinaryExtension = /** @class */ (function (_super) {
  104211. __extends(GLTFBinaryExtension, _super);
  104212. function GLTFBinaryExtension() {
  104213. return _super.call(this, "KHR_binary_glTF") || this;
  104214. }
  104215. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104216. var extensionsUsed = data.json.extensionsUsed;
  104217. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  104218. return false;
  104219. }
  104220. this._bin = data.bin;
  104221. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  104222. return true;
  104223. };
  104224. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104225. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  104226. return false;
  104227. }
  104228. if (id !== BinaryExtensionBufferName) {
  104229. return false;
  104230. }
  104231. onSuccess(this._bin);
  104232. return true;
  104233. };
  104234. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104235. var texture = gltfRuntime.textures[id];
  104236. var source = gltfRuntime.images[texture.source];
  104237. if (!source.extensions || !(this.name in source.extensions)) {
  104238. return false;
  104239. }
  104240. var sourceExt = source.extensions[this.name];
  104241. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  104242. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  104243. onSuccess(buffer);
  104244. return true;
  104245. };
  104246. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104247. var shader = gltfRuntime.shaders[id];
  104248. if (!shader.extensions || !(this.name in shader.extensions)) {
  104249. return false;
  104250. }
  104251. var binaryExtensionShader = shader.extensions[this.name];
  104252. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  104253. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  104254. setTimeout(function () {
  104255. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  104256. onSuccess(shaderString);
  104257. });
  104258. return true;
  104259. };
  104260. return GLTFBinaryExtension;
  104261. }(GLTF1.GLTFLoaderExtension));
  104262. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  104263. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  104264. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104265. })(BABYLON || (BABYLON = {}));
  104266. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  104267. var BABYLON;
  104268. (function (BABYLON) {
  104269. var GLTF1;
  104270. (function (GLTF1) {
  104271. ;
  104272. ;
  104273. ;
  104274. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  104275. __extends(GLTFMaterialsCommonExtension, _super);
  104276. function GLTFMaterialsCommonExtension() {
  104277. return _super.call(this, "KHR_materials_common") || this;
  104278. }
  104279. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104280. if (!gltfRuntime.extensions)
  104281. return false;
  104282. var extension = gltfRuntime.extensions[this.name];
  104283. if (!extension)
  104284. return false;
  104285. // Create lights
  104286. var lights = extension.lights;
  104287. if (lights) {
  104288. for (var thing in lights) {
  104289. var light = lights[thing];
  104290. switch (light.type) {
  104291. case "ambient":
  104292. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  104293. var ambient = light.ambient;
  104294. if (ambient) {
  104295. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  104296. }
  104297. break;
  104298. case "point":
  104299. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  104300. var point = light.point;
  104301. if (point) {
  104302. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  104303. }
  104304. break;
  104305. case "directional":
  104306. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  104307. var directional = light.directional;
  104308. if (directional) {
  104309. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  104310. }
  104311. break;
  104312. case "spot":
  104313. var spot = light.spot;
  104314. if (spot) {
  104315. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  104316. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  104317. }
  104318. break;
  104319. default:
  104320. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  104321. break;
  104322. }
  104323. }
  104324. }
  104325. return false;
  104326. };
  104327. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104328. var material = gltfRuntime.materials[id];
  104329. if (!material || !material.extensions)
  104330. return false;
  104331. var extension = material.extensions[this.name];
  104332. if (!extension)
  104333. return false;
  104334. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  104335. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  104336. if (extension.technique === "CONSTANT") {
  104337. standardMaterial.disableLighting = true;
  104338. }
  104339. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  104340. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  104341. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  104342. // Ambient
  104343. if (typeof extension.values.ambient === "string") {
  104344. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  104345. }
  104346. else {
  104347. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  104348. }
  104349. // Diffuse
  104350. if (typeof extension.values.diffuse === "string") {
  104351. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  104352. }
  104353. else {
  104354. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  104355. }
  104356. // Emission
  104357. if (typeof extension.values.emission === "string") {
  104358. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  104359. }
  104360. else {
  104361. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  104362. }
  104363. // Specular
  104364. if (typeof extension.values.specular === "string") {
  104365. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  104366. }
  104367. else {
  104368. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  104369. }
  104370. return true;
  104371. };
  104372. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  104373. // Create buffer from texture url
  104374. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  104375. // Create texture from buffer
  104376. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  104377. }, onError);
  104378. };
  104379. return GLTFMaterialsCommonExtension;
  104380. }(GLTF1.GLTFLoaderExtension));
  104381. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  104382. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  104383. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104384. })(BABYLON || (BABYLON = {}));
  104385. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  104386. var BABYLON;
  104387. (function (BABYLON) {
  104388. var GLTF2;
  104389. (function (GLTF2) {
  104390. /** @hidden */
  104391. var _ArrayItem = /** @class */ (function () {
  104392. function _ArrayItem() {
  104393. }
  104394. /** @hidden */
  104395. _ArrayItem.Assign = function (values) {
  104396. if (values) {
  104397. for (var index = 0; index < values.length; index++) {
  104398. values[index]._index = index;
  104399. }
  104400. }
  104401. };
  104402. return _ArrayItem;
  104403. }());
  104404. GLTF2._ArrayItem = _ArrayItem;
  104405. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104406. })(BABYLON || (BABYLON = {}));
  104407. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  104408. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  104409. /**
  104410. * Defines the module used to import/export glTF 2.0 assets
  104411. */
  104412. var BABYLON;
  104413. (function (BABYLON) {
  104414. var GLTF2;
  104415. (function (GLTF2) {
  104416. /**
  104417. * Loader for loading a glTF 2.0 asset
  104418. */
  104419. var GLTFLoader = /** @class */ (function () {
  104420. function GLTFLoader() {
  104421. /** @hidden */
  104422. this._completePromises = new Array();
  104423. this._disposed = false;
  104424. this._state = null;
  104425. this._extensions = {};
  104426. this._defaultSampler = {};
  104427. this._defaultBabylonMaterials = {};
  104428. this._requests = new Array();
  104429. /**
  104430. * Mode that determines the coordinate system to use.
  104431. */
  104432. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  104433. /**
  104434. * Mode that determines what animations will start.
  104435. */
  104436. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  104437. /**
  104438. * Defines if the loader should compile materials.
  104439. */
  104440. this.compileMaterials = false;
  104441. /**
  104442. * Defines if the loader should also compile materials with clip planes.
  104443. */
  104444. this.useClipPlane = false;
  104445. /**
  104446. * Defines if the loader should compile shadow generators.
  104447. */
  104448. this.compileShadowGenerators = false;
  104449. /**
  104450. * Defines if the Alpha blended materials are only applied as coverage.
  104451. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  104452. * If true, no extra effects are applied to transparent pixels.
  104453. */
  104454. this.transparencyAsCoverage = false;
  104455. /** @hidden */
  104456. this._normalizeAnimationGroupsToBeginAtZero = true;
  104457. /**
  104458. * Function called before loading a url referenced by the asset.
  104459. */
  104460. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104461. /**
  104462. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104463. */
  104464. this.onMeshLoadedObservable = new BABYLON.Observable();
  104465. /**
  104466. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  104467. */
  104468. this.onTextureLoadedObservable = new BABYLON.Observable();
  104469. /**
  104470. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  104471. */
  104472. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104473. /**
  104474. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  104475. */
  104476. this.onCameraLoadedObservable = new BABYLON.Observable();
  104477. /**
  104478. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  104479. * For assets with LODs, raised when all of the LODs are complete.
  104480. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  104481. */
  104482. this.onCompleteObservable = new BABYLON.Observable();
  104483. /**
  104484. * Observable raised after the loader is disposed.
  104485. */
  104486. this.onDisposeObservable = new BABYLON.Observable();
  104487. /**
  104488. * Observable raised after a loader extension is created.
  104489. * Set additional options for a loader extension in this event.
  104490. */
  104491. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104492. }
  104493. /** @hidden */
  104494. GLTFLoader._Register = function (name, factory) {
  104495. if (GLTFLoader._ExtensionFactories[name]) {
  104496. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  104497. return;
  104498. }
  104499. GLTFLoader._ExtensionFactories[name] = factory;
  104500. // Keep the order of registration so that extensions registered first are called first.
  104501. GLTFLoader._ExtensionNames.push(name);
  104502. };
  104503. Object.defineProperty(GLTFLoader.prototype, "state", {
  104504. /**
  104505. * Loader state or null if the loader is not active.
  104506. */
  104507. get: function () {
  104508. return this._state;
  104509. },
  104510. enumerable: true,
  104511. configurable: true
  104512. });
  104513. /**
  104514. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  104515. */
  104516. GLTFLoader.prototype.dispose = function () {
  104517. if (this._disposed) {
  104518. return;
  104519. }
  104520. this._disposed = true;
  104521. this.onDisposeObservable.notifyObservers(this);
  104522. this.onDisposeObservable.clear();
  104523. this._clear();
  104524. };
  104525. /**
  104526. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  104527. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  104528. * @param scene the scene the meshes should be added to
  104529. * @param data the glTF data to load
  104530. * @param rootUrl root url to load from
  104531. * @param onProgress event that fires when loading progress has occured
  104532. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  104533. */
  104534. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104535. var _this = this;
  104536. return Promise.resolve().then(function () {
  104537. var nodes = null;
  104538. if (meshesNames) {
  104539. var nodeMap_1 = {};
  104540. if (_this._gltf.nodes) {
  104541. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  104542. var node = _a[_i];
  104543. if (node.name) {
  104544. nodeMap_1[node.name] = node;
  104545. }
  104546. }
  104547. }
  104548. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  104549. nodes = names.map(function (name) {
  104550. var node = nodeMap_1[name];
  104551. if (!node) {
  104552. throw new Error("Failed to find node '" + name + "'");
  104553. }
  104554. return node;
  104555. });
  104556. }
  104557. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  104558. return {
  104559. meshes: _this._getMeshes(),
  104560. particleSystems: [],
  104561. skeletons: _this._getSkeletons(),
  104562. animationGroups: _this._getAnimationGroups()
  104563. };
  104564. });
  104565. });
  104566. };
  104567. /**
  104568. * Imports all objects from the loaded glTF data and adds them to the scene
  104569. * @param scene the scene the objects should be added to
  104570. * @param data the glTF data to load
  104571. * @param rootUrl root url to load from
  104572. * @param onProgress event that fires when loading progress has occured
  104573. * @returns a promise which completes when objects have been loaded to the scene
  104574. */
  104575. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104576. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  104577. };
  104578. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  104579. var _this = this;
  104580. return Promise.resolve().then(function () {
  104581. _this._babylonScene = scene;
  104582. _this._rootUrl = rootUrl;
  104583. _this._progressCallback = onProgress;
  104584. _this._state = BABYLON.GLTFLoaderState.LOADING;
  104585. _this._loadData(data);
  104586. _this._loadExtensions();
  104587. _this._checkExtensions();
  104588. var promises = new Array();
  104589. if (nodes) {
  104590. promises.push(_this._loadNodesAsync(nodes));
  104591. }
  104592. else {
  104593. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  104594. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  104595. }
  104596. if (_this.compileMaterials) {
  104597. promises.push(_this._compileMaterialsAsync());
  104598. }
  104599. if (_this.compileShadowGenerators) {
  104600. promises.push(_this._compileShadowGeneratorsAsync());
  104601. }
  104602. var resultPromise = Promise.all(promises).then(function () {
  104603. _this._state = BABYLON.GLTFLoaderState.READY;
  104604. _this._startAnimations();
  104605. });
  104606. resultPromise.then(function () {
  104607. _this._rootBabylonMesh.setEnabled(true);
  104608. BABYLON.Tools.SetImmediate(function () {
  104609. if (!_this._disposed) {
  104610. Promise.all(_this._completePromises).then(function () {
  104611. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  104612. _this.onCompleteObservable.notifyObservers(_this);
  104613. _this.onCompleteObservable.clear();
  104614. _this._clear();
  104615. }).catch(function (error) {
  104616. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104617. _this._clear();
  104618. });
  104619. }
  104620. });
  104621. });
  104622. return resultPromise;
  104623. }).catch(function (error) {
  104624. if (!_this._disposed) {
  104625. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104626. _this._clear();
  104627. throw error;
  104628. }
  104629. });
  104630. };
  104631. GLTFLoader.prototype._loadData = function (data) {
  104632. this._gltf = data.json;
  104633. this._setupData();
  104634. if (data.bin) {
  104635. var buffers = this._gltf.buffers;
  104636. if (buffers && buffers[0] && !buffers[0].uri) {
  104637. var binaryBuffer = buffers[0];
  104638. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  104639. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  104640. }
  104641. binaryBuffer._data = Promise.resolve(data.bin);
  104642. }
  104643. else {
  104644. BABYLON.Tools.Warn("Unexpected BIN chunk");
  104645. }
  104646. }
  104647. };
  104648. GLTFLoader.prototype._setupData = function () {
  104649. GLTF2._ArrayItem.Assign(this._gltf.accessors);
  104650. GLTF2._ArrayItem.Assign(this._gltf.animations);
  104651. GLTF2._ArrayItem.Assign(this._gltf.buffers);
  104652. GLTF2._ArrayItem.Assign(this._gltf.bufferViews);
  104653. GLTF2._ArrayItem.Assign(this._gltf.cameras);
  104654. GLTF2._ArrayItem.Assign(this._gltf.images);
  104655. GLTF2._ArrayItem.Assign(this._gltf.materials);
  104656. GLTF2._ArrayItem.Assign(this._gltf.meshes);
  104657. GLTF2._ArrayItem.Assign(this._gltf.nodes);
  104658. GLTF2._ArrayItem.Assign(this._gltf.samplers);
  104659. GLTF2._ArrayItem.Assign(this._gltf.scenes);
  104660. GLTF2._ArrayItem.Assign(this._gltf.skins);
  104661. GLTF2._ArrayItem.Assign(this._gltf.textures);
  104662. if (this._gltf.nodes) {
  104663. var nodeParents = {};
  104664. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  104665. var node = _a[_i];
  104666. if (node.children) {
  104667. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  104668. var index = _c[_b];
  104669. nodeParents[index] = node._index;
  104670. }
  104671. }
  104672. }
  104673. var rootNode = this._createRootNode();
  104674. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  104675. var node = _e[_d];
  104676. var parentIndex = nodeParents[node._index];
  104677. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  104678. }
  104679. }
  104680. };
  104681. GLTFLoader.prototype._loadExtensions = function () {
  104682. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  104683. var name_1 = _a[_i];
  104684. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  104685. this._extensions[name_1] = extension;
  104686. this.onExtensionLoadedObservable.notifyObservers(extension);
  104687. }
  104688. this.onExtensionLoadedObservable.clear();
  104689. };
  104690. GLTFLoader.prototype._checkExtensions = function () {
  104691. if (this._gltf.extensionsRequired) {
  104692. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  104693. var name_2 = _a[_i];
  104694. var extension = this._extensions[name_2];
  104695. if (!extension || !extension.enabled) {
  104696. throw new Error("Require extension " + name_2 + " is not available");
  104697. }
  104698. }
  104699. }
  104700. };
  104701. GLTFLoader.prototype._createRootNode = function () {
  104702. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  104703. this._rootBabylonMesh.setEnabled(false);
  104704. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  104705. switch (this.coordinateSystemMode) {
  104706. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  104707. if (!this._babylonScene.useRightHandedSystem) {
  104708. rootNode.rotation = [0, 1, 0, 0];
  104709. rootNode.scale = [1, 1, -1];
  104710. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  104711. }
  104712. break;
  104713. }
  104714. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  104715. this._babylonScene.useRightHandedSystem = true;
  104716. break;
  104717. }
  104718. default: {
  104719. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  104720. }
  104721. }
  104722. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  104723. return rootNode;
  104724. };
  104725. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  104726. var promises = new Array();
  104727. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  104728. var node = nodes_1[_i];
  104729. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104730. }
  104731. promises.push(this._loadAnimationsAsync());
  104732. return Promise.all(promises).then(function () { });
  104733. };
  104734. /** @hidden */
  104735. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  104736. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  104737. if (promise) {
  104738. return promise;
  104739. }
  104740. var promises = new Array();
  104741. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  104742. var index = _a[_i];
  104743. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  104744. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104745. }
  104746. promises.push(this._loadAnimationsAsync());
  104747. return Promise.all(promises).then(function () { });
  104748. };
  104749. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  104750. if (node._primitiveBabylonMeshes) {
  104751. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  104752. var babylonMesh = _a[_i];
  104753. callback(babylonMesh);
  104754. }
  104755. }
  104756. else {
  104757. callback(node._babylonMesh);
  104758. }
  104759. };
  104760. GLTFLoader.prototype._getMeshes = function () {
  104761. var meshes = new Array();
  104762. // Root mesh is always first.
  104763. meshes.push(this._rootBabylonMesh);
  104764. var nodes = this._gltf.nodes;
  104765. if (nodes) {
  104766. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  104767. var node = nodes_2[_i];
  104768. if (node._babylonMesh) {
  104769. meshes.push(node._babylonMesh);
  104770. }
  104771. if (node._primitiveBabylonMeshes) {
  104772. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  104773. var babylonMesh = _b[_a];
  104774. meshes.push(babylonMesh);
  104775. }
  104776. }
  104777. }
  104778. }
  104779. return meshes;
  104780. };
  104781. GLTFLoader.prototype._getSkeletons = function () {
  104782. var skeletons = new Array();
  104783. var skins = this._gltf.skins;
  104784. if (skins) {
  104785. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  104786. var skin = skins_1[_i];
  104787. if (skin._babylonSkeleton) {
  104788. skeletons.push(skin._babylonSkeleton);
  104789. }
  104790. }
  104791. }
  104792. return skeletons;
  104793. };
  104794. GLTFLoader.prototype._getAnimationGroups = function () {
  104795. var animationGroups = new Array();
  104796. var animations = this._gltf.animations;
  104797. if (animations) {
  104798. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  104799. var animation = animations_1[_i];
  104800. if (animation._babylonAnimationGroup) {
  104801. animationGroups.push(animation._babylonAnimationGroup);
  104802. }
  104803. }
  104804. }
  104805. return animationGroups;
  104806. };
  104807. GLTFLoader.prototype._startAnimations = function () {
  104808. switch (this.animationStartMode) {
  104809. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  104810. // do nothing
  104811. break;
  104812. }
  104813. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  104814. var babylonAnimationGroups = this._getAnimationGroups();
  104815. if (babylonAnimationGroups.length !== 0) {
  104816. babylonAnimationGroups[0].start(true);
  104817. }
  104818. break;
  104819. }
  104820. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  104821. var babylonAnimationGroups = this._getAnimationGroups();
  104822. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  104823. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  104824. babylonAnimationGroup.start(true);
  104825. }
  104826. break;
  104827. }
  104828. default: {
  104829. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  104830. return;
  104831. }
  104832. }
  104833. };
  104834. /** @hidden */
  104835. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  104836. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  104837. if (promise) {
  104838. return promise;
  104839. }
  104840. if (node._babylonMesh) {
  104841. throw new Error(context + ": Invalid recursive node hierarchy");
  104842. }
  104843. var promises = new Array();
  104844. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  104845. node._babylonMesh = babylonMesh;
  104846. GLTFLoader._LoadTransform(node, babylonMesh);
  104847. if (node.mesh != undefined) {
  104848. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  104849. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  104850. }
  104851. if (node.camera != undefined) {
  104852. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  104853. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  104854. }
  104855. if (node.children) {
  104856. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  104857. var index = _a[_i];
  104858. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  104859. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  104860. }
  104861. }
  104862. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104863. return Promise.all(promises).then(function () { });
  104864. };
  104865. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  104866. var _this = this;
  104867. var promises = new Array();
  104868. var primitives = mesh.primitives;
  104869. if (!primitives || primitives.length === 0) {
  104870. throw new Error(context + ": Primitives are missing");
  104871. }
  104872. GLTF2._ArrayItem.Assign(primitives);
  104873. if (primitives.length === 1) {
  104874. var primitive = primitives[0];
  104875. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  104876. }
  104877. else {
  104878. node._primitiveBabylonMeshes = [];
  104879. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  104880. var primitive = primitives_1[_i];
  104881. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  104882. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  104883. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  104884. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104885. }
  104886. }
  104887. if (node.skin != undefined) {
  104888. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  104889. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  104890. }
  104891. return Promise.all(promises).then(function () {
  104892. _this._forEachPrimitive(node, function (babylonMesh) {
  104893. babylonMesh._refreshBoundingInfo(true);
  104894. });
  104895. });
  104896. };
  104897. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  104898. var _this = this;
  104899. var promises = new Array();
  104900. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  104901. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  104902. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  104903. babylonGeometry.applyToMesh(babylonMesh);
  104904. });
  104905. }));
  104906. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  104907. if (primitive.material == undefined) {
  104908. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  104909. }
  104910. else {
  104911. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  104912. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  104913. babylonMesh.material = babylonMaterial;
  104914. }));
  104915. }
  104916. return Promise.all(promises).then(function () { });
  104917. };
  104918. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  104919. var _this = this;
  104920. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  104921. if (promise) {
  104922. return promise;
  104923. }
  104924. var attributes = primitive.attributes;
  104925. if (!attributes) {
  104926. throw new Error(context + ": Attributes are missing");
  104927. }
  104928. var promises = new Array();
  104929. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  104930. if (primitive.indices == undefined) {
  104931. babylonMesh.isUnIndexed = true;
  104932. }
  104933. else {
  104934. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  104935. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104936. babylonGeometry.setIndices(data);
  104937. }));
  104938. }
  104939. var loadAttribute = function (attribute, kind, callback) {
  104940. if (attributes[attribute] == undefined) {
  104941. return;
  104942. }
  104943. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  104944. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  104945. babylonMesh._delayInfo.push(kind);
  104946. }
  104947. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  104948. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  104949. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  104950. }));
  104951. if (callback) {
  104952. callback(accessor);
  104953. }
  104954. };
  104955. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  104956. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  104957. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  104958. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  104959. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  104960. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  104961. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  104962. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  104963. if (accessor.type === "VEC4" /* VEC4 */) {
  104964. babylonMesh.hasVertexAlpha = true;
  104965. }
  104966. });
  104967. return Promise.all(promises).then(function () {
  104968. return babylonGeometry;
  104969. });
  104970. };
  104971. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  104972. if (!primitive.targets) {
  104973. return;
  104974. }
  104975. if (node._numMorphTargets == undefined) {
  104976. node._numMorphTargets = primitive.targets.length;
  104977. }
  104978. else if (primitive.targets.length !== node._numMorphTargets) {
  104979. throw new Error(context + ": Primitives do not have the same number of targets");
  104980. }
  104981. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  104982. for (var index = 0; index < primitive.targets.length; index++) {
  104983. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  104984. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  104985. // TODO: tell the target whether it has positions, normals, tangents
  104986. }
  104987. };
  104988. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  104989. if (!primitive.targets) {
  104990. return Promise.resolve();
  104991. }
  104992. var promises = new Array();
  104993. var morphTargetManager = babylonMesh.morphTargetManager;
  104994. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  104995. var babylonMorphTarget = morphTargetManager.getTarget(index);
  104996. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  104997. }
  104998. return Promise.all(promises).then(function () { });
  104999. };
  105000. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  105001. var _this = this;
  105002. var promises = new Array();
  105003. var loadAttribute = function (attribute, kind, setData) {
  105004. if (attributes[attribute] == undefined) {
  105005. return;
  105006. }
  105007. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  105008. if (!babylonVertexBuffer) {
  105009. return;
  105010. }
  105011. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  105012. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  105013. setData(babylonVertexBuffer, data);
  105014. }));
  105015. };
  105016. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  105017. babylonVertexBuffer.forEach(data.length, function (value, index) {
  105018. data[index] += value;
  105019. });
  105020. babylonMorphTarget.setPositions(data);
  105021. });
  105022. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  105023. babylonVertexBuffer.forEach(data.length, function (value, index) {
  105024. data[index] += value;
  105025. });
  105026. babylonMorphTarget.setNormals(data);
  105027. });
  105028. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  105029. var dataIndex = 0;
  105030. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  105031. // Tangent data for morph targets is stored as xyz delta.
  105032. // The vertexData.tangent is stored as xyzw.
  105033. // So we need to skip every fourth vertexData.tangent.
  105034. if (((index + 1) % 4) !== 0) {
  105035. data[dataIndex++] += value;
  105036. }
  105037. });
  105038. babylonMorphTarget.setTangents(data);
  105039. });
  105040. return Promise.all(promises).then(function () { });
  105041. };
  105042. GLTFLoader._LoadTransform = function (node, babylonNode) {
  105043. var position = BABYLON.Vector3.Zero();
  105044. var rotation = BABYLON.Quaternion.Identity();
  105045. var scaling = BABYLON.Vector3.One();
  105046. if (node.matrix) {
  105047. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  105048. matrix.decompose(scaling, rotation, position);
  105049. }
  105050. else {
  105051. if (node.translation)
  105052. position = BABYLON.Vector3.FromArray(node.translation);
  105053. if (node.rotation)
  105054. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  105055. if (node.scale)
  105056. scaling = BABYLON.Vector3.FromArray(node.scale);
  105057. }
  105058. babylonNode.position = position;
  105059. babylonNode.rotationQuaternion = rotation;
  105060. babylonNode.scaling = scaling;
  105061. };
  105062. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  105063. var _this = this;
  105064. var assignSkeleton = function (skeleton) {
  105065. _this._forEachPrimitive(node, function (babylonMesh) {
  105066. babylonMesh.skeleton = skeleton;
  105067. });
  105068. // Ignore the TRS of skinned nodes.
  105069. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  105070. node._babylonMesh.parent = _this._rootBabylonMesh;
  105071. node._babylonMesh.position = BABYLON.Vector3.Zero();
  105072. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  105073. node._babylonMesh.scaling = BABYLON.Vector3.One();
  105074. };
  105075. if (skin._loaded) {
  105076. return skin._loaded.then(function () {
  105077. assignSkeleton(skin._babylonSkeleton);
  105078. });
  105079. }
  105080. var skeletonId = "skeleton" + skin._index;
  105081. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  105082. skin._babylonSkeleton = babylonSkeleton;
  105083. this._loadBones(context, skin);
  105084. assignSkeleton(babylonSkeleton);
  105085. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  105086. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  105087. }));
  105088. };
  105089. GLTFLoader.prototype._loadBones = function (context, skin) {
  105090. var babylonBones = {};
  105091. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  105092. var index = _a[_i];
  105093. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  105094. this._loadBone(node, skin, babylonBones);
  105095. }
  105096. };
  105097. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  105098. var babylonBone = babylonBones[node._index];
  105099. if (babylonBone) {
  105100. return babylonBone;
  105101. }
  105102. var babylonParentBone = null;
  105103. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  105104. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  105105. }
  105106. var boneIndex = skin.joints.indexOf(node._index);
  105107. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  105108. babylonBones[node._index] = babylonBone;
  105109. node._babylonBones = node._babylonBones || [];
  105110. node._babylonBones.push(babylonBone);
  105111. return babylonBone;
  105112. };
  105113. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  105114. if (skin.inverseBindMatrices == undefined) {
  105115. return Promise.resolve(null);
  105116. }
  105117. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  105118. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  105119. };
  105120. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  105121. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  105122. var babylonBone = _a[_i];
  105123. var baseMatrix = BABYLON.Matrix.Identity();
  105124. var boneIndex = babylonBone._index;
  105125. if (inverseBindMatricesData && boneIndex !== -1) {
  105126. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  105127. baseMatrix.invertToRef(baseMatrix);
  105128. }
  105129. var babylonParentBone = babylonBone.getParent();
  105130. if (babylonParentBone) {
  105131. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  105132. }
  105133. babylonBone.updateMatrix(baseMatrix, false, false);
  105134. babylonBone._updateDifferenceMatrix(undefined, false);
  105135. }
  105136. };
  105137. GLTFLoader.prototype._getNodeMatrix = function (node) {
  105138. return node.matrix ?
  105139. BABYLON.Matrix.FromArray(node.matrix) :
  105140. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  105141. };
  105142. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  105143. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  105144. babylonCamera.parent = babylonMesh;
  105145. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  105146. switch (camera.type) {
  105147. case "perspective" /* PERSPECTIVE */: {
  105148. var perspective = camera.perspective;
  105149. if (!perspective) {
  105150. throw new Error(context + ": Camera perspective properties are missing");
  105151. }
  105152. babylonCamera.fov = perspective.yfov;
  105153. babylonCamera.minZ = perspective.znear;
  105154. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  105155. break;
  105156. }
  105157. case "orthographic" /* ORTHOGRAPHIC */: {
  105158. if (!camera.orthographic) {
  105159. throw new Error(context + ": Camera orthographic properties are missing");
  105160. }
  105161. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  105162. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  105163. babylonCamera.orthoRight = camera.orthographic.xmag;
  105164. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  105165. babylonCamera.orthoTop = camera.orthographic.ymag;
  105166. babylonCamera.minZ = camera.orthographic.znear;
  105167. babylonCamera.maxZ = camera.orthographic.zfar;
  105168. break;
  105169. }
  105170. default: {
  105171. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  105172. }
  105173. }
  105174. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  105175. };
  105176. GLTFLoader.prototype._loadAnimationsAsync = function () {
  105177. var animations = this._gltf.animations;
  105178. if (!animations) {
  105179. return Promise.resolve();
  105180. }
  105181. var promises = new Array();
  105182. for (var index = 0; index < animations.length; index++) {
  105183. var animation = animations[index];
  105184. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  105185. }
  105186. return Promise.all(promises).then(function () { });
  105187. };
  105188. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  105189. var _this = this;
  105190. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  105191. animation._babylonAnimationGroup = babylonAnimationGroup;
  105192. var promises = new Array();
  105193. GLTF2._ArrayItem.Assign(animation.channels);
  105194. GLTF2._ArrayItem.Assign(animation.samplers);
  105195. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  105196. var channel = _a[_i];
  105197. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  105198. }
  105199. return Promise.all(promises).then(function () {
  105200. babylonAnimationGroup.normalize(_this._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  105201. });
  105202. };
  105203. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  105204. var _this = this;
  105205. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  105206. // Ignore animations that have no animation targets.
  105207. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  105208. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  105209. return Promise.resolve();
  105210. }
  105211. // Ignore animations targeting TRS of skinned nodes.
  105212. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  105213. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  105214. return Promise.resolve();
  105215. }
  105216. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  105217. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  105218. var targetPath;
  105219. var animationType;
  105220. switch (channel.target.path) {
  105221. case "translation" /* TRANSLATION */: {
  105222. targetPath = "position";
  105223. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105224. break;
  105225. }
  105226. case "rotation" /* ROTATION */: {
  105227. targetPath = "rotationQuaternion";
  105228. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  105229. break;
  105230. }
  105231. case "scale" /* SCALE */: {
  105232. targetPath = "scaling";
  105233. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105234. break;
  105235. }
  105236. case "weights" /* WEIGHTS */: {
  105237. targetPath = "influence";
  105238. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  105239. break;
  105240. }
  105241. default: {
  105242. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  105243. }
  105244. }
  105245. var outputBufferOffset = 0;
  105246. var getNextOutputValue;
  105247. switch (targetPath) {
  105248. case "position": {
  105249. getNextOutputValue = function () {
  105250. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  105251. outputBufferOffset += 3;
  105252. return value;
  105253. };
  105254. break;
  105255. }
  105256. case "rotationQuaternion": {
  105257. getNextOutputValue = function () {
  105258. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  105259. outputBufferOffset += 4;
  105260. return value;
  105261. };
  105262. break;
  105263. }
  105264. case "scaling": {
  105265. getNextOutputValue = function () {
  105266. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  105267. outputBufferOffset += 3;
  105268. return value;
  105269. };
  105270. break;
  105271. }
  105272. case "influence": {
  105273. getNextOutputValue = function () {
  105274. var value = new Array(targetNode._numMorphTargets);
  105275. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  105276. value[i] = data.output[outputBufferOffset++];
  105277. }
  105278. return value;
  105279. };
  105280. break;
  105281. }
  105282. }
  105283. var getNextKey;
  105284. switch (data.interpolation) {
  105285. case "STEP" /* STEP */: {
  105286. getNextKey = function (frameIndex) { return ({
  105287. frame: data.input[frameIndex],
  105288. value: getNextOutputValue(),
  105289. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  105290. }); };
  105291. break;
  105292. }
  105293. case "LINEAR" /* LINEAR */: {
  105294. getNextKey = function (frameIndex) { return ({
  105295. frame: data.input[frameIndex],
  105296. value: getNextOutputValue()
  105297. }); };
  105298. break;
  105299. }
  105300. case "CUBICSPLINE" /* CUBICSPLINE */: {
  105301. getNextKey = function (frameIndex) { return ({
  105302. frame: data.input[frameIndex],
  105303. inTangent: getNextOutputValue(),
  105304. value: getNextOutputValue(),
  105305. outTangent: getNextOutputValue()
  105306. }); };
  105307. break;
  105308. }
  105309. }
  105310. var keys = new Array(data.input.length);
  105311. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  105312. keys[frameIndex] = getNextKey(frameIndex);
  105313. }
  105314. if (targetPath === "influence") {
  105315. var _loop_1 = function (targetIndex) {
  105316. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  105317. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  105318. babylonAnimation.setKeys(keys.map(function (key) { return ({
  105319. frame: key.frame,
  105320. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  105321. value: key.value[targetIndex],
  105322. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  105323. }); }));
  105324. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  105325. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  105326. var babylonAnimationClone = babylonAnimation.clone();
  105327. morphTarget.animations.push(babylonAnimationClone);
  105328. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  105329. });
  105330. };
  105331. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  105332. _loop_1(targetIndex);
  105333. }
  105334. }
  105335. else {
  105336. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  105337. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  105338. babylonAnimation.setKeys(keys);
  105339. if (targetNode._babylonBones) {
  105340. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  105341. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  105342. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  105343. babylonAnimationTarget.animations.push(babylonAnimation);
  105344. }
  105345. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  105346. }
  105347. else {
  105348. targetNode._babylonMesh.animations.push(babylonAnimation);
  105349. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  105350. }
  105351. }
  105352. });
  105353. };
  105354. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  105355. if (sampler._data) {
  105356. return sampler._data;
  105357. }
  105358. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  105359. switch (interpolation) {
  105360. case "STEP" /* STEP */:
  105361. case "LINEAR" /* LINEAR */:
  105362. case "CUBICSPLINE" /* CUBICSPLINE */: {
  105363. break;
  105364. }
  105365. default: {
  105366. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  105367. }
  105368. }
  105369. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  105370. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  105371. sampler._data = Promise.all([
  105372. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  105373. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  105374. ]).then(function (_a) {
  105375. var inputData = _a[0], outputData = _a[1];
  105376. return {
  105377. input: inputData,
  105378. interpolation: interpolation,
  105379. output: outputData,
  105380. };
  105381. });
  105382. return sampler._data;
  105383. };
  105384. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  105385. if (buffer._data) {
  105386. return buffer._data;
  105387. }
  105388. if (!buffer.uri) {
  105389. throw new Error(context + ": Uri is missing");
  105390. }
  105391. buffer._data = this._loadUriAsync(context, buffer.uri);
  105392. return buffer._data;
  105393. };
  105394. /** @hidden */
  105395. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  105396. if (bufferView._data) {
  105397. return bufferView._data;
  105398. }
  105399. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  105400. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  105401. try {
  105402. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  105403. }
  105404. catch (e) {
  105405. throw new Error(context + ": " + e.message);
  105406. }
  105407. });
  105408. return bufferView._data;
  105409. };
  105410. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  105411. if (accessor.type !== "SCALAR" /* SCALAR */) {
  105412. throw new Error(context + ": Invalid type " + accessor.type);
  105413. }
  105414. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  105415. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  105416. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  105417. throw new Error(context + ": Invalid component type " + accessor.componentType);
  105418. }
  105419. if (accessor._data) {
  105420. return accessor._data;
  105421. }
  105422. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105423. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105424. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  105425. });
  105426. return accessor._data;
  105427. };
  105428. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  105429. // TODO: support normalized and stride
  105430. var _this = this;
  105431. if (accessor.componentType !== 5126 /* FLOAT */) {
  105432. throw new Error("Invalid component type " + accessor.componentType);
  105433. }
  105434. if (accessor._data) {
  105435. return accessor._data;
  105436. }
  105437. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  105438. var length = numComponents * accessor.count;
  105439. if (accessor.bufferView == undefined) {
  105440. accessor._data = Promise.resolve(new Float32Array(length));
  105441. }
  105442. else {
  105443. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105444. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105445. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  105446. });
  105447. }
  105448. if (accessor.sparse) {
  105449. var sparse_1 = accessor.sparse;
  105450. accessor._data = accessor._data.then(function (data) {
  105451. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  105452. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  105453. return Promise.all([
  105454. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  105455. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  105456. ]).then(function (_a) {
  105457. var indicesData = _a[0], valuesData = _a[1];
  105458. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  105459. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  105460. var valuesIndex = 0;
  105461. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  105462. var dataIndex = indices[indicesIndex] * numComponents;
  105463. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  105464. data[dataIndex++] = values[valuesIndex++];
  105465. }
  105466. }
  105467. return data;
  105468. });
  105469. });
  105470. }
  105471. return accessor._data;
  105472. };
  105473. /** @hidden */
  105474. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  105475. var _this = this;
  105476. if (bufferView._babylonBuffer) {
  105477. return bufferView._babylonBuffer;
  105478. }
  105479. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  105480. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  105481. });
  105482. return bufferView._babylonBuffer;
  105483. };
  105484. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  105485. var _this = this;
  105486. if (accessor._babylonVertexBuffer) {
  105487. return accessor._babylonVertexBuffer;
  105488. }
  105489. if (accessor.sparse) {
  105490. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  105491. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  105492. });
  105493. }
  105494. else {
  105495. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105496. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  105497. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  105498. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  105499. });
  105500. }
  105501. return accessor._babylonVertexBuffer;
  105502. };
  105503. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  105504. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  105505. if (!babylonMaterial) {
  105506. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  105507. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  105508. babylonMaterial.metallic = 1;
  105509. babylonMaterial.roughness = 1;
  105510. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105511. }
  105512. return babylonMaterial;
  105513. };
  105514. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  105515. var promises = new Array();
  105516. // Ensure metallic workflow
  105517. babylonMaterial.metallic = 1;
  105518. babylonMaterial.roughness = 1;
  105519. var properties = material.pbrMetallicRoughness;
  105520. if (properties) {
  105521. if (properties.baseColorFactor) {
  105522. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  105523. babylonMaterial.alpha = properties.baseColorFactor[3];
  105524. }
  105525. else {
  105526. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105527. }
  105528. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  105529. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  105530. if (properties.baseColorTexture) {
  105531. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  105532. babylonMaterial.albedoTexture = texture;
  105533. }));
  105534. }
  105535. if (properties.metallicRoughnessTexture) {
  105536. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  105537. babylonMaterial.metallicTexture = texture;
  105538. }));
  105539. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  105540. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  105541. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  105542. }
  105543. }
  105544. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105545. return Promise.all(promises).then(function () { });
  105546. };
  105547. /** @hidden */
  105548. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105549. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  105550. if (promise) {
  105551. return promise;
  105552. }
  105553. material._babylonData = material._babylonData || {};
  105554. var babylonData = material._babylonData[babylonDrawMode];
  105555. if (!babylonData) {
  105556. var promises = new Array();
  105557. var name_3 = material.name || "materialSG_" + material._index;
  105558. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  105559. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  105560. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  105561. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105562. babylonData = {
  105563. material: babylonMaterial,
  105564. meshes: [],
  105565. loaded: Promise.all(promises).then(function () { })
  105566. };
  105567. material._babylonData[babylonDrawMode] = babylonData;
  105568. }
  105569. babylonData.meshes.push(babylonMesh);
  105570. assign(babylonData.material);
  105571. return babylonData.loaded;
  105572. };
  105573. /** @hidden */
  105574. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  105575. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  105576. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  105577. babylonMaterial.fillMode = drawMode;
  105578. babylonMaterial.enableSpecularAntiAliasing = true;
  105579. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  105580. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  105581. return babylonMaterial;
  105582. };
  105583. /** @hidden */
  105584. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  105585. var promises = new Array();
  105586. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  105587. if (material.doubleSided) {
  105588. babylonMaterial.backFaceCulling = false;
  105589. babylonMaterial.twoSidedLighting = true;
  105590. }
  105591. if (material.normalTexture) {
  105592. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  105593. babylonMaterial.bumpTexture = texture;
  105594. }));
  105595. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  105596. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  105597. if (material.normalTexture.scale != undefined) {
  105598. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  105599. }
  105600. }
  105601. if (material.occlusionTexture) {
  105602. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  105603. babylonMaterial.ambientTexture = texture;
  105604. }));
  105605. babylonMaterial.useAmbientInGrayScale = true;
  105606. if (material.occlusionTexture.strength != undefined) {
  105607. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  105608. }
  105609. }
  105610. if (material.emissiveTexture) {
  105611. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  105612. babylonMaterial.emissiveTexture = texture;
  105613. }));
  105614. }
  105615. return Promise.all(promises).then(function () { });
  105616. };
  105617. /** @hidden */
  105618. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  105619. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  105620. switch (alphaMode) {
  105621. case "OPAQUE" /* OPAQUE */: {
  105622. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  105623. break;
  105624. }
  105625. case "MASK" /* MASK */: {
  105626. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  105627. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  105628. if (babylonMaterial.albedoTexture) {
  105629. babylonMaterial.albedoTexture.hasAlpha = true;
  105630. }
  105631. break;
  105632. }
  105633. case "BLEND" /* BLEND */: {
  105634. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  105635. if (babylonMaterial.albedoTexture) {
  105636. babylonMaterial.albedoTexture.hasAlpha = true;
  105637. babylonMaterial.useAlphaFromAlbedoTexture = true;
  105638. }
  105639. break;
  105640. }
  105641. default: {
  105642. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  105643. }
  105644. }
  105645. };
  105646. /** @hidden */
  105647. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  105648. var _this = this;
  105649. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  105650. if (promise) {
  105651. return promise;
  105652. }
  105653. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  105654. context = "#/textures/" + textureInfo.index;
  105655. var promises = new Array();
  105656. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  105657. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  105658. var deferred = new BABYLON.Deferred();
  105659. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  105660. if (!_this._disposed) {
  105661. deferred.resolve();
  105662. }
  105663. }, function (message, exception) {
  105664. if (!_this._disposed) {
  105665. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  105666. }
  105667. });
  105668. promises.push(deferred.promise);
  105669. babylonTexture.name = texture.name || "texture" + texture._index;
  105670. babylonTexture.wrapU = samplerData.wrapU;
  105671. babylonTexture.wrapV = samplerData.wrapV;
  105672. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  105673. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  105674. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  105675. babylonTexture.updateURL(objectURL);
  105676. }));
  105677. assign(babylonTexture);
  105678. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  105679. return Promise.all(promises).then(function () { });
  105680. };
  105681. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  105682. if (!sampler._data) {
  105683. sampler._data = {
  105684. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  105685. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  105686. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  105687. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  105688. };
  105689. }
  105690. ;
  105691. return sampler._data;
  105692. };
  105693. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  105694. if (image._objectURL) {
  105695. return image._objectURL;
  105696. }
  105697. var promise;
  105698. if (image.uri) {
  105699. promise = this._loadUriAsync(context, image.uri);
  105700. }
  105701. else {
  105702. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  105703. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  105704. }
  105705. image._objectURL = promise.then(function (data) {
  105706. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  105707. });
  105708. return image._objectURL;
  105709. };
  105710. /** @hidden */
  105711. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  105712. var _this = this;
  105713. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  105714. if (promise) {
  105715. return promise;
  105716. }
  105717. if (!GLTFLoader._ValidateUri(uri)) {
  105718. throw new Error(context + ": Uri '" + uri + "' is invalid");
  105719. }
  105720. if (BABYLON.Tools.IsBase64(uri)) {
  105721. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  105722. }
  105723. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  105724. return new Promise(function (resolve, reject) {
  105725. if (!_this._disposed) {
  105726. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  105727. if (!_this._disposed) {
  105728. resolve(new Uint8Array(data));
  105729. }
  105730. }, function (event) {
  105731. if (!_this._disposed) {
  105732. try {
  105733. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  105734. request_1._lengthComputable = event.lengthComputable;
  105735. request_1._loaded = event.loaded;
  105736. request_1._total = event.total;
  105737. _this._onProgress();
  105738. }
  105739. }
  105740. catch (e) {
  105741. reject(e);
  105742. }
  105743. }
  105744. }, _this._babylonScene.database, true, function (request, exception) {
  105745. if (!_this._disposed) {
  105746. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  105747. }
  105748. });
  105749. _this._requests.push(request_1);
  105750. }
  105751. });
  105752. });
  105753. };
  105754. GLTFLoader.prototype._onProgress = function () {
  105755. if (!this._progressCallback) {
  105756. return;
  105757. }
  105758. var lengthComputable = true;
  105759. var loaded = 0;
  105760. var total = 0;
  105761. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105762. var request = _a[_i];
  105763. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  105764. return;
  105765. }
  105766. lengthComputable = lengthComputable && request._lengthComputable;
  105767. loaded += request._loaded;
  105768. total += request._total;
  105769. }
  105770. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  105771. };
  105772. /** @hidden */
  105773. GLTFLoader._GetProperty = function (context, array, index) {
  105774. if (!array || index == undefined || !array[index]) {
  105775. throw new Error(context + ": Failed to find index (" + index + ")");
  105776. }
  105777. return array[index];
  105778. };
  105779. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  105780. // Set defaults if undefined
  105781. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  105782. switch (mode) {
  105783. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  105784. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  105785. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  105786. default:
  105787. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  105788. return BABYLON.Texture.WRAP_ADDRESSMODE;
  105789. }
  105790. };
  105791. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  105792. // Set defaults if undefined
  105793. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  105794. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  105795. if (magFilter === 9729 /* LINEAR */) {
  105796. switch (minFilter) {
  105797. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  105798. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  105799. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  105800. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  105801. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  105802. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  105803. default:
  105804. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105805. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  105806. }
  105807. }
  105808. else {
  105809. if (magFilter !== 9728 /* NEAREST */) {
  105810. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  105811. }
  105812. switch (minFilter) {
  105813. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  105814. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  105815. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105816. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  105817. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  105818. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  105819. default:
  105820. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105821. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105822. }
  105823. }
  105824. };
  105825. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  105826. var buffer = bufferView.buffer;
  105827. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  105828. try {
  105829. switch (componentType) {
  105830. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  105831. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  105832. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  105833. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  105834. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  105835. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  105836. default: throw new Error("Invalid component type " + componentType);
  105837. }
  105838. }
  105839. catch (e) {
  105840. throw new Error(context + ": " + e);
  105841. }
  105842. };
  105843. GLTFLoader._GetNumComponents = function (context, type) {
  105844. switch (type) {
  105845. case "SCALAR": return 1;
  105846. case "VEC2": return 2;
  105847. case "VEC3": return 3;
  105848. case "VEC4": return 4;
  105849. case "MAT2": return 4;
  105850. case "MAT3": return 9;
  105851. case "MAT4": return 16;
  105852. }
  105853. throw new Error(context + ": Invalid type (" + type + ")");
  105854. };
  105855. GLTFLoader._ValidateUri = function (uri) {
  105856. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  105857. };
  105858. GLTFLoader._GetDrawMode = function (context, mode) {
  105859. if (mode == undefined) {
  105860. mode = 4 /* TRIANGLES */;
  105861. }
  105862. switch (mode) {
  105863. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  105864. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  105865. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  105866. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  105867. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  105868. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  105869. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  105870. }
  105871. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  105872. };
  105873. GLTFLoader.prototype._compileMaterialsAsync = function () {
  105874. var promises = new Array();
  105875. if (this._gltf.materials) {
  105876. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  105877. var material = _a[_i];
  105878. if (material._babylonData) {
  105879. for (var babylonDrawMode in material._babylonData) {
  105880. var babylonData = material._babylonData[babylonDrawMode];
  105881. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  105882. var babylonMesh = _c[_b];
  105883. // Ensure nonUniformScaling is set if necessary.
  105884. babylonMesh.computeWorldMatrix(true);
  105885. var babylonMaterial = babylonData.material;
  105886. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  105887. if (this.useClipPlane) {
  105888. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  105889. }
  105890. }
  105891. }
  105892. }
  105893. }
  105894. }
  105895. return Promise.all(promises).then(function () { });
  105896. };
  105897. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  105898. var promises = new Array();
  105899. var lights = this._babylonScene.lights;
  105900. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  105901. var light = lights_1[_i];
  105902. var generator = light.getShadowGenerator();
  105903. if (generator) {
  105904. promises.push(generator.forceCompilationAsync());
  105905. }
  105906. }
  105907. return Promise.all(promises).then(function () { });
  105908. };
  105909. GLTFLoader.prototype._clear = function () {
  105910. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105911. var request = _a[_i];
  105912. request.abort();
  105913. }
  105914. this._requests.length = 0;
  105915. if (this._gltf && this._gltf.images) {
  105916. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  105917. var image = _c[_b];
  105918. if (image._objectURL) {
  105919. image._objectURL.then(function (value) {
  105920. URL.revokeObjectURL(value);
  105921. });
  105922. image._objectURL = undefined;
  105923. }
  105924. }
  105925. }
  105926. delete this._gltf;
  105927. delete this._babylonScene;
  105928. this._completePromises.length = 0;
  105929. for (var name_4 in this._extensions) {
  105930. this._extensions[name_4].dispose();
  105931. }
  105932. this._extensions = {};
  105933. delete this._rootBabylonMesh;
  105934. delete this._progressCallback;
  105935. this.onMeshLoadedObservable.clear();
  105936. this.onTextureLoadedObservable.clear();
  105937. this.onMaterialLoadedObservable.clear();
  105938. this.onCameraLoadedObservable.clear();
  105939. };
  105940. /** @hidden */
  105941. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  105942. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  105943. var name_5 = _a[_i];
  105944. var extension = this._extensions[name_5];
  105945. if (extension.enabled) {
  105946. var promise = actionAsync(extension);
  105947. if (promise) {
  105948. return promise;
  105949. }
  105950. }
  105951. }
  105952. return null;
  105953. };
  105954. GLTFLoader._ExtensionNames = new Array();
  105955. GLTFLoader._ExtensionFactories = {};
  105956. return GLTFLoader;
  105957. }());
  105958. GLTF2.GLTFLoader = GLTFLoader;
  105959. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  105960. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105961. })(BABYLON || (BABYLON = {}));
  105962. //# sourceMappingURL=babylon.glTFLoader.js.map
  105963. var BABYLON;
  105964. (function (BABYLON) {
  105965. var GLTF2;
  105966. (function (GLTF2) {
  105967. /**
  105968. * Abstract class that can be implemented to extend existing glTF loader behavior.
  105969. */
  105970. var GLTFLoaderExtension = /** @class */ (function () {
  105971. function GLTFLoaderExtension(loader) {
  105972. this.enabled = true;
  105973. this._loader = loader;
  105974. }
  105975. GLTFLoaderExtension.prototype.dispose = function () {
  105976. delete this._loader;
  105977. };
  105978. // #region Overridable Methods
  105979. /** Override this method to modify the default behavior for loading scenes. */
  105980. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  105981. /** Override this method to modify the default behavior for loading nodes. */
  105982. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  105983. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  105984. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  105985. /** Override this method to modify the default behavior for loading materials. */
  105986. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  105987. /** Override this method to modify the default behavior for loading textures. */
  105988. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  105989. /** Override this method to modify the default behavior for loading uris. */
  105990. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  105991. // #endregion
  105992. /** Helper method called by a loader extension to load an glTF extension. */
  105993. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  105994. if (!property.extensions) {
  105995. return null;
  105996. }
  105997. var extensions = property.extensions;
  105998. var extension = extensions[this.name];
  105999. if (!extension) {
  106000. return null;
  106001. }
  106002. // Clear out the extension before executing the action to avoid recursing into the same property.
  106003. delete extensions[this.name];
  106004. try {
  106005. return actionAsync(context + "/extensions/" + this.name, extension);
  106006. }
  106007. finally {
  106008. // Restore the extension after executing the action.
  106009. extensions[this.name] = extension;
  106010. }
  106011. };
  106012. /** Helper method called by the loader to allow extensions to override loading scenes. */
  106013. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  106014. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  106015. };
  106016. /** Helper method called by the loader to allow extensions to override loading nodes. */
  106017. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  106018. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  106019. };
  106020. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  106021. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  106022. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  106023. };
  106024. /** Helper method called by the loader to allow extensions to override loading materials. */
  106025. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  106026. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  106027. };
  106028. /** Helper method called by the loader to allow extensions to override loading textures. */
  106029. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  106030. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  106031. };
  106032. /** Helper method called by the loader to allow extensions to override loading uris. */
  106033. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  106034. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  106035. };
  106036. return GLTFLoaderExtension;
  106037. }());
  106038. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  106039. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106040. })(BABYLON || (BABYLON = {}));
  106041. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  106042. var BABYLON;
  106043. (function (BABYLON) {
  106044. var GLTF2;
  106045. (function (GLTF2) {
  106046. var Extensions;
  106047. (function (Extensions) {
  106048. var NAME = "MSFT_lod";
  106049. /**
  106050. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  106051. */
  106052. var MSFT_lod = /** @class */ (function (_super) {
  106053. __extends(MSFT_lod, _super);
  106054. function MSFT_lod() {
  106055. var _this = _super !== null && _super.apply(this, arguments) || this;
  106056. _this.name = NAME;
  106057. /**
  106058. * Maximum number of LODs to load, starting from the lowest LOD.
  106059. */
  106060. _this.maxLODsToLoad = Number.MAX_VALUE;
  106061. _this._loadingNodeLOD = null;
  106062. _this._loadNodeSignals = {};
  106063. _this._loadingMaterialLOD = null;
  106064. _this._loadMaterialSignals = {};
  106065. return _this;
  106066. }
  106067. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  106068. var _this = this;
  106069. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  106070. var firstPromise;
  106071. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  106072. var _loop_1 = function (indexLOD) {
  106073. var nodeLOD = nodeLODs[indexLOD];
  106074. if (indexLOD !== 0) {
  106075. _this._loadingNodeLOD = nodeLOD;
  106076. if (!_this._loadNodeSignals[nodeLOD._index]) {
  106077. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  106078. }
  106079. }
  106080. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  106081. if (indexLOD !== 0) {
  106082. var previousNodeLOD = nodeLODs[indexLOD - 1];
  106083. if (previousNodeLOD._babylonMesh) {
  106084. previousNodeLOD._babylonMesh.dispose(false, true);
  106085. delete previousNodeLOD._babylonMesh;
  106086. }
  106087. }
  106088. if (indexLOD !== nodeLODs.length - 1) {
  106089. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  106090. if (_this._loadNodeSignals[nodeIndex]) {
  106091. _this._loadNodeSignals[nodeIndex].resolve();
  106092. delete _this._loadNodeSignals[nodeIndex];
  106093. }
  106094. }
  106095. });
  106096. if (indexLOD === 0) {
  106097. firstPromise = promise;
  106098. }
  106099. else {
  106100. _this._loader._completePromises.push(promise);
  106101. _this._loadingNodeLOD = null;
  106102. }
  106103. };
  106104. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  106105. _loop_1(indexLOD);
  106106. }
  106107. return firstPromise;
  106108. });
  106109. };
  106110. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106111. var _this = this;
  106112. // Don't load material LODs if already loading a node LOD.
  106113. if (this._loadingNodeLOD) {
  106114. return null;
  106115. }
  106116. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  106117. var firstPromise;
  106118. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  106119. var _loop_2 = function (indexLOD) {
  106120. var materialLOD = materialLODs[indexLOD];
  106121. if (indexLOD !== 0) {
  106122. _this._loadingMaterialLOD = materialLOD;
  106123. if (!_this._loadMaterialSignals[materialLOD._index]) {
  106124. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  106125. }
  106126. }
  106127. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  106128. if (indexLOD !== 0) {
  106129. var babylonDataLOD = materialLOD._babylonData;
  106130. assign(babylonDataLOD[babylonDrawMode].material);
  106131. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  106132. if (previousBabylonDataLOD[babylonDrawMode]) {
  106133. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  106134. delete previousBabylonDataLOD[babylonDrawMode];
  106135. }
  106136. }
  106137. if (indexLOD !== materialLODs.length - 1) {
  106138. var materialIndex = materialLODs[indexLOD + 1]._index;
  106139. if (_this._loadMaterialSignals[materialIndex]) {
  106140. _this._loadMaterialSignals[materialIndex].resolve();
  106141. delete _this._loadMaterialSignals[materialIndex];
  106142. }
  106143. }
  106144. });
  106145. if (indexLOD === 0) {
  106146. firstPromise = promise;
  106147. }
  106148. else {
  106149. _this._loader._completePromises.push(promise);
  106150. _this._loadingMaterialLOD = null;
  106151. }
  106152. };
  106153. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  106154. _loop_2(indexLOD);
  106155. }
  106156. return firstPromise;
  106157. });
  106158. };
  106159. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  106160. var _this = this;
  106161. // Defer the loading of uris if loading a material or node LOD.
  106162. if (this._loadingMaterialLOD) {
  106163. var index = this._loadingMaterialLOD._index;
  106164. return this._loadMaterialSignals[index].promise.then(function () {
  106165. return _this._loader._loadUriAsync(context, uri);
  106166. });
  106167. }
  106168. else if (this._loadingNodeLOD) {
  106169. var index = this._loadingNodeLOD._index;
  106170. return this._loadNodeSignals[index].promise.then(function () {
  106171. return _this._loader._loadUriAsync(context, uri);
  106172. });
  106173. }
  106174. return null;
  106175. };
  106176. /**
  106177. * Gets an array of LOD properties from lowest to highest.
  106178. */
  106179. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  106180. if (this.maxLODsToLoad <= 0) {
  106181. throw new Error("maxLODsToLoad must be greater than zero");
  106182. }
  106183. var properties = new Array();
  106184. for (var i = ids.length - 1; i >= 0; i--) {
  106185. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  106186. if (properties.length === this.maxLODsToLoad) {
  106187. return properties;
  106188. }
  106189. }
  106190. properties.push(property);
  106191. return properties;
  106192. };
  106193. return MSFT_lod;
  106194. }(GLTF2.GLTFLoaderExtension));
  106195. Extensions.MSFT_lod = MSFT_lod;
  106196. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  106197. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106198. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106199. })(BABYLON || (BABYLON = {}));
  106200. //# sourceMappingURL=MSFT_lod.js.map
  106201. var BABYLON;
  106202. (function (BABYLON) {
  106203. var GLTF2;
  106204. (function (GLTF2) {
  106205. var Extensions;
  106206. (function (Extensions) {
  106207. var NAME = "MSFT_minecraftMesh";
  106208. /** @hidden */
  106209. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  106210. __extends(MSFT_minecraftMesh, _super);
  106211. function MSFT_minecraftMesh(loader) {
  106212. var _this = _super.call(this, loader) || this;
  106213. _this.name = NAME;
  106214. _this._onMaterialLoaded = function (material) {
  106215. if (material.needAlphaBlending()) {
  106216. material.forceDepthWrite = true;
  106217. material.separateCullingPass = true;
  106218. }
  106219. material.backFaceCulling = material.forceDepthWrite;
  106220. material.twoSidedLighting = true;
  106221. };
  106222. var meshes = loader._gltf.meshes;
  106223. if (meshes && meshes.length) {
  106224. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  106225. var mesh = meshes_1[_i];
  106226. if (mesh && mesh.extras && mesh.extras.MSFT_minecraftMesh) {
  106227. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  106228. break;
  106229. }
  106230. }
  106231. }
  106232. return _this;
  106233. }
  106234. return MSFT_minecraftMesh;
  106235. }(GLTF2.GLTFLoaderExtension));
  106236. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  106237. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  106238. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106239. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106240. })(BABYLON || (BABYLON = {}));
  106241. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  106242. var BABYLON;
  106243. (function (BABYLON) {
  106244. var GLTF2;
  106245. (function (GLTF2) {
  106246. var Extensions;
  106247. (function (Extensions) {
  106248. var NAME = "MSFT_sRGBFactors";
  106249. /** @hidden */
  106250. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  106251. __extends(MSFT_sRGBFactors, _super);
  106252. function MSFT_sRGBFactors(loader) {
  106253. var _this = _super.call(this, loader) || this;
  106254. _this.name = NAME;
  106255. _this._onMaterialLoaded = function (material) {
  106256. if (!material.albedoTexture) {
  106257. material.albedoColor.toLinearSpaceToRef(material.albedoColor);
  106258. }
  106259. if (!material.reflectivityTexture) {
  106260. material.reflectivityColor.toLinearSpaceToRef(material.reflectivityColor);
  106261. }
  106262. };
  106263. var materials = loader._gltf.materials;
  106264. if (materials && materials.length) {
  106265. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  106266. var material = materials_1[_i];
  106267. if (material && material.extras && material.extras.MSFT_sRGBFactors) {
  106268. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  106269. break;
  106270. }
  106271. }
  106272. }
  106273. return _this;
  106274. }
  106275. return MSFT_sRGBFactors;
  106276. }(GLTF2.GLTFLoaderExtension));
  106277. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  106278. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  106279. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106280. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106281. })(BABYLON || (BABYLON = {}));
  106282. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  106283. var BABYLON;
  106284. (function (BABYLON) {
  106285. var GLTF2;
  106286. (function (GLTF2) {
  106287. var Extensions;
  106288. (function (Extensions) {
  106289. var NAME = "KHR_draco_mesh_compression";
  106290. /**
  106291. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  106292. */
  106293. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  106294. __extends(KHR_draco_mesh_compression, _super);
  106295. function KHR_draco_mesh_compression(loader) {
  106296. var _this = _super.call(this, loader) || this;
  106297. _this.name = NAME;
  106298. _this._dracoCompression = null;
  106299. // Disable extension if decoder is not available.
  106300. if (!BABYLON.DracoCompression.DecoderAvailable) {
  106301. _this.enabled = false;
  106302. }
  106303. return _this;
  106304. }
  106305. KHR_draco_mesh_compression.prototype.dispose = function () {
  106306. if (this._dracoCompression) {
  106307. this._dracoCompression.dispose();
  106308. }
  106309. _super.prototype.dispose.call(this);
  106310. };
  106311. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  106312. var _this = this;
  106313. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  106314. if (primitive.mode != undefined) {
  106315. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  106316. primitive.mode !== 4 /* TRIANGLES */) {
  106317. throw new Error(context + ": Unsupported mode " + primitive.mode);
  106318. }
  106319. // TODO: handle triangle strips
  106320. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  106321. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  106322. }
  106323. }
  106324. var attributes = {};
  106325. var loadAttribute = function (name, kind) {
  106326. var uniqueId = extension.attributes[name];
  106327. if (uniqueId == undefined) {
  106328. return;
  106329. }
  106330. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  106331. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  106332. babylonMesh._delayInfo.push(kind);
  106333. }
  106334. attributes[kind] = uniqueId;
  106335. };
  106336. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  106337. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  106338. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  106339. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  106340. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  106341. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  106342. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  106343. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  106344. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  106345. if (!bufferView._dracoBabylonGeometry) {
  106346. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  106347. if (!_this._dracoCompression) {
  106348. _this._dracoCompression = new BABYLON.DracoCompression();
  106349. }
  106350. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  106351. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  106352. babylonVertexData.applyToGeometry(babylonGeometry);
  106353. return babylonGeometry;
  106354. }).catch(function (error) {
  106355. throw new Error(context + ": " + error.message);
  106356. });
  106357. });
  106358. }
  106359. return bufferView._dracoBabylonGeometry;
  106360. });
  106361. };
  106362. return KHR_draco_mesh_compression;
  106363. }(GLTF2.GLTFLoaderExtension));
  106364. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  106365. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  106366. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106367. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106368. })(BABYLON || (BABYLON = {}));
  106369. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  106370. var BABYLON;
  106371. (function (BABYLON) {
  106372. var GLTF2;
  106373. (function (GLTF2) {
  106374. var Extensions;
  106375. (function (Extensions) {
  106376. var NAME = "KHR_materials_pbrSpecularGlossiness";
  106377. /**
  106378. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  106379. */
  106380. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  106381. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  106382. function KHR_materials_pbrSpecularGlossiness() {
  106383. var _this = _super !== null && _super.apply(this, arguments) || this;
  106384. _this.name = NAME;
  106385. return _this;
  106386. }
  106387. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106388. var _this = this;
  106389. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  106390. material._babylonData = material._babylonData || {};
  106391. var babylonData = material._babylonData[babylonDrawMode];
  106392. if (!babylonData) {
  106393. var promises = new Array();
  106394. var name_1 = material.name || "materialSG_" + material._index;
  106395. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  106396. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  106397. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  106398. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106399. babylonData = {
  106400. material: babylonMaterial,
  106401. meshes: [],
  106402. loaded: Promise.all(promises).then(function () { })
  106403. };
  106404. material._babylonData[babylonDrawMode] = babylonData;
  106405. }
  106406. babylonData.meshes.push(babylonMesh);
  106407. assign(babylonData.material);
  106408. return babylonData.loaded;
  106409. });
  106410. };
  106411. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  106412. var promises = new Array();
  106413. if (properties.diffuseFactor) {
  106414. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  106415. babylonMaterial.alpha = properties.diffuseFactor[3];
  106416. }
  106417. else {
  106418. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106419. }
  106420. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  106421. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  106422. if (properties.diffuseTexture) {
  106423. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  106424. babylonMaterial.albedoTexture = texture;
  106425. }));
  106426. }
  106427. if (properties.specularGlossinessTexture) {
  106428. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  106429. babylonMaterial.reflectivityTexture = texture;
  106430. }));
  106431. babylonMaterial.reflectivityTexture.hasAlpha = true;
  106432. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  106433. }
  106434. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106435. return Promise.all(promises).then(function () { });
  106436. };
  106437. return KHR_materials_pbrSpecularGlossiness;
  106438. }(GLTF2.GLTFLoaderExtension));
  106439. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  106440. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  106441. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106442. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106443. })(BABYLON || (BABYLON = {}));
  106444. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  106445. var BABYLON;
  106446. (function (BABYLON) {
  106447. var GLTF2;
  106448. (function (GLTF2) {
  106449. var Extensions;
  106450. (function (Extensions) {
  106451. var NAME = "KHR_materials_unlit";
  106452. /**
  106453. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  106454. */
  106455. var KHR_materials_unlit = /** @class */ (function (_super) {
  106456. __extends(KHR_materials_unlit, _super);
  106457. function KHR_materials_unlit() {
  106458. var _this = _super !== null && _super.apply(this, arguments) || this;
  106459. _this.name = NAME;
  106460. return _this;
  106461. }
  106462. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106463. var _this = this;
  106464. return this._loadExtensionAsync(context, material, function () {
  106465. material._babylonData = material._babylonData || {};
  106466. var babylonData = material._babylonData[babylonDrawMode];
  106467. if (!babylonData) {
  106468. var name_1 = material.name || "materialUnlit_" + material._index;
  106469. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  106470. babylonMaterial.unlit = true;
  106471. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  106472. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106473. babylonData = {
  106474. material: babylonMaterial,
  106475. meshes: [],
  106476. loaded: promise
  106477. };
  106478. material._babylonData[babylonDrawMode] = babylonData;
  106479. }
  106480. babylonData.meshes.push(babylonMesh);
  106481. assign(babylonData.material);
  106482. return babylonData.loaded;
  106483. });
  106484. };
  106485. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  106486. var promises = new Array();
  106487. // Ensure metallic workflow
  106488. babylonMaterial.metallic = 1;
  106489. babylonMaterial.roughness = 1;
  106490. var properties = material.pbrMetallicRoughness;
  106491. if (properties) {
  106492. if (properties.baseColorFactor) {
  106493. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  106494. babylonMaterial.alpha = properties.baseColorFactor[3];
  106495. }
  106496. else {
  106497. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106498. }
  106499. if (properties.baseColorTexture) {
  106500. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  106501. babylonMaterial.albedoTexture = texture;
  106502. }));
  106503. }
  106504. }
  106505. if (material.doubleSided) {
  106506. babylonMaterial.backFaceCulling = false;
  106507. babylonMaterial.twoSidedLighting = true;
  106508. }
  106509. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106510. return Promise.all(promises).then(function () { });
  106511. };
  106512. return KHR_materials_unlit;
  106513. }(GLTF2.GLTFLoaderExtension));
  106514. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  106515. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  106516. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106517. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106518. })(BABYLON || (BABYLON = {}));
  106519. var BABYLON;
  106520. (function (BABYLON) {
  106521. var GLTF2;
  106522. (function (GLTF2) {
  106523. var Extensions;
  106524. (function (Extensions) {
  106525. var NAME = "KHR_lights";
  106526. var LightType;
  106527. (function (LightType) {
  106528. LightType["AMBIENT"] = "ambient";
  106529. LightType["DIRECTIONAL"] = "directional";
  106530. LightType["POINT"] = "point";
  106531. LightType["SPOT"] = "spot";
  106532. })(LightType || (LightType = {}));
  106533. /**
  106534. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  106535. */
  106536. var KHR_lights = /** @class */ (function (_super) {
  106537. __extends(KHR_lights, _super);
  106538. function KHR_lights() {
  106539. var _this = _super !== null && _super.apply(this, arguments) || this;
  106540. _this.name = NAME;
  106541. return _this;
  106542. }
  106543. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  106544. var _this = this;
  106545. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  106546. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  106547. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  106548. if (light.type !== LightType.AMBIENT) {
  106549. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  106550. }
  106551. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  106552. return promise;
  106553. });
  106554. };
  106555. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  106556. var _this = this;
  106557. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  106558. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  106559. var babylonLight;
  106560. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  106561. var name = node._babylonMesh.name;
  106562. switch (light.type) {
  106563. case LightType.AMBIENT: {
  106564. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  106565. }
  106566. case LightType.DIRECTIONAL: {
  106567. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  106568. break;
  106569. }
  106570. case LightType.POINT: {
  106571. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  106572. break;
  106573. }
  106574. case LightType.SPOT: {
  106575. var spotLight = light;
  106576. // TODO: support inner and outer cone angles
  106577. //const innerConeAngle = spotLight.innerConeAngle || 0;
  106578. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  106579. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  106580. break;
  106581. }
  106582. default: {
  106583. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  106584. }
  106585. }
  106586. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  106587. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  106588. babylonLight.parent = node._babylonMesh;
  106589. return promise;
  106590. });
  106591. };
  106592. Object.defineProperty(KHR_lights.prototype, "_lights", {
  106593. get: function () {
  106594. var extensions = this._loader._gltf.extensions;
  106595. if (!extensions || !extensions[this.name]) {
  106596. throw new Error("#/extensions: '" + this.name + "' not found");
  106597. }
  106598. var extension = extensions[this.name];
  106599. return extension.lights;
  106600. },
  106601. enumerable: true,
  106602. configurable: true
  106603. });
  106604. return KHR_lights;
  106605. }(GLTF2.GLTFLoaderExtension));
  106606. Extensions.KHR_lights = KHR_lights;
  106607. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  106608. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106609. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106610. })(BABYLON || (BABYLON = {}));
  106611. var BABYLON;
  106612. (function (BABYLON) {
  106613. var GLTF2;
  106614. (function (GLTF2) {
  106615. var Extensions;
  106616. (function (Extensions) {
  106617. var NAME = "KHR_texture_transform";
  106618. /**
  106619. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  106620. */
  106621. var KHR_texture_transform = /** @class */ (function (_super) {
  106622. __extends(KHR_texture_transform, _super);
  106623. function KHR_texture_transform() {
  106624. var _this = _super !== null && _super.apply(this, arguments) || this;
  106625. _this.name = NAME;
  106626. return _this;
  106627. }
  106628. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  106629. var _this = this;
  106630. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  106631. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  106632. if (extension.offset) {
  106633. babylonTexture.uOffset = extension.offset[0];
  106634. babylonTexture.vOffset = extension.offset[1];
  106635. }
  106636. // Always rotate around the origin.
  106637. babylonTexture.uRotationCenter = 0;
  106638. babylonTexture.vRotationCenter = 0;
  106639. if (extension.rotation) {
  106640. babylonTexture.wAng = -extension.rotation;
  106641. }
  106642. if (extension.scale) {
  106643. babylonTexture.uScale = extension.scale[0];
  106644. babylonTexture.vScale = extension.scale[1];
  106645. }
  106646. if (extension.texCoord != undefined) {
  106647. babylonTexture.coordinatesIndex = extension.texCoord;
  106648. }
  106649. assign(babylonTexture);
  106650. });
  106651. });
  106652. };
  106653. return KHR_texture_transform;
  106654. }(GLTF2.GLTFLoaderExtension));
  106655. Extensions.KHR_texture_transform = KHR_texture_transform;
  106656. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  106657. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106658. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106659. })(BABYLON || (BABYLON = {}));
  106660. return BABYLON;
  106661. });
  106662. /***/ }),
  106663. /* 21 */
  106664. /***/ (function(module, exports, __webpack_require__) {
  106665. module.exports = __webpack_require__(6);
  106666. /***/ }),
  106667. /* 22 */
  106668. /***/ (function(module, exports) {
  106669. var g;
  106670. // This works in non-strict mode
  106671. g = (function() {
  106672. return this;
  106673. })();
  106674. try {
  106675. // This works if eval is allowed (see CSP)
  106676. g = g || Function("return this")() || (1,eval)("this");
  106677. } catch(e) {
  106678. // This works if the window reference is available
  106679. if(typeof window === "object")
  106680. g = window;
  106681. }
  106682. // g can still be undefined, but nothing to do about it...
  106683. // We return undefined, instead of nothing here, so it's
  106684. // easier to handle this case. if(!global) { ...}
  106685. module.exports = g;
  106686. /***/ }),
  106687. /* 23 */
  106688. /***/ (function(module, exports) {
  106689. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106690. module.exports = CANNON;
  106691. /***/ }),
  106692. /* 24 */
  106693. /***/ (function(module, exports) {
  106694. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106695. module.exports = OIMO;
  106696. /***/ }),
  106697. /* 25 */
  106698. /***/ (function(module, exports) {
  106699. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106700. module.exports = earcut;
  106701. /***/ }),
  106702. /* 26 */
  106703. /***/ (function(module, exports, __webpack_require__) {
  106704. "use strict";
  106705. Object.defineProperty(exports, "__esModule", { value: true });
  106706. var babylonjs_1 = __webpack_require__(0);
  106707. var configuration_1 = __webpack_require__(27);
  106708. var viewerModel_1 = __webpack_require__(4);
  106709. var helper_1 = __webpack_require__(2);
  106710. var viewerLabs_1 = __webpack_require__(29);
  106711. var _1 = __webpack_require__(31);
  106712. var SceneManager = /** @class */ (function () {
  106713. function SceneManager(_viewer) {
  106714. var _this = this;
  106715. this._viewer = _viewer;
  106716. this._animationBlendingEnabled = true;
  106717. this._mainColor = babylonjs_1.Color3.White();
  106718. this._reflectionColor = babylonjs_1.Color3.White();
  106719. this._white = babylonjs_1.Color3.White();
  106720. this._processShadows = true;
  106721. this._groundEnabled = true;
  106722. this._groundMirrorEnabled = false;
  106723. this._defaultRenderingPipelineEnabled = false;
  106724. this._defaultRenderingPipelineShouldBuild = true;
  106725. // default from rendering pipeline
  106726. this._bloomEnabled = false;
  106727. // default from rendering pipeline
  106728. this._fxaaEnabled = false;
  106729. this._focusOnModel = function (model) {
  106730. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  106731. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  106732. var halfSizeVec = sizeVec.scale(0.5);
  106733. var center = boundingInfo.min.add(halfSizeVec);
  106734. _this.camera.setTarget(center);
  106735. _this.camera.alpha = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.alpha) || _this.camera.alpha;
  106736. _this.camera.beta = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.beta) || _this.camera.beta;
  106737. _this.camera.radius = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.radius) || _this.camera.radius;
  106738. };
  106739. this.models = [];
  106740. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  106741. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  106742. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  106743. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  106744. this.onSceneInitObservable = new babylonjs_1.Observable();
  106745. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  106746. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  106747. this._viewer.onEngineInitObservable.add(function () {
  106748. _this._handleHardwareLimitations();
  106749. });
  106750. this.labs = new viewerLabs_1.ViewerLabs(this);
  106751. this.onSceneInitObservable.add(function (scene) {
  106752. scene.registerBeforeRender(function () {
  106753. if (_this.models.length && scene.animatables && scene.animatables.length > 0) {
  106754. // make sure all models are loaded
  106755. if (_this.models.every(function (model) { return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation; }))
  106756. return;
  106757. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  106758. var light = _a[_i];
  106759. var generator = light.getShadowGenerator();
  106760. if (generator) {
  106761. // Processing shadows if animates
  106762. var shadowMap = generator.getShadowMap();
  106763. if (shadowMap) {
  106764. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106765. }
  106766. }
  106767. }
  106768. }
  106769. });
  106770. return _this._viewer.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  106771. });
  106772. this._viewer.onModelLoadedObservable.add(function (model) {
  106773. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  106774. var light = _a[_i];
  106775. var generator = light.getShadowGenerator();
  106776. if (generator) {
  106777. // Processing shadows if animates
  106778. var shadowMap = generator.getShadowMap();
  106779. if (shadowMap) {
  106780. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106781. }
  106782. }
  106783. }
  106784. _this._focusOnModel(model);
  106785. });
  106786. }
  106787. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  106788. get: function () {
  106789. return this._defaultRenderingPipeline;
  106790. },
  106791. enumerable: true,
  106792. configurable: true
  106793. });
  106794. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  106795. /**
  106796. * Returns a boolean representing HDR support
  106797. */
  106798. get: function () {
  106799. return this._hdrSupport;
  106800. },
  106801. enumerable: true,
  106802. configurable: true
  106803. });
  106804. Object.defineProperty(SceneManager.prototype, "mainColor", {
  106805. /**
  106806. * Return the main color defined in the configuration.
  106807. */
  106808. get: function () {
  106809. return this._mainColor;
  106810. },
  106811. enumerable: true,
  106812. configurable: true
  106813. });
  106814. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  106815. get: function () {
  106816. return this._reflectionColor;
  106817. },
  106818. enumerable: true,
  106819. configurable: true
  106820. });
  106821. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  106822. get: function () {
  106823. return this._animationBlendingEnabled;
  106824. },
  106825. set: function (value) {
  106826. this.scene.animationPropertiesOverride = this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  106827. this.scene.animationPropertiesOverride.enableBlending = value;
  106828. this._animationBlendingEnabled = value;
  106829. },
  106830. enumerable: true,
  106831. configurable: true
  106832. });
  106833. Object.defineProperty(SceneManager.prototype, "processShadows", {
  106834. /**
  106835. * The flag defining whether shadows are rendered constantly or once.
  106836. */
  106837. get: function () {
  106838. return this._processShadows;
  106839. },
  106840. /**
  106841. * Should shadows be rendered every frame, or only once and stop.
  106842. * This can be used to optimize a scene.
  106843. *
  106844. * Not that the shadows will NOT disapear but will remain in place.
  106845. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  106846. */
  106847. set: function (process) {
  106848. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106849. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  106850. var light = _a[_i];
  106851. var generator = light.getShadowGenerator();
  106852. if (generator) {
  106853. var shadowMap = generator.getShadowMap();
  106854. if (shadowMap) {
  106855. shadowMap.refreshRate = refreshType;
  106856. }
  106857. }
  106858. }
  106859. this._processShadows = process;
  106860. },
  106861. enumerable: true,
  106862. configurable: true
  106863. });
  106864. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  106865. get: function () {
  106866. return this._groundEnabled;
  106867. },
  106868. set: function (newValue) {
  106869. if (newValue === this._groundEnabled)
  106870. return;
  106871. this._groundEnabled = newValue;
  106872. if (this.environmentHelper && this.environmentHelper.ground) {
  106873. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  106874. }
  106875. },
  106876. enumerable: true,
  106877. configurable: true
  106878. });
  106879. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  106880. /**
  106881. * gets wether the reflection is disabled.
  106882. */
  106883. get: function () {
  106884. return this._groundMirrorEnabled;
  106885. },
  106886. /**
  106887. * sets wether the reflection is disabled.
  106888. */
  106889. set: function (value) {
  106890. if (this._groundMirrorEnabled === value) {
  106891. return;
  106892. }
  106893. this._groundMirrorEnabled = value;
  106894. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  106895. if (value) {
  106896. this.environmentHelper.groundMaterial.reflectionTexture = null;
  106897. }
  106898. else {
  106899. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  106900. }
  106901. }
  106902. },
  106903. enumerable: true,
  106904. configurable: true
  106905. });
  106906. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  106907. get: function () {
  106908. return this._defaultRenderingPipelineEnabled;
  106909. },
  106910. set: function (value) {
  106911. if (value === this._defaultRenderingPipelineEnabled) {
  106912. return;
  106913. }
  106914. this._defaultRenderingPipelineEnabled = value;
  106915. this._rebuildPostprocesses();
  106916. if (this._defaultRenderingPipeline) {
  106917. this._defaultRenderingPipelineShouldBuild = false;
  106918. this._defaultRenderingPipeline.prepare();
  106919. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  106920. }
  106921. },
  106922. enumerable: true,
  106923. configurable: true
  106924. });
  106925. /**
  106926. * Sets the engine flags to unlock all babylon features.
  106927. * Can also be configured using the scene.flags configuration object
  106928. */
  106929. SceneManager.prototype.unlockBabylonFeatures = function () {
  106930. this.scene.shadowsEnabled = true;
  106931. this.scene.particlesEnabled = true;
  106932. this.scene.postProcessesEnabled = true;
  106933. this.scene.collisionsEnabled = true;
  106934. this.scene.lightsEnabled = true;
  106935. this.scene.texturesEnabled = true;
  106936. this.scene.lensFlaresEnabled = true;
  106937. this.scene.proceduralTexturesEnabled = true;
  106938. this.scene.renderTargetsEnabled = true;
  106939. this.scene.spritesEnabled = true;
  106940. this.scene.skeletonsEnabled = true;
  106941. this.scene.audioEnabled = true;
  106942. };
  106943. /**
  106944. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  106945. */
  106946. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  106947. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  106948. // if the scen exists, dispose it.
  106949. if (this.scene) {
  106950. this.scene.dispose();
  106951. }
  106952. // create a new scene
  106953. this.scene = new babylonjs_1.Scene(this._viewer.engine);
  106954. // set a default PBR material
  106955. if (!sceneConfiguration.defaultMaterial) {
  106956. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  106957. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  106958. defaultMaterial.microSurface = 0.6;
  106959. if (this.scene.defaultMaterial) {
  106960. this.scene.defaultMaterial.dispose();
  106961. }
  106962. this.scene.defaultMaterial = defaultMaterial;
  106963. }
  106964. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  106965. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  106966. this._mainColor = babylonjs_1.Color3.White();
  106967. if (sceneConfiguration.glow) {
  106968. var options = {
  106969. mainTextureFixedSize: 512
  106970. };
  106971. if (typeof sceneConfiguration.glow === 'object') {
  106972. options = sceneConfiguration.glow;
  106973. }
  106974. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  106975. }
  106976. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  106977. };
  106978. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  106979. if (clearModels === void 0) { clearModels = true; }
  106980. if (clearLights === void 0) { clearLights = false; }
  106981. if (clearModels) {
  106982. this.models.forEach(function (m) { return m.dispose(); });
  106983. this.models.length = 0;
  106984. }
  106985. if (clearLights) {
  106986. this.scene.lights.forEach(function (l) { return l.dispose(); });
  106987. }
  106988. };
  106989. /**
  106990. * This will update the scene's configuration, including camera, lights, environment.
  106991. * @param newConfiguration the delta that should be configured. This includes only the changes
  106992. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  106993. */
  106994. SceneManager.prototype.updateConfiguration = function (newConfiguration, globalConfiguration) {
  106995. var _this = this;
  106996. if (newConfiguration.lab) {
  106997. if (newConfiguration.lab.assetsRootURL) {
  106998. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  106999. }
  107000. }
  107001. // update scene configuration
  107002. if (newConfiguration.scene) {
  107003. this._configureScene(newConfiguration.scene);
  107004. }
  107005. // optimizer
  107006. if (newConfiguration.optimizer) {
  107007. this._configureOptimizer(newConfiguration.optimizer);
  107008. }
  107009. // configure model
  107010. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  107011. this._configureModel(newConfiguration.model);
  107012. }*/
  107013. // lights
  107014. this._configureLights(newConfiguration.lights);
  107015. // environment
  107016. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  107017. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  107018. }
  107019. // camera
  107020. this._configureCamera(newConfiguration.camera);
  107021. if (newConfiguration.lab) {
  107022. if (newConfiguration.lab.environmentMap) {
  107023. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  107024. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  107025. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  107026. });
  107027. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  107028. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  107029. }
  107030. }
  107031. // rendering piplines
  107032. if (newConfiguration.lab.defaultRenderingPipelines) {
  107033. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  107034. if (typeof pipelineConfig === 'boolean') {
  107035. this.defaultRenderingPipelineEnabled = pipelineConfig;
  107036. }
  107037. else {
  107038. this.defaultRenderingPipelineEnabled = true;
  107039. }
  107040. }
  107041. if (newConfiguration.lab.environmentMainColor) {
  107042. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  107043. this.environmentHelper.setMainColor(mainColor);
  107044. }
  107045. }
  107046. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  107047. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  107048. }
  107049. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  107050. this._defaultRenderingPipelineShouldBuild = false;
  107051. this._defaultRenderingPipeline.prepare();
  107052. }
  107053. };
  107054. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  107055. if (!this.defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._viewer.configuration)) {
  107056. if (this._defaultRenderingPipeline) {
  107057. this._defaultRenderingPipeline.dispose();
  107058. this._defaultRenderingPipeline = null;
  107059. this.scene.autoClearDepthAndStencil = true;
  107060. this.scene.autoClear = true;
  107061. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  107062. }
  107063. return;
  107064. }
  107065. var pipelineConfig = configuration || (this._viewer.configuration.lab && this._viewer.configuration.lab.defaultRenderingPipelines);
  107066. if (pipelineConfig) {
  107067. if (!this._defaultRenderingPipeline) {
  107068. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  107069. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  107070. }
  107071. this.scene.autoClear = false;
  107072. this.scene.autoClearDepthAndStencil = false;
  107073. this._defaultRenderingPipelineShouldBuild = true;
  107074. var bloomEnabled = this._bloomEnabled;
  107075. if (typeof pipelineConfig !== 'boolean') {
  107076. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  107077. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  107078. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  107079. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  107080. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  107081. }
  107082. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  107083. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  107084. }
  107085. };
  107086. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  107087. get: function () {
  107088. return this._bloomEnabled;
  107089. },
  107090. set: function (value) {
  107091. if (this._bloomEnabled === value) {
  107092. return;
  107093. }
  107094. this._bloomEnabled = value;
  107095. this._rebuildPostprocesses();
  107096. if (this._defaultRenderingPipeline) {
  107097. this._defaultRenderingPipelineShouldBuild = false;
  107098. this._defaultRenderingPipeline.prepare();
  107099. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  107100. }
  107101. },
  107102. enumerable: true,
  107103. configurable: true
  107104. });
  107105. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  107106. get: function () {
  107107. return this._fxaaEnabled;
  107108. },
  107109. set: function (value) {
  107110. if (this._fxaaEnabled === value) {
  107111. return;
  107112. }
  107113. this._fxaaEnabled = value;
  107114. this._rebuildPostprocesses();
  107115. if (this._defaultRenderingPipeline) {
  107116. this._defaultRenderingPipelineShouldBuild = false;
  107117. this._defaultRenderingPipeline.prepare();
  107118. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  107119. }
  107120. },
  107121. enumerable: true,
  107122. configurable: true
  107123. });
  107124. /**
  107125. * internally configure the scene using the provided configuration.
  107126. * The scene will not be recreated, but just updated.
  107127. * @param sceneConfig the (new) scene configuration
  107128. */
  107129. SceneManager.prototype._configureScene = function (sceneConfig) {
  107130. // sanity check!
  107131. if (!this.scene) {
  107132. return;
  107133. }
  107134. var cc = sceneConfig.clearColor;
  107135. var oldcc = this.scene.clearColor;
  107136. if (cc) {
  107137. if (cc.r !== undefined) {
  107138. oldcc.r = cc.r;
  107139. }
  107140. if (cc.g !== undefined) {
  107141. oldcc.g = cc.g;
  107142. }
  107143. if (cc.b !== undefined) {
  107144. oldcc.b = cc.b;
  107145. }
  107146. if (cc.a !== undefined) {
  107147. oldcc.a = cc.a;
  107148. }
  107149. }
  107150. // image processing configuration - optional.
  107151. if (sceneConfig.imageProcessingConfiguration) {
  107152. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  107153. }
  107154. //animation properties override
  107155. if (sceneConfig.animationPropertiesOverride) {
  107156. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  107157. }
  107158. if (sceneConfig.environmentTexture) {
  107159. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  107160. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  107161. this.scene.environmentTexture.dispose();
  107162. }
  107163. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  107164. this.scene.environmentTexture = environmentTexture;
  107165. }
  107166. }
  107167. if (sceneConfig.debug) {
  107168. this.scene.debugLayer.show();
  107169. }
  107170. else {
  107171. if (this.scene.debugLayer.isVisible()) {
  107172. this.scene.debugLayer.hide();
  107173. }
  107174. }
  107175. if (sceneConfig.disableHdr) {
  107176. this._handleHardwareLimitations(false);
  107177. }
  107178. else {
  107179. this._handleHardwareLimitations(true);
  107180. }
  107181. if (sceneConfig.renderInBackground !== undefined) {
  107182. this._viewer.renderInBackground = !!sceneConfig.renderInBackground;
  107183. }
  107184. if (this.camera && sceneConfig.disableCameraControl) {
  107185. this.camera.detachControl(this._viewer.canvas);
  107186. }
  107187. else if (this.camera && sceneConfig.disableCameraControl === false) {
  107188. this.camera.attachControl(this._viewer.canvas);
  107189. }
  107190. // process mainColor changes:
  107191. if (sceneConfig.mainColor) {
  107192. this._mainColor = this._mainColor || babylonjs_1.Color3.White();
  107193. var mc = sceneConfig.mainColor;
  107194. if (mc.r !== undefined) {
  107195. this._mainColor.r = mc.r;
  107196. }
  107197. if (mc.g !== undefined) {
  107198. this._mainColor.g = mc.g;
  107199. }
  107200. if (mc.b !== undefined) {
  107201. this._mainColor.b = mc.b;
  107202. }
  107203. this._reflectionColor.copyFrom(this.mainColor);
  107204. if (this._viewer.configuration.camera && this._viewer.configuration.camera.exposure) {
  107205. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._viewer.configuration) || 0;
  107206. /*this._mainColor.toLinearSpaceToRef(this._mainColor);
  107207. let exposure = Math.pow(2.0, -(this._viewer.configuration.camera.exposure) * Math.PI);
  107208. this._mainColor.scaleToRef(1 / exposure, this._mainColor);
  107209. let tmpColor = Color3.Lerp(this._white, this._mainColor, environmentTint);
  107210. this._mainColor.copyFrom(tmpColor);*/
  107211. // reflection color
  107212. this._reflectionColor.toLinearSpaceToRef(this._reflectionColor);
  107213. this._reflectionColor.scaleToRef(1 / this._viewer.configuration.camera.exposure, this._reflectionColor);
  107214. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this._reflectionColor, environmentTint);
  107215. this._reflectionColor.copyFrom(tmpColor3);
  107216. }
  107217. //update the environment, if exists
  107218. if (this.environmentHelper) {
  107219. if (this.environmentHelper.groundMaterial) {
  107220. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  107221. }
  107222. if (this.environmentHelper.skyboxMaterial) {
  107223. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  107224. }
  107225. }
  107226. }
  107227. if (sceneConfig.defaultMaterial) {
  107228. var conf = sceneConfig.defaultMaterial;
  107229. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  107230. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  107231. this.scene.defaultMaterial.dispose();
  107232. if (conf.materialType === 'standard') {
  107233. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  107234. }
  107235. else {
  107236. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  107237. }
  107238. }
  107239. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  107240. }
  107241. if (sceneConfig.flags) {
  107242. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  107243. }
  107244. this.onSceneConfiguredObservable.notifyObservers({
  107245. sceneManager: this,
  107246. object: this.scene,
  107247. newConfiguration: sceneConfig
  107248. });
  107249. };
  107250. /**
  107251. * Configure the scene optimizer.
  107252. * The existing scene optimizer will be disposed and a new one will be created.
  107253. * @param optimizerConfig the (new) optimizer configuration
  107254. */
  107255. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  107256. var _this = this;
  107257. if (typeof optimizerConfig === 'boolean') {
  107258. if (this.sceneOptimizer) {
  107259. this.sceneOptimizer.stop();
  107260. this.sceneOptimizer.dispose();
  107261. delete this.sceneOptimizer;
  107262. }
  107263. if (optimizerConfig) {
  107264. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  107265. this.sceneOptimizer.start();
  107266. }
  107267. }
  107268. else {
  107269. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  107270. // check for degradation
  107271. if (optimizerConfig.degradation) {
  107272. switch (optimizerConfig.degradation) {
  107273. case "low":
  107274. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  107275. break;
  107276. case "moderate":
  107277. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  107278. break;
  107279. case "hight":
  107280. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  107281. break;
  107282. }
  107283. }
  107284. if (this.sceneOptimizer) {
  107285. this.sceneOptimizer.stop();
  107286. this.sceneOptimizer.dispose();
  107287. }
  107288. if (optimizerConfig.custom) {
  107289. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  107290. if (customOptimizer_1) {
  107291. optimizerOptions.addCustomOptimization(function () {
  107292. return customOptimizer_1(_this._viewer);
  107293. }, function () {
  107294. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  107295. });
  107296. }
  107297. }
  107298. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  107299. this.sceneOptimizer.start();
  107300. }
  107301. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  107302. sceneManager: this,
  107303. object: this.sceneOptimizer,
  107304. newConfiguration: optimizerConfig
  107305. });
  107306. };
  107307. /**
  107308. * configure all models using the configuration.
  107309. * @param modelConfiguration the configuration to use to reconfigure the models
  107310. */
  107311. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  107312. this.models.forEach(model => {
  107313. model.updateConfiguration(modelConfiguration);
  107314. });
  107315. this.onModelsConfiguredObservable.notifyObservers({
  107316. sceneManager: this,
  107317. object: this.models,
  107318. newConfiguration: modelConfiguration
  107319. });
  107320. }*/
  107321. /**
  107322. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  107323. * @param cameraConfig the new camera configuration
  107324. * @param model optionally use the model to configure the camera.
  107325. */
  107326. SceneManager.prototype._configureCamera = function (cameraConfig) {
  107327. var _this = this;
  107328. if (cameraConfig === void 0) { cameraConfig = {}; }
  107329. if (!this.scene.activeCamera) {
  107330. var attachControl = true;
  107331. if (this._viewer.configuration.scene && this._viewer.configuration.scene.disableCameraControl) {
  107332. attachControl = false;
  107333. }
  107334. this.scene.createDefaultCamera(true, true, attachControl);
  107335. this.camera = this.scene.activeCamera;
  107336. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  107337. }
  107338. if (cameraConfig.position) {
  107339. var newPosition = this.camera.position.clone();
  107340. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  107341. this.camera.setPosition(newPosition);
  107342. }
  107343. if (cameraConfig.target) {
  107344. var newTarget = this.camera.target.clone();
  107345. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  107346. this.camera.setTarget(newTarget);
  107347. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  107348. this._focusOnModel(this.models[0]);
  107349. }*/
  107350. if (cameraConfig.rotation) {
  107351. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  107352. }
  107353. if (cameraConfig.behaviors) {
  107354. for (var name_1 in cameraConfig.behaviors) {
  107355. if (cameraConfig.behaviors[name_1]) {
  107356. this._setCameraBehavior(cameraConfig.behaviors[name_1]);
  107357. }
  107358. }
  107359. }
  107360. ;
  107361. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  107362. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  107363. });
  107364. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  107365. var sceneDiagonalLenght = sceneDiagonal.length();
  107366. if (isFinite(sceneDiagonalLenght))
  107367. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  107368. else {
  107369. this.camera.upperRadiusLimit = 10;
  107370. }
  107371. // sanity check!
  107372. if (this.scene.imageProcessingConfiguration) {
  107373. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  107374. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  107375. if (cameraConfig.contrast !== undefined)
  107376. this.scene.imageProcessingConfiguration.contrast = cameraConfig.contrast;
  107377. if (cameraConfig.exposure !== undefined)
  107378. this.scene.imageProcessingConfiguration.exposure = cameraConfig.exposure;
  107379. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!cameraConfig.toneMappingEnabled;
  107380. }
  107381. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  107382. this.onCameraConfiguredObservable.notifyObservers({
  107383. sceneManager: this,
  107384. object: this.camera,
  107385. newConfiguration: cameraConfig
  107386. });
  107387. };
  107388. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  107389. var _this = this;
  107390. if (!skyboxConifguration && !groundConfiguration) {
  107391. if (this.environmentHelper) {
  107392. this.environmentHelper.dispose();
  107393. delete this.environmentHelper;
  107394. }
  107395. ;
  107396. return Promise.resolve(this.scene);
  107397. }
  107398. var options = {
  107399. createGround: !!groundConfiguration && this._groundEnabled,
  107400. createSkybox: !!skyboxConifguration,
  107401. setupImageProcessing: false,
  107402. };
  107403. // will that cause problems with model ground configuration?
  107404. /*if (model) {
  107405. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  107406. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  107407. const halfSizeVec = sizeVec.scale(0.5);
  107408. const center = boundingInfo.min.add(halfSizeVec);
  107409. options.groundYBias = -center.y;
  107410. }*/
  107411. if (groundConfiguration) {
  107412. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  107413. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  107414. if (groundSize) {
  107415. options.groundSize = groundSize;
  107416. }
  107417. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  107418. if (groundConfig_1.shadowLevel !== undefined) {
  107419. options.groundShadowLevel = groundConfig_1.shadowLevel;
  107420. }
  107421. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  107422. if (groundConfig_1.texture) {
  107423. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  107424. }
  107425. if (groundConfig_1.color) {
  107426. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  107427. }
  107428. if (groundConfig_1.opacity !== undefined) {
  107429. options.groundOpacity = groundConfig_1.opacity;
  107430. }
  107431. if (groundConfig_1.mirror) {
  107432. options.enableGroundMirror = true;
  107433. // to prevent undefines
  107434. if (typeof groundConfig_1.mirror === "object") {
  107435. if (groundConfig_1.mirror.amount !== undefined)
  107436. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  107437. if (groundConfig_1.mirror.sizeRatio !== undefined)
  107438. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  107439. if (groundConfig_1.mirror.blurKernel !== undefined)
  107440. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  107441. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  107442. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  107443. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  107444. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  107445. if (this._defaultPipelineTextureType !== undefined)
  107446. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  107447. }
  107448. }
  107449. }
  107450. var postInitSkyboxMaterial = false;
  107451. if (skyboxConifguration) {
  107452. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  107453. if (conf.material && conf.material.imageProcessingConfiguration) {
  107454. options.setupImageProcessing = false; // will be configured later manually.
  107455. }
  107456. var skyboxSize = conf.scale;
  107457. if (skyboxSize) {
  107458. options.skyboxSize = skyboxSize;
  107459. }
  107460. options.sizeAuto = !options.skyboxSize;
  107461. if (conf.color) {
  107462. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  107463. }
  107464. if (conf.cubeTexture && conf.cubeTexture.url) {
  107465. if (typeof conf.cubeTexture.url === "string") {
  107466. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  107467. }
  107468. else {
  107469. // init later!
  107470. postInitSkyboxMaterial = true;
  107471. }
  107472. }
  107473. if (conf.material) {
  107474. postInitSkyboxMaterial = true;
  107475. }
  107476. }
  107477. options.setupImageProcessing = false; // TMP
  107478. if (!this.environmentHelper) {
  107479. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  107480. }
  107481. else {
  107482. // there might be a new scene! we need to dispose.
  107483. // get the scene used by the envHelper
  107484. var scene = this.environmentHelper.rootMesh.getScene();
  107485. // is it a different scene? Oh no!
  107486. if (scene !== this.scene) {
  107487. this.environmentHelper.dispose();
  107488. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  107489. }
  107490. else {
  107491. this.environmentHelper.updateOptions(options);
  107492. }
  107493. }
  107494. if (this.environmentHelper.rootMesh && this._viewer.configuration.scene && this._viewer.configuration.scene.environmentRotationY !== undefined) {
  107495. this.environmentHelper.rootMesh.rotation.y = this._viewer.configuration.scene.environmentRotationY;
  107496. }
  107497. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  107498. if (this.environmentHelper.groundMaterial && groundConfig && groundConfig.material) {
  107499. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  107500. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  107501. if (this.environmentHelper.groundMirror) {
  107502. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  107503. // TODO user camera exposure value to set the mirror clear color
  107504. //let exposure = Math.pow(2.0, -this.configuration.camera.exposure) * Math.PI;
  107505. //mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  107506. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  107507. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  107508. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  107509. this.environmentHelper.groundMirror.clearColor.a = 1;
  107510. if (!this.groundMirrorEnabled) {
  107511. this.environmentHelper.groundMaterial.reflectionTexture = null;
  107512. }
  107513. }
  107514. }
  107515. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  107516. if (skyboxMaterial) {
  107517. skyboxMaterial._perceptualColor = this.mainColor;
  107518. if (postInitSkyboxMaterial) {
  107519. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  107520. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  107521. }
  107522. }
  107523. }
  107524. this._viewer.onModelLoadedObservable.add(function (model) {
  107525. _this._updateGroundMirrorRenderList(model);
  107526. });
  107527. this.onEnvironmentConfiguredObservable.notifyObservers({
  107528. sceneManager: this,
  107529. object: this.environmentHelper,
  107530. newConfiguration: {
  107531. skybox: skyboxConifguration,
  107532. ground: groundConfiguration
  107533. }
  107534. });
  107535. };
  107536. /**
  107537. * configure the lights.
  107538. *
  107539. * @param lightsConfiguration the (new) light(s) configuration
  107540. * @param model optionally use the model to configure the camera.
  107541. */
  107542. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  107543. var _this = this;
  107544. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  107545. // sanity check!
  107546. if (!Object.keys(lightsConfiguration).length) {
  107547. if (!this.scene.lights.length)
  107548. this.scene.createDefaultLight(true);
  107549. return;
  107550. }
  107551. ;
  107552. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  107553. // compare to the global (!) configuration object and dispose unneeded:
  107554. var lightsToConfigure = Object.keys(this._viewer.configuration.lights || []);
  107555. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  107556. lightsAvailable.forEach(function (lName) {
  107557. if (lightsToConfigure.indexOf(lName) === -1) {
  107558. _this.scene.getLightByName(lName).dispose();
  107559. }
  107560. });
  107561. }
  107562. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  107563. var lightConfig = { type: 0 };
  107564. if (typeof lightsConfiguration[name] === 'object') {
  107565. lightConfig = lightsConfiguration[name];
  107566. }
  107567. lightConfig.name = name;
  107568. var light;
  107569. // light is not already available
  107570. if (lightsAvailable.indexOf(name) === -1) {
  107571. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  107572. if (!constructor)
  107573. return;
  107574. light = constructor();
  107575. }
  107576. else {
  107577. // available? get it from the scene
  107578. light = _this.scene.getLightByName(name);
  107579. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  107580. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  107581. light.dispose();
  107582. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  107583. if (!constructor)
  107584. return;
  107585. light = constructor();
  107586. }
  107587. }
  107588. // if config set the light to false, dispose it.
  107589. if (lightsConfiguration[name] === false) {
  107590. light.dispose();
  107591. return;
  107592. }
  107593. //enabled
  107594. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  107595. light.setEnabled(enabled);
  107596. helper_1.extendClassWithConfig(light, lightConfig);
  107597. //position. Some lights don't support shadows
  107598. if (light instanceof babylonjs_1.ShadowLight) {
  107599. // set default values
  107600. light.shadowMinZ = light.shadowMinZ || 0.2;
  107601. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  107602. if (lightConfig.target) {
  107603. if (light.setDirectionToTarget) {
  107604. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  107605. light.setDirectionToTarget(target);
  107606. }
  107607. }
  107608. else if (lightConfig.direction) {
  107609. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  107610. light.direction = direction;
  107611. }
  107612. var isShadowEnabled = false;
  107613. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  107614. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  107615. isShadowEnabled = true;
  107616. }
  107617. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  107618. var spotLight = light;
  107619. if (lightConfig.spotAngle !== undefined) {
  107620. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  107621. }
  107622. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  107623. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  107624. }
  107625. isShadowEnabled = true;
  107626. }
  107627. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  107628. if (lightConfig.shadowFieldOfView) {
  107629. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  107630. }
  107631. isShadowEnabled = true;
  107632. }
  107633. var shadowGenerator_1 = light.getShadowGenerator();
  107634. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  107635. var bufferSize = lightConfig.shadowBufferSize || 256;
  107636. if (!shadowGenerator_1) {
  107637. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  107638. }
  107639. var blurKernel = _this.getBlurKernel(light, bufferSize);
  107640. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  107641. shadowGenerator_1.blurKernel = blurKernel;
  107642. //override defaults
  107643. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  107644. // add the focues meshes to the shadow list
  107645. _this._viewer.onModelLoadedObservable.add(function (model) {
  107646. _this._updateShadowRenderList(shadowGenerator_1, model);
  107647. });
  107648. //if (model) {
  107649. _this._updateShadowRenderList(shadowGenerator_1);
  107650. //}
  107651. }
  107652. else if (shadowGenerator_1) {
  107653. shadowGenerator_1.dispose();
  107654. }
  107655. }
  107656. });
  107657. // render priority
  107658. var globalLightsConfiguration = this._viewer.configuration.lights || {};
  107659. Object.keys(globalLightsConfiguration).sort().forEach(function (name, idx) {
  107660. var configuration = globalLightsConfiguration[name];
  107661. var light = _this.scene.getLightByName(name);
  107662. // sanity check
  107663. if (!light)
  107664. return;
  107665. light.renderPriority = -idx;
  107666. });
  107667. this.onLightsConfiguredObservable.notifyObservers({
  107668. sceneManager: this,
  107669. object: this.scene.lights,
  107670. newConfiguration: lightsConfiguration
  107671. });
  107672. };
  107673. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  107674. var focusMeshes = model ? model.meshes : this.scene.meshes;
  107675. // add the focues meshes to the shadow list
  107676. var shadownMap = shadowGenerator.getShadowMap();
  107677. if (!shadownMap)
  107678. return;
  107679. if (resetList && shadownMap.renderList) {
  107680. shadownMap.renderList.length = 0;
  107681. }
  107682. else {
  107683. shadownMap.renderList = shadownMap.renderList || [];
  107684. }
  107685. for (var index = 0; index < focusMeshes.length; index++) {
  107686. var mesh = focusMeshes[index];
  107687. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  107688. shadownMap.renderList.push(mesh);
  107689. }
  107690. }
  107691. if (!this._shadowGroundPlane) {
  107692. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  107693. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  107694. shadowGroundPlane.useVertexColors = false;
  107695. //material isn't ever used in rendering, just used to set back face culling
  107696. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  107697. shadowGroundPlane.material.backFaceCulling = false;
  107698. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  107699. shadowGroundPlane.freezeWorldMatrix();
  107700. this._shadowGroundPlane = shadowGroundPlane;
  107701. this.scene.removeMesh(shadowGroundPlane);
  107702. }
  107703. }
  107704. else {
  107705. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  107706. this._shadowGroundPlane.dispose();
  107707. this._shadowGroundPlane = null;
  107708. }
  107709. }
  107710. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  107711. shadownMap.renderList.push(this._shadowGroundPlane);
  107712. }
  107713. };
  107714. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  107715. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  107716. var focusMeshes = model ? model.meshes : this.scene.meshes;
  107717. var renderList = this.environmentHelper.groundMirror.renderList;
  107718. if (resetList) {
  107719. renderList.length = 0;
  107720. }
  107721. for (var index = 0; index < focusMeshes.length; index++) {
  107722. var mesh = focusMeshes[index];
  107723. if (renderList.indexOf(mesh) === -1) {
  107724. renderList.push(mesh);
  107725. }
  107726. }
  107727. }
  107728. };
  107729. /**
  107730. * Gets the shadow map blur kernel according to the light configuration.
  107731. * @param light The light used to generate the shadows
  107732. * @param bufferSize The size of the shadow map
  107733. * @return the kernel blur size
  107734. */
  107735. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  107736. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  107737. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  107738. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  107739. }
  107740. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  107741. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  107742. }
  107743. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  107744. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  107745. }
  107746. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  107747. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  107748. return blurKernel;
  107749. };
  107750. /**
  107751. * Alters render settings to reduce features based on hardware feature limitations
  107752. * @param enableHDR Allows the viewer to run in HDR mode.
  107753. */
  107754. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  107755. if (enableHDR === void 0) { enableHDR = true; }
  107756. //flip rendering settings switches based on hardware support
  107757. var maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  107758. var maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  107759. //shadows are disabled if there's not enough varyings for a single shadow
  107760. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  107761. this._maxShadows = 0;
  107762. }
  107763. else {
  107764. this._maxShadows = 3;
  107765. }
  107766. //can we render to any >= 16-bit targets (required for HDR)
  107767. var caps = this._viewer.engine.getCaps();
  107768. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  107769. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  107770. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  107771. if (linearHalfFloatTargets) {
  107772. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  107773. this._shadowGeneratorBias = 0.002;
  107774. }
  107775. else if (linearFloatTargets) {
  107776. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  107777. this._shadowGeneratorBias = 0.001;
  107778. }
  107779. else {
  107780. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  107781. this._shadowGeneratorBias = 0.001;
  107782. }
  107783. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  107784. };
  107785. /**
  107786. * Dispoe the entire viewer including the scene and the engine
  107787. */
  107788. SceneManager.prototype.dispose = function () {
  107789. // this.onCameraConfiguredObservable.clear();
  107790. this.onEnvironmentConfiguredObservable.clear();
  107791. this.onLightsConfiguredObservable.clear();
  107792. this.onModelsConfiguredObservable.clear();
  107793. this.onSceneConfiguredObservable.clear();
  107794. this.onSceneInitObservable.clear();
  107795. this.onSceneOptimizerConfiguredObservable.clear();
  107796. if (this.sceneOptimizer) {
  107797. this.sceneOptimizer.stop();
  107798. this.sceneOptimizer.dispose();
  107799. }
  107800. if (this.environmentHelper) {
  107801. this.environmentHelper.dispose();
  107802. }
  107803. this.models.forEach(function (model) {
  107804. model.dispose();
  107805. });
  107806. if (this._defaultRenderingPipeline) {
  107807. this._defaultRenderingPipeline.dispose();
  107808. }
  107809. this.models.length = 0;
  107810. this.scene.dispose();
  107811. };
  107812. SceneManager.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  107813. var behavior;
  107814. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  107815. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  107816. // constructing behavior
  107817. switch (type) {
  107818. case 0 /* AUTOROTATION */:
  107819. this.camera.useAutoRotationBehavior = true;
  107820. behavior = this.camera.autoRotationBehavior;
  107821. break;
  107822. case 1 /* BOUNCING */:
  107823. this.camera.useBouncingBehavior = true;
  107824. behavior = this.camera.bouncingBehavior;
  107825. break;
  107826. case 2 /* FRAMING */:
  107827. this.camera.useFramingBehavior = true;
  107828. behavior = this.camera.framingBehavior;
  107829. break;
  107830. default:
  107831. behavior = null;
  107832. break;
  107833. }
  107834. if (behavior) {
  107835. if (typeof behaviorConfig === "object") {
  107836. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  107837. }
  107838. }
  107839. // post attach configuration. Some functionalities require the attached camera.
  107840. switch (type) {
  107841. case 0 /* AUTOROTATION */:
  107842. break;
  107843. case 1 /* BOUNCING */:
  107844. break;
  107845. case 2 /* FRAMING */:
  107846. this._viewer.onModelLoadedObservable.add(function (model) {
  107847. if (config.zoomOnBoundingInfo) {
  107848. behavior.zoomOnMeshHierarchy(model.rootMesh);
  107849. }
  107850. });
  107851. break;
  107852. }
  107853. };
  107854. return SceneManager;
  107855. }());
  107856. exports.SceneManager = SceneManager;
  107857. /***/ }),
  107858. /* 27 */
  107859. /***/ (function(module, exports, __webpack_require__) {
  107860. "use strict";
  107861. Object.defineProperty(exports, "__esModule", { value: true });
  107862. function getConfigurationKey(key, configObject) {
  107863. var splits = key.split('.');
  107864. if (splits.length === 0 || !configObject)
  107865. return false;
  107866. else if (splits.length === 1) {
  107867. if (configObject[key] !== undefined) {
  107868. return configObject[key];
  107869. }
  107870. }
  107871. else {
  107872. var firstKey = splits.shift();
  107873. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  107874. }
  107875. }
  107876. exports.getConfigurationKey = getConfigurationKey;
  107877. /***/ }),
  107878. /* 28 */
  107879. /***/ (function(module, exports, __webpack_require__) {
  107880. "use strict";
  107881. Object.defineProperty(exports, "__esModule", { value: true });
  107882. /**
  107883. * Animation play mode enum - is the animation looping or playing once
  107884. */
  107885. var AnimationPlayMode;
  107886. (function (AnimationPlayMode) {
  107887. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  107888. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  107889. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  107890. /**
  107891. * An enum representing the current state of an animation object
  107892. */
  107893. var AnimationState;
  107894. (function (AnimationState) {
  107895. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  107896. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  107897. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  107898. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  107899. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  107900. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  107901. /**
  107902. * The different type of easing functions available
  107903. */
  107904. var EasingFunction;
  107905. (function (EasingFunction) {
  107906. EasingFunction[EasingFunction["Linear"] = 0] = "Linear";
  107907. EasingFunction[EasingFunction["CircleEase"] = 1] = "CircleEase";
  107908. EasingFunction[EasingFunction["BackEase"] = 2] = "BackEase";
  107909. EasingFunction[EasingFunction["BounceEase"] = 3] = "BounceEase";
  107910. EasingFunction[EasingFunction["CubicEase"] = 4] = "CubicEase";
  107911. EasingFunction[EasingFunction["ElasticEase"] = 5] = "ElasticEase";
  107912. EasingFunction[EasingFunction["ExponentialEase"] = 6] = "ExponentialEase";
  107913. EasingFunction[EasingFunction["PowerEase"] = 7] = "PowerEase";
  107914. EasingFunction[EasingFunction["QuadraticEase"] = 8] = "QuadraticEase";
  107915. EasingFunction[EasingFunction["QuarticEase"] = 9] = "QuarticEase";
  107916. EasingFunction[EasingFunction["QuinticEase"] = 10] = "QuinticEase";
  107917. EasingFunction[EasingFunction["SineEase"] = 11] = "SineEase";
  107918. })(EasingFunction = exports.EasingFunction || (exports.EasingFunction = {}));
  107919. /**
  107920. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  107921. * native GroupAnimation class.
  107922. */
  107923. var GroupModelAnimation = /** @class */ (function () {
  107924. /**
  107925. * Create a new GroupModelAnimation object using an AnimationGroup object
  107926. * @param _animationGroup The aniamtion group to base the class on
  107927. */
  107928. function GroupModelAnimation(_animationGroup) {
  107929. var _this = this;
  107930. this._animationGroup = _animationGroup;
  107931. this._state = 0 /* INIT */;
  107932. this._playMode = 1 /* LOOP */;
  107933. this._animationGroup.onAnimationEndObservable.add(function () {
  107934. _this.stop();
  107935. _this._state = 4 /* ENDED */;
  107936. });
  107937. }
  107938. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  107939. /**
  107940. * Get the animation's name
  107941. */
  107942. get: function () {
  107943. return this._animationGroup.name;
  107944. },
  107945. enumerable: true,
  107946. configurable: true
  107947. });
  107948. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  107949. /**
  107950. * Get the current animation's state
  107951. */
  107952. get: function () {
  107953. return this._state;
  107954. },
  107955. enumerable: true,
  107956. configurable: true
  107957. });
  107958. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  107959. /**
  107960. * Gets the speed ratio to use for all animations
  107961. */
  107962. get: function () {
  107963. return this._animationGroup.speedRatio;
  107964. },
  107965. /**
  107966. * Sets the speed ratio to use for all animations
  107967. */
  107968. set: function (value) {
  107969. this._animationGroup.speedRatio = value;
  107970. },
  107971. enumerable: true,
  107972. configurable: true
  107973. });
  107974. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  107975. /**
  107976. * Get the max numbers of frame available in the animation group
  107977. *
  107978. * In correlation to an arry, this would be ".length"
  107979. */
  107980. get: function () {
  107981. return this._animationGroup.to - this._animationGroup.from;
  107982. },
  107983. enumerable: true,
  107984. configurable: true
  107985. });
  107986. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  107987. /**
  107988. * Get the current frame playing right now.
  107989. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  107990. *
  107991. * In correlation to an array, this would be the current index
  107992. */
  107993. get: function () {
  107994. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  107995. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  107996. }
  107997. else {
  107998. return 0;
  107999. }
  108000. },
  108001. enumerable: true,
  108002. configurable: true
  108003. });
  108004. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  108005. /**
  108006. * Get the FPS value of this animation
  108007. */
  108008. get: function () {
  108009. // get the first currentFrame found
  108010. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  108011. var animatable = this._animationGroup.animatables[i];
  108012. var animations = animatable.getAnimations();
  108013. if (!animations || !animations.length) {
  108014. continue;
  108015. }
  108016. for (var idx = 0; idx < animations.length; ++idx) {
  108017. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  108018. return animations[idx].animation.framePerSecond;
  108019. }
  108020. }
  108021. }
  108022. return 0;
  108023. },
  108024. enumerable: true,
  108025. configurable: true
  108026. });
  108027. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  108028. /**
  108029. * What is the animation'S play mode (looping or played once)
  108030. */
  108031. get: function () {
  108032. return this._playMode;
  108033. },
  108034. /**
  108035. * Set the play mode.
  108036. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  108037. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  108038. */
  108039. set: function (value) {
  108040. if (value === this._playMode) {
  108041. return;
  108042. }
  108043. this._playMode = value;
  108044. if (this.state === 1 /* PLAYING */) {
  108045. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  108046. }
  108047. else {
  108048. this._animationGroup.reset();
  108049. this._state = 0 /* INIT */;
  108050. }
  108051. },
  108052. enumerable: true,
  108053. configurable: true
  108054. });
  108055. /**
  108056. * Reset the animation group
  108057. */
  108058. GroupModelAnimation.prototype.reset = function () {
  108059. this._animationGroup.reset();
  108060. };
  108061. /**
  108062. * Restart the animation group
  108063. */
  108064. GroupModelAnimation.prototype.restart = function () {
  108065. if (this.state === 2 /* PAUSED */)
  108066. this._animationGroup.restart();
  108067. else
  108068. this.start();
  108069. };
  108070. /**
  108071. *
  108072. * @param frameNumber Go to a specific frame in the animation
  108073. */
  108074. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  108075. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  108076. };
  108077. /**
  108078. * Start playing the animation.
  108079. */
  108080. GroupModelAnimation.prototype.start = function () {
  108081. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  108082. if (this._animationGroup.isStarted) {
  108083. this._state = 1 /* PLAYING */;
  108084. }
  108085. };
  108086. /**
  108087. * Pause the animation
  108088. */
  108089. GroupModelAnimation.prototype.pause = function () {
  108090. this._animationGroup.pause();
  108091. this._state = 2 /* PAUSED */;
  108092. };
  108093. /**
  108094. * Stop the animation.
  108095. * This will fail silently if the animation group is already stopped.
  108096. */
  108097. GroupModelAnimation.prototype.stop = function () {
  108098. this._animationGroup.stop();
  108099. if (!this._animationGroup.isStarted) {
  108100. this._state = 3 /* STOPPED */;
  108101. }
  108102. };
  108103. /**
  108104. * Dispose this animation object.
  108105. */
  108106. GroupModelAnimation.prototype.dispose = function () {
  108107. this._animationGroup.dispose();
  108108. };
  108109. return GroupModelAnimation;
  108110. }());
  108111. exports.GroupModelAnimation = GroupModelAnimation;
  108112. /***/ }),
  108113. /* 29 */
  108114. /***/ (function(module, exports, __webpack_require__) {
  108115. "use strict";
  108116. Object.defineProperty(exports, "__esModule", { value: true });
  108117. var environmentSerializer_1 = __webpack_require__(30);
  108118. var babylonjs_1 = __webpack_require__(0);
  108119. var texture_1 = __webpack_require__(11);
  108120. /**
  108121. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  108122. * The APIs in all labs-related classes and configuration might change.
  108123. * Once stable, lab features will be moved to the publis API and configuration object.
  108124. */
  108125. var ViewerLabs = /** @class */ (function () {
  108126. function ViewerLabs(_sceneManager) {
  108127. this._sceneManager = _sceneManager;
  108128. this.environment = {
  108129. //irradiance
  108130. irradiancePolynomialCoefficients: {
  108131. x: new BABYLON.Vector3(0, 0, 0),
  108132. y: new BABYLON.Vector3(0, 0, 0),
  108133. z: new BABYLON.Vector3(0, 0, 0),
  108134. xx: new BABYLON.Vector3(0, 0, 0),
  108135. yy: new BABYLON.Vector3(0, 0, 0),
  108136. zz: new BABYLON.Vector3(0, 0, 0),
  108137. yz: new BABYLON.Vector3(0, 0, 0),
  108138. zx: new BABYLON.Vector3(0, 0, 0),
  108139. xy: new BABYLON.Vector3(0, 0, 0)
  108140. },
  108141. textureIntensityScale: 1.0
  108142. };
  108143. }
  108144. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  108145. var _this = this;
  108146. //@! todo: should loadEnvironment cancel any currently loading environments?
  108147. if (data instanceof ArrayBuffer) {
  108148. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  108149. if (onSuccess)
  108150. onSuccess(this.environment);
  108151. }
  108152. else if (typeof data === 'string') {
  108153. var url = this.getAssetUrl(data);
  108154. this._sceneManager.scene._loadFile(url, function (arrayBuffer) {
  108155. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  108156. if (onSuccess)
  108157. onSuccess(_this.environment);
  108158. }, function (progressEvent) { if (onProgress)
  108159. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  108160. if (onError) {
  108161. onError(e);
  108162. }
  108163. });
  108164. }
  108165. else {
  108166. //data assumed to be PBREnvironment object
  108167. this.environment = data;
  108168. if (onSuccess)
  108169. onSuccess(data);
  108170. }
  108171. };
  108172. /**
  108173. * Applies an `EnvironmentMapConfiguration` to the scene
  108174. * @param environmentMapConfiguration Environment map configuration to apply
  108175. */
  108176. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  108177. if (!this.environment)
  108178. return;
  108179. //set orientation
  108180. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(BABYLON.Axis.Y, rotationY || 0);
  108181. // Add env texture to the scene.
  108182. if (this.environment.specularTexture) {
  108183. // IE crashes when disposing the old texture and setting a new one
  108184. if (!this._sceneManager.scene.environmentTexture) {
  108185. this._sceneManager.scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._sceneManager.scene, this.environment.specularTexture, false, true);
  108186. }
  108187. if (this._sceneManager.scene.environmentTexture) {
  108188. this._sceneManager.scene.environmentTexture.level = this.environment.textureIntensityScale;
  108189. this._sceneManager.scene.environmentTexture.invertZ = true;
  108190. this._sceneManager.scene.environmentTexture.lodLevelInAlpha = true;
  108191. var poly = this._sceneManager.scene.environmentTexture.sphericalPolynomial || new BABYLON.SphericalPolynomial();
  108192. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  108193. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  108194. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  108195. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  108196. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  108197. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  108198. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  108199. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  108200. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  108201. this._sceneManager.scene.environmentTexture.sphericalPolynomial = poly;
  108202. //set orientation
  108203. BABYLON.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._sceneManager.scene.environmentTexture.getReflectionTextureMatrix());
  108204. }
  108205. }
  108206. };
  108207. /**
  108208. * Get an environment asset url by using the configuration if the path is not absolute.
  108209. * @param url Asset url
  108210. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  108211. */
  108212. ViewerLabs.prototype.getAssetUrl = function (url) {
  108213. var returnUrl = url;
  108214. if (url && url.toLowerCase().indexOf("//") === -1) {
  108215. if (!this.assetsRootURL) {
  108216. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  108217. return url;
  108218. }
  108219. returnUrl = this.assetsRootURL + returnUrl;
  108220. }
  108221. return returnUrl;
  108222. };
  108223. return ViewerLabs;
  108224. }());
  108225. exports.ViewerLabs = ViewerLabs;
  108226. /***/ }),
  108227. /* 30 */
  108228. /***/ (function(module, exports, __webpack_require__) {
  108229. "use strict";
  108230. Object.defineProperty(exports, "__esModule", { value: true });
  108231. var babylonjs_1 = __webpack_require__(0);
  108232. var texture_1 = __webpack_require__(11);
  108233. /**
  108234. * A static class proving methods to aid parsing Spectre environment files
  108235. */
  108236. var EnvironmentDeserializer = /** @class */ (function () {
  108237. function EnvironmentDeserializer() {
  108238. }
  108239. /**
  108240. * Parses an arraybuffer into a new PBREnvironment object
  108241. * @param arrayBuffer The arraybuffer of the Spectre environment file
  108242. * @return a PBREnvironment object
  108243. */
  108244. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  108245. var environment = {
  108246. //irradiance
  108247. irradiancePolynomialCoefficients: {
  108248. x: new babylonjs_1.Vector3(0, 0, 0),
  108249. y: new babylonjs_1.Vector3(0, 0, 0),
  108250. z: new babylonjs_1.Vector3(0, 0, 0),
  108251. xx: new babylonjs_1.Vector3(0, 0, 0),
  108252. yy: new babylonjs_1.Vector3(0, 0, 0),
  108253. zz: new babylonjs_1.Vector3(0, 0, 0),
  108254. yz: new babylonjs_1.Vector3(0, 0, 0),
  108255. zx: new babylonjs_1.Vector3(0, 0, 0),
  108256. xy: new babylonjs_1.Vector3(0, 0, 0)
  108257. },
  108258. //specular
  108259. textureIntensityScale: 1.0,
  108260. };
  108261. //read .env
  108262. var littleEndian = false;
  108263. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  108264. var dataView = new DataView(arrayBuffer);
  108265. var pos = 0;
  108266. for (var i = 0; i < magicBytes.length; i++) {
  108267. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  108268. babylonjs_1.Tools.Error('Not a Spectre environment map');
  108269. }
  108270. }
  108271. var version = dataView.getUint16(pos, littleEndian);
  108272. pos += 2;
  108273. if (version !== 1) {
  108274. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  108275. }
  108276. //read json descriptor - collect characters up to null terminator
  108277. var descriptorString = '';
  108278. var charCode = 0x00;
  108279. while ((charCode = dataView.getUint8(pos++))) {
  108280. descriptorString += String.fromCharCode(charCode);
  108281. }
  108282. var descriptor = JSON.parse(descriptorString);
  108283. var payloadPos = pos;
  108284. //irradiance
  108285. switch (descriptor.irradiance.type) {
  108286. case 'irradiance_sh_coefficients_9':
  108287. //irradiance
  108288. var harmonics = descriptor.irradiance;
  108289. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  108290. //harmonics now represent radiance
  108291. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  108292. break;
  108293. default:
  108294. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  108295. }
  108296. //specular
  108297. switch (descriptor.specular.type) {
  108298. case 'cubemap_faces':
  108299. var specularDescriptor = descriptor.specular;
  108300. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  108301. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  108302. var mipmaps = specularDescriptor.mipmaps;
  108303. var imageType = specularDescriptor.imageType;
  108304. for (var l = 0; l < mipmaps.length; l++) {
  108305. var faceRanges = mipmaps[l];
  108306. specularTexture.source[l] = [];
  108307. for (var i = 0; i < 6; i++) {
  108308. var range = faceRanges[i];
  108309. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  108310. switch (imageType) {
  108311. case 'png':
  108312. //construct image element from bytes
  108313. var image = new Image();
  108314. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  108315. image.src = src;
  108316. specularTexture.source[l][i] = image;
  108317. break;
  108318. default:
  108319. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  108320. }
  108321. }
  108322. }
  108323. break;
  108324. default:
  108325. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  108326. }
  108327. return environment;
  108328. };
  108329. /**
  108330. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  108331. * L = (1/pi) * E * rho
  108332. *
  108333. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  108334. * @param harmonics Spherical harmonic coefficients (9)
  108335. */
  108336. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  108337. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  108338. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  108339. // (The pixel shader must apply albedo after texture fetches, etc).
  108340. };
  108341. /**
  108342. * Convert spherical harmonics to spherical polynomial coefficients
  108343. * @param harmonics Spherical harmonic coefficients (9)
  108344. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  108345. */
  108346. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  108347. var rPi = 1 / Math.PI;
  108348. //x
  108349. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  108350. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  108351. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  108352. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  108353. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  108354. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  108355. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  108356. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  108357. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  108358. //xx
  108359. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  108360. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  108361. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  108362. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  108363. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  108364. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  108365. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  108366. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  108367. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  108368. //yz
  108369. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  108370. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  108371. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  108372. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  108373. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  108374. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  108375. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  108376. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  108377. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  108378. };
  108379. /**
  108380. * Multiplies harmonic coefficients in place
  108381. * @param harmonics Spherical harmonic coefficients (9)
  108382. * @param scaleFactor Value to multiply by
  108383. */
  108384. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  108385. harmonics.l00[0] *= scaleFactor;
  108386. harmonics.l00[1] *= scaleFactor;
  108387. harmonics.l00[2] *= scaleFactor;
  108388. harmonics.l1_1[0] *= scaleFactor;
  108389. harmonics.l1_1[1] *= scaleFactor;
  108390. harmonics.l1_1[2] *= scaleFactor;
  108391. harmonics.l10[0] *= scaleFactor;
  108392. harmonics.l10[1] *= scaleFactor;
  108393. harmonics.l10[2] *= scaleFactor;
  108394. harmonics.l11[0] *= scaleFactor;
  108395. harmonics.l11[1] *= scaleFactor;
  108396. harmonics.l11[2] *= scaleFactor;
  108397. harmonics.l2_2[0] *= scaleFactor;
  108398. harmonics.l2_2[1] *= scaleFactor;
  108399. harmonics.l2_2[2] *= scaleFactor;
  108400. harmonics.l2_1[0] *= scaleFactor;
  108401. harmonics.l2_1[1] *= scaleFactor;
  108402. harmonics.l2_1[2] *= scaleFactor;
  108403. harmonics.l20[0] *= scaleFactor;
  108404. harmonics.l20[1] *= scaleFactor;
  108405. harmonics.l20[2] *= scaleFactor;
  108406. harmonics.l21[0] *= scaleFactor;
  108407. harmonics.l21[1] *= scaleFactor;
  108408. harmonics.l21[2] *= scaleFactor;
  108409. harmonics.l22[0] *= scaleFactor;
  108410. harmonics.l22[1] *= scaleFactor;
  108411. harmonics.l22[2] *= scaleFactor;
  108412. };
  108413. return EnvironmentDeserializer;
  108414. }());
  108415. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  108416. /***/ }),
  108417. /* 31 */
  108418. /***/ (function(module, exports, __webpack_require__) {
  108419. "use strict";
  108420. Object.defineProperty(exports, "__esModule", { value: true });
  108421. var extended_1 = __webpack_require__(32);
  108422. var cache = {};
  108423. /**
  108424. *
  108425. * @param name the name of the custom optimizer configuration
  108426. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  108427. */
  108428. function getCustomOptimizerByName(name, upgrade) {
  108429. if (!cache[name]) {
  108430. switch (name) {
  108431. case 'extended':
  108432. if (upgrade) {
  108433. return extended_1.extendedUpgrade;
  108434. }
  108435. else {
  108436. return extended_1.extendedDegrade;
  108437. }
  108438. }
  108439. }
  108440. return cache[name];
  108441. }
  108442. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  108443. /***/ }),
  108444. /* 32 */
  108445. /***/ (function(module, exports, __webpack_require__) {
  108446. "use strict";
  108447. Object.defineProperty(exports, "__esModule", { value: true });
  108448. var babylonjs_1 = __webpack_require__(0);
  108449. /**
  108450. * A custom upgrade-oriented function configuration for the scene optimizer.
  108451. *
  108452. * @param viewer the viewer to optimize
  108453. */
  108454. function extendedUpgrade(viewer) {
  108455. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  108456. // if (!this.Scene.BackgroundHelper) {
  108457. // this.Scene.EngineScene.autoClear = false;
  108458. // this.Scene.BackgroundHelper = true;
  108459. // Would require a dedicated clear color;
  108460. // return false;
  108461. // }
  108462. if (viewer.engine.getHardwareScalingLevel() > 1) {
  108463. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, 1);
  108464. viewer.engine.setHardwareScalingLevel(scaling);
  108465. return false;
  108466. }
  108467. if (!viewer.sceneManager.scene.postProcessesEnabled) {
  108468. viewer.sceneManager.scene.postProcessesEnabled = true;
  108469. return false;
  108470. }
  108471. if (!viewer.sceneManager.groundEnabled) {
  108472. viewer.sceneManager.groundEnabled = true;
  108473. return false;
  108474. }
  108475. if (defaultPipeline && !viewer.sceneManager.fxaaEnabled) {
  108476. viewer.sceneManager.fxaaEnabled = true;
  108477. return false;
  108478. }
  108479. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  108480. if (viewer.engine.getHardwareScalingLevel() > hardwareScalingLevel) {
  108481. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  108482. viewer.engine.setHardwareScalingLevel(scaling);
  108483. return false;
  108484. }
  108485. if (!viewer.sceneManager.processShadows) {
  108486. viewer.sceneManager.processShadows = true;
  108487. return false;
  108488. }
  108489. if (defaultPipeline && !viewer.sceneManager.bloomEnabled) {
  108490. viewer.sceneManager.bloomEnabled = true;
  108491. return false;
  108492. }
  108493. if (!viewer.sceneManager.groundMirrorEnabled) {
  108494. viewer.sceneManager.groundMirrorEnabled = true;
  108495. return false;
  108496. }
  108497. return true;
  108498. }
  108499. exports.extendedUpgrade = extendedUpgrade;
  108500. /**
  108501. * A custom degrade-oriented function configuration for the scene optimizer.
  108502. *
  108503. * @param viewer the viewer to optimize
  108504. */
  108505. function extendedDegrade(viewer) {
  108506. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  108507. if (viewer.sceneManager.groundMirrorEnabled) {
  108508. viewer.sceneManager.groundMirrorEnabled = false;
  108509. return false;
  108510. }
  108511. if (defaultPipeline && viewer.sceneManager.bloomEnabled) {
  108512. viewer.sceneManager.bloomEnabled = false;
  108513. return false;
  108514. }
  108515. if (viewer.sceneManager.processShadows) {
  108516. viewer.sceneManager.processShadows = false;
  108517. return false;
  108518. }
  108519. if (viewer.engine.getHardwareScalingLevel() < 1) {
  108520. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1);
  108521. viewer.engine.setHardwareScalingLevel(scaling);
  108522. return false;
  108523. }
  108524. if (defaultPipeline && viewer.sceneManager.fxaaEnabled) {
  108525. viewer.sceneManager.fxaaEnabled = false;
  108526. return false;
  108527. }
  108528. if (viewer.sceneManager.groundEnabled) {
  108529. viewer.sceneManager.groundEnabled = false;
  108530. return false;
  108531. }
  108532. if (viewer.sceneManager.scene.postProcessesEnabled) {
  108533. viewer.sceneManager.scene.postProcessesEnabled = false;
  108534. return false;
  108535. }
  108536. if (viewer.engine.getHardwareScalingLevel() < 1.25) {
  108537. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1.25);
  108538. viewer.engine.setHardwareScalingLevel(scaling);
  108539. return false;
  108540. }
  108541. // if (this.Scene.BackgroundHelper) {
  108542. // this.Scene.EngineScene.autoClear = true;
  108543. // this.Scene.BackgroundHelper = false;
  108544. // Would require a dedicated clear color;
  108545. // return false;
  108546. // }
  108547. return true;
  108548. }
  108549. exports.extendedDegrade = extendedDegrade;
  108550. /***/ }),
  108551. /* 33 */
  108552. /***/ (function(module, exports, __webpack_require__) {
  108553. "use strict";
  108554. Object.defineProperty(exports, "__esModule", { value: true });
  108555. var babylonjs_1 = __webpack_require__(0);
  108556. var helper_1 = __webpack_require__(2);
  108557. var deepmerge = __webpack_require__(1);
  108558. /**
  108559. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  108560. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  108561. */
  108562. var TemplateManager = /** @class */ (function () {
  108563. function TemplateManager(containerElement) {
  108564. this.containerElement = containerElement;
  108565. this.templates = {};
  108566. this.onTemplateInit = new babylonjs_1.Observable();
  108567. this.onTemplateLoaded = new babylonjs_1.Observable();
  108568. this.onTemplateStateChange = new babylonjs_1.Observable();
  108569. this.onAllLoaded = new babylonjs_1.Observable();
  108570. this.onEventTriggered = new babylonjs_1.Observable();
  108571. this.eventManager = new eventManager_1.EventManager(this);
  108572. }
  108573. /**
  108574. * Initialize the template(s) for the viewer. Called bay the Viewer class
  108575. * @param templates the templates to be used to initialize the main template
  108576. */
  108577. TemplateManager.prototype.initTemplate = function (templates) {
  108578. var _this = this;
  108579. var internalInit = function (dependencyMap, name, parentTemplate) {
  108580. //init template
  108581. var template = _this.templates[name];
  108582. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  108583. return internalInit(dependencyMap[childName], childName, template);
  108584. });
  108585. // register the observers
  108586. //template.onLoaded.add(() => {
  108587. var addToParent = function () {
  108588. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  108589. template.appendTo(containingElement);
  108590. _this._checkLoadedState();
  108591. };
  108592. if (parentTemplate && !parentTemplate.parent) {
  108593. parentTemplate.onAppended.add(function () {
  108594. addToParent();
  108595. });
  108596. }
  108597. else {
  108598. addToParent();
  108599. }
  108600. //});
  108601. return template;
  108602. };
  108603. //build the html tree
  108604. return this._buildHTMLTree(templates).then(function (htmlTree) {
  108605. if (_this.templates['main']) {
  108606. internalInit(htmlTree, 'main');
  108607. }
  108608. else {
  108609. _this._checkLoadedState();
  108610. }
  108611. return;
  108612. });
  108613. };
  108614. /**
  108615. *
  108616. * This function will create a simple map with child-dependencies of the template html tree.
  108617. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  108618. * It is expected that the main template will be called main!
  108619. *
  108620. * @param templates
  108621. */
  108622. TemplateManager.prototype._buildHTMLTree = function (templates) {
  108623. var _this = this;
  108624. var promises = Object.keys(templates).map(function (name) {
  108625. // if the template was overridden
  108626. if (!templates[name])
  108627. return Promise.resolve(false);
  108628. // else - we have a template, let's do our job!
  108629. var template = new Template(name, templates[name]);
  108630. template.onLoaded.add(function () {
  108631. _this.onTemplateLoaded.notifyObservers(template);
  108632. });
  108633. template.onStateChange.add(function () {
  108634. _this.onTemplateStateChange.notifyObservers(template);
  108635. });
  108636. _this.onTemplateInit.notifyObservers(template);
  108637. // make sure the global onEventTriggered is called as well
  108638. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  108639. _this.templates[name] = template;
  108640. return template.initPromise;
  108641. });
  108642. return Promise.all(promises).then(function () {
  108643. var templateStructure = {};
  108644. // now iterate through all templates and check for children:
  108645. var buildTree = function (parentObject, name) {
  108646. _this.templates[name].isInHtmlTree = true;
  108647. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  108648. childNodes.forEach(function (element) {
  108649. parentObject[element] = {};
  108650. buildTree(parentObject[element], element);
  108651. });
  108652. };
  108653. if (_this.templates['main']) {
  108654. buildTree(templateStructure, "main");
  108655. }
  108656. return templateStructure;
  108657. });
  108658. };
  108659. /**
  108660. * Get the canvas in the template tree.
  108661. * There must be one and only one canvas inthe template.
  108662. */
  108663. TemplateManager.prototype.getCanvas = function () {
  108664. return this.containerElement.querySelector('canvas');
  108665. };
  108666. /**
  108667. * Get a specific template from the template tree
  108668. * @param name the name of the template to load
  108669. */
  108670. TemplateManager.prototype.getTemplate = function (name) {
  108671. return this.templates[name];
  108672. };
  108673. TemplateManager.prototype._checkLoadedState = function () {
  108674. var _this = this;
  108675. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  108676. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  108677. });
  108678. if (done) {
  108679. this.onAllLoaded.notifyObservers(this);
  108680. }
  108681. };
  108682. /**
  108683. * Dispose the template manager
  108684. */
  108685. TemplateManager.prototype.dispose = function () {
  108686. var _this = this;
  108687. // dispose all templates
  108688. Object.keys(this.templates).forEach(function (template) {
  108689. _this.templates[template].dispose();
  108690. });
  108691. this.templates = {};
  108692. this.eventManager.dispose();
  108693. this.onTemplateInit.clear();
  108694. this.onAllLoaded.clear();
  108695. this.onEventTriggered.clear();
  108696. this.onTemplateLoaded.clear();
  108697. this.onTemplateStateChange.clear();
  108698. };
  108699. return TemplateManager;
  108700. }());
  108701. exports.TemplateManager = TemplateManager;
  108702. var Handlebars = __webpack_require__(34);
  108703. var eventManager_1 = __webpack_require__(35);
  108704. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  108705. Handlebars.registerHelper('eachInMap', function (map, block) {
  108706. var out = '';
  108707. Object.keys(map).map(function (prop) {
  108708. var data = map[prop];
  108709. if (typeof data === 'object') {
  108710. data.id = data.id || prop;
  108711. out += block.fn(data);
  108712. }
  108713. else {
  108714. out += block.fn({ id: prop, value: data });
  108715. }
  108716. });
  108717. return out;
  108718. });
  108719. Handlebars.registerHelper('add', function (a, b) {
  108720. var out = a + b;
  108721. return out;
  108722. });
  108723. Handlebars.registerHelper('eq', function (a, b) {
  108724. var out = (a == b);
  108725. return out;
  108726. });
  108727. Handlebars.registerHelper('or', function (a, b) {
  108728. var out = a || b;
  108729. return out;
  108730. });
  108731. Handlebars.registerHelper('not', function (a) {
  108732. var out = !a;
  108733. return out;
  108734. });
  108735. Handlebars.registerHelper('count', function (map) {
  108736. return map.length;
  108737. });
  108738. Handlebars.registerHelper('gt', function (a, b) {
  108739. var out = a > b;
  108740. return out;
  108741. });
  108742. /**
  108743. * This class represents a single template in the viewer's template tree.
  108744. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  108745. * A template is injected using the template manager in the correct position.
  108746. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  108747. *
  108748. * For further information please refer to the documentation page, https://doc.babylonjs.com
  108749. */
  108750. var Template = /** @class */ (function () {
  108751. function Template(name, _configuration) {
  108752. var _this = this;
  108753. this.name = name;
  108754. this._configuration = _configuration;
  108755. this.onLoaded = new babylonjs_1.Observable();
  108756. this.onAppended = new babylonjs_1.Observable();
  108757. this.onStateChange = new babylonjs_1.Observable();
  108758. this.onEventTriggered = new babylonjs_1.Observable();
  108759. this.loadRequests = [];
  108760. this.isLoaded = false;
  108761. this.isShown = false;
  108762. this.isInHtmlTree = false;
  108763. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  108764. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  108765. if (htmlTemplate) {
  108766. _this._htmlTemplate = htmlTemplate;
  108767. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && _this._configuration.params.noEscape) });
  108768. var config = _this._configuration.params || {};
  108769. _this._rawHtml = compiledTemplate(config);
  108770. try {
  108771. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  108772. }
  108773. catch (e) {
  108774. var test = document.createElement(_this.name);
  108775. test.innerHTML = _this._rawHtml;
  108776. _this._fragment = test;
  108777. }
  108778. _this.isLoaded = true;
  108779. _this.isShown = true;
  108780. _this.onLoaded.notifyObservers(_this);
  108781. }
  108782. return _this;
  108783. });
  108784. }
  108785. /**
  108786. * Some templates have parameters (like background color for example).
  108787. * The parameters are provided to Handlebars which in turn generates the template.
  108788. * This function will update the template with the new parameters
  108789. *
  108790. * Note that when updating parameters the events will be registered again (after being cleared).
  108791. *
  108792. * @param params the new template parameters
  108793. */
  108794. Template.prototype.updateParams = function (params, append) {
  108795. if (append === void 0) { append = true; }
  108796. if (append) {
  108797. this._configuration.params = deepmerge(this._configuration.params, params);
  108798. }
  108799. else {
  108800. this._configuration.params = params;
  108801. }
  108802. // update the template
  108803. if (this.isLoaded) {
  108804. // this.dispose();
  108805. }
  108806. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  108807. var config = this._configuration.params || {};
  108808. this._rawHtml = compiledTemplate(config);
  108809. try {
  108810. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  108811. }
  108812. catch (e) {
  108813. var test = document.createElement(this.name);
  108814. test.innerHTML = this._rawHtml;
  108815. this._fragment = test;
  108816. }
  108817. if (this.parent) {
  108818. this.appendTo(this.parent, true);
  108819. }
  108820. };
  108821. Object.defineProperty(Template.prototype, "configuration", {
  108822. /**
  108823. * Get the template'S configuration
  108824. */
  108825. get: function () {
  108826. return this._configuration;
  108827. },
  108828. enumerable: true,
  108829. configurable: true
  108830. });
  108831. /**
  108832. * A template can be a parent element for other templates or HTML elements.
  108833. * This function will deliver all child HTML elements of this template.
  108834. */
  108835. Template.prototype.getChildElements = function () {
  108836. var childrenArray = [];
  108837. //Edge and IE don't support frage,ent.children
  108838. var children = this._fragment && this._fragment.children;
  108839. if (!this._fragment) {
  108840. var fragment = this.parent.querySelector(this.name);
  108841. if (fragment) {
  108842. children = fragment.querySelectorAll('*');
  108843. }
  108844. }
  108845. if (!children) {
  108846. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  108847. children = this._fragment.querySelectorAll('*');
  108848. }
  108849. for (var i = 0; i < children.length; ++i) {
  108850. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  108851. }
  108852. return childrenArray;
  108853. };
  108854. /**
  108855. * Appending the template to a parent HTML element.
  108856. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  108857. * @param parent the parent to which the template is added
  108858. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  108859. */
  108860. Template.prototype.appendTo = function (parent, forceRemove) {
  108861. var _this = this;
  108862. if (this.parent) {
  108863. if (forceRemove && this._addedFragment) {
  108864. /*let fragement = this.parent.querySelector(this.name)
  108865. if (fragement)
  108866. this.parent.removeChild(fragement);*/
  108867. this.parent.innerHTML = '';
  108868. }
  108869. else {
  108870. return;
  108871. }
  108872. }
  108873. this.parent = parent;
  108874. if (this._configuration.id) {
  108875. this.parent.id = this._configuration.id;
  108876. }
  108877. if (this._fragment) {
  108878. this.parent.appendChild(this._fragment);
  108879. this._addedFragment = this._fragment;
  108880. }
  108881. else {
  108882. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  108883. }
  108884. // appended only one frame after.
  108885. setTimeout(function () {
  108886. _this._registerEvents();
  108887. _this.onAppended.notifyObservers(_this);
  108888. });
  108889. };
  108890. /**
  108891. * Show the template using the provided visibilityFunction, or natively using display: flex.
  108892. * The provided function returns a promise that should be fullfilled when the element is shown.
  108893. * Since it is a promise async operations are more than possible.
  108894. * See the default viewer for an opacity example.
  108895. * @param visibilityFunction The function to execute to show the template.
  108896. */
  108897. Template.prototype.show = function (visibilityFunction) {
  108898. var _this = this;
  108899. if (this._isHiding)
  108900. return Promise.resolve(this);
  108901. return Promise.resolve().then(function () {
  108902. _this._isShowing = true;
  108903. if (visibilityFunction) {
  108904. return visibilityFunction(_this);
  108905. }
  108906. else {
  108907. // flex? box? should this be configurable easier than the visibilityFunction?
  108908. _this.parent.style.display = 'flex';
  108909. // support old browsers with no flex:
  108910. if (_this.parent.style.display !== 'flex') {
  108911. _this.parent.style.display = '';
  108912. }
  108913. return _this;
  108914. }
  108915. }).then(function () {
  108916. _this.isShown = true;
  108917. _this._isShowing = false;
  108918. _this.onStateChange.notifyObservers(_this);
  108919. return _this;
  108920. });
  108921. };
  108922. /**
  108923. * Hide the template using the provided visibilityFunction, or natively using display: none.
  108924. * The provided function returns a promise that should be fullfilled when the element is hidden.
  108925. * Since it is a promise async operations are more than possible.
  108926. * See the default viewer for an opacity example.
  108927. * @param visibilityFunction The function to execute to show the template.
  108928. */
  108929. Template.prototype.hide = function (visibilityFunction) {
  108930. var _this = this;
  108931. if (this._isShowing)
  108932. return Promise.resolve(this);
  108933. return Promise.resolve().then(function () {
  108934. _this._isHiding = true;
  108935. if (visibilityFunction) {
  108936. return visibilityFunction(_this);
  108937. }
  108938. else {
  108939. // flex? box? should this be configurable easier than the visibilityFunction?
  108940. _this.parent.style.display = 'none';
  108941. return _this;
  108942. }
  108943. }).then(function () {
  108944. _this.isShown = false;
  108945. _this._isHiding = false;
  108946. _this.onStateChange.notifyObservers(_this);
  108947. return _this;
  108948. });
  108949. };
  108950. /**
  108951. * Dispose this template
  108952. */
  108953. Template.prototype.dispose = function () {
  108954. this.onAppended.clear();
  108955. this.onEventTriggered.clear();
  108956. this.onLoaded.clear();
  108957. this.onStateChange.clear();
  108958. this.isLoaded = false;
  108959. // remove from parent
  108960. try {
  108961. this.parent.removeChild(this._fragment);
  108962. }
  108963. catch (e) {
  108964. //noop
  108965. }
  108966. this.loadRequests.forEach(function (request) {
  108967. request.abort();
  108968. });
  108969. if (this._registeredEvents) {
  108970. this._registeredEvents.forEach(function (evt) {
  108971. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  108972. });
  108973. }
  108974. delete this._fragment;
  108975. };
  108976. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  108977. var _this = this;
  108978. if (!templateConfig) {
  108979. return Promise.reject('No templateConfig provided');
  108980. }
  108981. else if (templateConfig.html !== undefined) {
  108982. return Promise.resolve(templateConfig.html);
  108983. }
  108984. else {
  108985. var location_1 = this._getTemplateLocation(templateConfig);
  108986. if (helper_1.isUrl(location_1)) {
  108987. return new Promise(function (resolve, reject) {
  108988. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  108989. resolve(data);
  108990. }, undefined, undefined, false, function (request, error) {
  108991. reject(error);
  108992. });
  108993. _this.loadRequests.push(fileRequest);
  108994. });
  108995. }
  108996. else {
  108997. location_1 = location_1.replace('#', '');
  108998. var element = document.getElementById(location_1);
  108999. if (element) {
  109000. return Promise.resolve(element.innerHTML);
  109001. }
  109002. else {
  109003. return Promise.reject('Template ID not found');
  109004. }
  109005. }
  109006. }
  109007. };
  109008. Template.prototype._registerEvents = function () {
  109009. var _this = this;
  109010. this._registeredEvents = this._registeredEvents || [];
  109011. if (this._registeredEvents.length) {
  109012. // first remove the registered events
  109013. this._registeredEvents.forEach(function (evt) {
  109014. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  109015. });
  109016. }
  109017. if (this._configuration.events) {
  109018. var _loop_1 = function (eventName) {
  109019. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  109020. var functionToFire_1 = function (selector, event) {
  109021. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  109022. };
  109023. // if boolean, set the parent as the event listener
  109024. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  109025. var selector = this_1.parent.id;
  109026. if (selector) {
  109027. selector = '#' + selector;
  109028. }
  109029. else {
  109030. selector = this_1.parent.tagName;
  109031. }
  109032. var binding = functionToFire_1.bind(this_1, selector);
  109033. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  109034. this_1._registeredEvents.push({
  109035. htmlElement: this_1.parent,
  109036. eventName: eventName,
  109037. function: binding
  109038. });
  109039. }
  109040. else if (typeof this_1._configuration.events[eventName] === 'object') {
  109041. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  109042. // strict null checl is working incorrectly, must override:
  109043. var event_1 = this_1._configuration.events[eventName] || {};
  109044. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  109045. if (selector && selector.indexOf('#') !== 0) {
  109046. selector = '#' + selector;
  109047. }
  109048. var htmlElement = _this.parent.querySelector(selector);
  109049. if (htmlElement) {
  109050. var binding = functionToFire_1.bind(_this, selector);
  109051. htmlElement.addEventListener(eventName, binding, false);
  109052. _this._registeredEvents.push({
  109053. htmlElement: htmlElement,
  109054. eventName: eventName,
  109055. function: binding
  109056. });
  109057. }
  109058. });
  109059. }
  109060. }
  109061. };
  109062. var this_1 = this;
  109063. for (var eventName in this._configuration.events) {
  109064. _loop_1(eventName);
  109065. }
  109066. }
  109067. };
  109068. Template.prototype._getTemplateLocation = function (templateConfig) {
  109069. if (!templateConfig || typeof templateConfig === 'string') {
  109070. return templateConfig;
  109071. }
  109072. else {
  109073. return templateConfig.location;
  109074. }
  109075. };
  109076. return Template;
  109077. }());
  109078. exports.Template = Template;
  109079. /***/ }),
  109080. /* 34 */
  109081. /***/ (function(module, exports, __webpack_require__) {
  109082. /**!
  109083. @license
  109084. handlebars v4.0.11
  109085. Copyright (C) 2011-2017 by Yehuda Katz
  109086. Permission is hereby granted, free of charge, to any person obtaining a copy
  109087. of this software and associated documentation files (the "Software"), to deal
  109088. in the Software without restriction, including without limitation the rights
  109089. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  109090. copies of the Software, and to permit persons to whom the Software is
  109091. furnished to do so, subject to the following conditions:
  109092. The above copyright notice and this permission notice shall be included in
  109093. all copies or substantial portions of the Software.
  109094. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  109095. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  109096. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  109097. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  109098. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  109099. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  109100. THE SOFTWARE.
  109101. */
  109102. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(35),i=e(h),j=c(36),k=c(41),l=c(42),m=e(l),n=c(39),o=e(n),p=c(34),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(21),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(22),p=e(o),q=c(34),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(18),k=c(20),l=e(k),m="4.0.11";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0;c&&(g=c.start.line,h=c.start.column,a+=" - "+g+":"+h);for(var i=Error.prototype.constructor.call(this,a),j=0;j<f.length;j++)this[f[j]]=i[f[j]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,e?Object.defineProperty(this,"column",{value:h,enumerable:!0}):this.column=h)}catch(k){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d;var f=c(11),g=e(f),h=c(12),i=e(h),j=c(13),k=e(j),l=c(14),m=e(l),n=c(15),o=e(n),p=c(16),q=e(p),r=c(17),s=e(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;h<l;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&&a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&&(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return b.data&&b.ids&&(e=d.createFrame(b.data),e.contextPath=d.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:e,blockParams:d.blockParams([a],[e&&e.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(19),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=s.COMPILER_REVISION;if(b!==c){if(b<c){var d=s.REVISION_CHANGES[c],e=s.REVISION_CHANGES[b];throw new r["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new r["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=p.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h<i&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new r["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!=f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new r["default"]("No environment passed to template");if(!a||!a.main)throw new r["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new r["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:p.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=p.extend({},b,a)),c},nullContext:l({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new r["default"]("must pass block params");if(a.useDepths&&!g)throw new r["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=s.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=s.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=p.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new r["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?s.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),p.extend(b,g)}return b}var l=c(23)["default"],m=c(3)["default"],n=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var o=c(5),p=m(o),q=c(6),r=n(q),s=c(4)},function(a,b,c){a.exports={"default":c(24),__esModule:!0}},function(a,b,c){c(25),a.exports=c(30).Object.seal},function(a,b,c){var d=c(26);c(27)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b,c){var d=c(28),e=c(30),f=c(33);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(29),e=c(30),f=c(31),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(32);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&&b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}var e=c(1)["default"],f=c(3)["default"];b.__esModule=!0,b.parse=d;var g=c(37),h=e(g),i=c(38),j=e(i),k=c(40),l=f(k),m=c(5);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[f[h]];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],
  109103. 85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(39),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;h<i;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=l.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(6),k=i(j),l=c(5),m=c(35),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(this.options.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new k["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new k["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(1)["default"];b.__esModule=!0;var h=c(4),i=c(6),j=g(i),k=c(5),l=c(43),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend(" + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){
  109104. var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;e<g;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(5),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add([" ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
  109105. /***/ }),
  109106. /* 35 */
  109107. /***/ (function(module, exports, __webpack_require__) {
  109108. "use strict";
  109109. Object.defineProperty(exports, "__esModule", { value: true });
  109110. /**
  109111. * The EventManager is in charge of registering user interctions with the viewer.
  109112. * It is used in the TemplateManager
  109113. */
  109114. var EventManager = /** @class */ (function () {
  109115. function EventManager(_templateManager) {
  109116. var _this = this;
  109117. this._templateManager = _templateManager;
  109118. this._callbacksContainer = {};
  109119. this._templateManager.onEventTriggered.add(function (eventData) {
  109120. _this._eventTriggered(eventData);
  109121. });
  109122. }
  109123. /**
  109124. * Register a new callback to a specific template.
  109125. * The best example for the usage can be found in the DefaultViewer
  109126. *
  109127. * @param templateName the templateName to register the event to
  109128. * @param callback The callback to be executed
  109129. * @param eventType the type of event to register
  109130. * @param selector an optional selector. if not defined the parent object in the template will be selected
  109131. */
  109132. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  109133. if (!this._callbacksContainer[templateName]) {
  109134. this._callbacksContainer[templateName] = [];
  109135. }
  109136. this._callbacksContainer[templateName].push({
  109137. eventType: eventType,
  109138. callback: callback,
  109139. selector: selector
  109140. });
  109141. };
  109142. /**
  109143. * This will remove a registered event from the defined template.
  109144. * Each one of the variables apart from the template name are optional, but one must be provided.
  109145. *
  109146. * @param templateName the templateName
  109147. * @param callback the callback to remove (optional)
  109148. * @param eventType the event type to remove (optional)
  109149. * @param selector the selector from which to remove the event (optional)
  109150. */
  109151. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  109152. var callbackDefs = this._callbacksContainer[templateName] || [];
  109153. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  109154. };
  109155. EventManager.prototype._eventTriggered = function (data) {
  109156. var templateName = data.template.name;
  109157. var eventType = data.event.type;
  109158. var selector = data.selector;
  109159. var callbackDefs = this._callbacksContainer[templateName] || [];
  109160. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  109161. callbackDef.callback(data);
  109162. });
  109163. };
  109164. /**
  109165. * Dispose the event manager
  109166. */
  109167. EventManager.prototype.dispose = function () {
  109168. this._callbacksContainer = {};
  109169. };
  109170. return EventManager;
  109171. }());
  109172. exports.EventManager = EventManager;
  109173. /***/ }),
  109174. /* 36 */
  109175. /***/ (function(module, exports, __webpack_require__) {
  109176. "use strict";
  109177. Object.defineProperty(exports, "__esModule", { value: true });
  109178. var mappers_1 = __webpack_require__(3);
  109179. var types_1 = __webpack_require__(37);
  109180. var deepmerge = __webpack_require__(1);
  109181. var babylonjs_1 = __webpack_require__(0);
  109182. /**
  109183. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  109184. * parse the object and return a conform ViewerConfiguration.
  109185. * It is a private member of the scene.
  109186. */
  109187. var ConfigurationLoader = /** @class */ (function () {
  109188. function ConfigurationLoader(_enableCache) {
  109189. if (_enableCache === void 0) { _enableCache = false; }
  109190. this._enableCache = _enableCache;
  109191. this._configurationCache = {};
  109192. this._loadRequests = [];
  109193. }
  109194. /**
  109195. * load a configuration object that is defined in the initial configuration provided.
  109196. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  109197. *
  109198. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  109199. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  109200. * @returns A promise that delivers the extended viewer configuration, when done.
  109201. */
  109202. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  109203. var _this = this;
  109204. if (initConfig === void 0) { initConfig = {}; }
  109205. var loadedConfig = deepmerge({}, initConfig);
  109206. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  109207. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  109208. if (loadedConfig.configuration) {
  109209. var mapperType_1 = "json";
  109210. return Promise.resolve().then(function () {
  109211. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  109212. // a file to load
  109213. var url = '';
  109214. if (typeof loadedConfig.configuration === "string") {
  109215. url = loadedConfig.configuration;
  109216. }
  109217. // if configuration is an object
  109218. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  109219. url = loadedConfig.configuration.url;
  109220. var type = loadedConfig.configuration.mapper;
  109221. // empty string?
  109222. if (!type) {
  109223. // load mapper type from filename / url
  109224. type = loadedConfig.configuration.url.split('.').pop();
  109225. }
  109226. mapperType_1 = type || mapperType_1;
  109227. }
  109228. return _this._loadFile(url);
  109229. }
  109230. else {
  109231. if (typeof loadedConfig.configuration === "object") {
  109232. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  109233. return loadedConfig.configuration.payload || {};
  109234. }
  109235. return {};
  109236. }
  109237. }).then(function (data) {
  109238. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  109239. var parsed = mapper.map(data);
  109240. var merged = deepmerge(loadedConfig, parsed);
  109241. if (callback)
  109242. callback(merged);
  109243. return merged;
  109244. });
  109245. }
  109246. else {
  109247. if (callback)
  109248. callback(loadedConfig);
  109249. return Promise.resolve(loadedConfig);
  109250. }
  109251. };
  109252. /**
  109253. * Dispose the configuration loader. This will cancel file requests, if active.
  109254. */
  109255. ConfigurationLoader.prototype.dispose = function () {
  109256. this._loadRequests.forEach(function (request) {
  109257. request.abort();
  109258. });
  109259. this._loadRequests.length = 0;
  109260. };
  109261. ConfigurationLoader.prototype._loadFile = function (url) {
  109262. var _this = this;
  109263. var cacheReference = this._configurationCache;
  109264. if (this._enableCache && cacheReference[url]) {
  109265. return Promise.resolve(cacheReference[url]);
  109266. }
  109267. return new Promise(function (resolve, reject) {
  109268. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  109269. var idx = _this._loadRequests.indexOf(fileRequest);
  109270. if (idx !== -1)
  109271. _this._loadRequests.splice(idx, 1);
  109272. if (_this._enableCache)
  109273. cacheReference[url] = result;
  109274. resolve(result);
  109275. }, undefined, undefined, false, function (request, error) {
  109276. var idx = _this._loadRequests.indexOf(fileRequest);
  109277. if (idx !== -1)
  109278. _this._loadRequests.splice(idx, 1);
  109279. reject(error);
  109280. });
  109281. _this._loadRequests.push(fileRequest);
  109282. });
  109283. };
  109284. return ConfigurationLoader;
  109285. }());
  109286. exports.ConfigurationLoader = ConfigurationLoader;
  109287. /***/ }),
  109288. /* 37 */
  109289. /***/ (function(module, exports, __webpack_require__) {
  109290. "use strict";
  109291. Object.defineProperty(exports, "__esModule", { value: true });
  109292. var minimal_1 = __webpack_require__(38);
  109293. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  109294. var default_1 = __webpack_require__(39);
  109295. exports.defaultConfiguration = default_1.defaultConfiguration;
  109296. var extended_1 = __webpack_require__(46);
  109297. var shadowLight_1 = __webpack_require__(47);
  109298. var environmentMap_1 = __webpack_require__(48);
  109299. var deepmerge = __webpack_require__(1);
  109300. /**
  109301. * Get the configuration type you need to use as the base for your viewer.
  109302. * The types can either be a single string, or comma separated types that will extend each other. for example:
  109303. *
  109304. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  109305. *
  109306. * @param types a comma-separated string of the type(s) or configuration to load.
  109307. */
  109308. var getConfigurationType = function (types) {
  109309. var config = {};
  109310. var typesSeparated = types.split(",");
  109311. typesSeparated.forEach(function (type) {
  109312. switch (type.trim()) {
  109313. case 'environmentMap':
  109314. config = deepmerge(config, environmentMap_1.environmentMapConfiguration);
  109315. break;
  109316. case 'shadowDirectionalLight':
  109317. config = deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  109318. break;
  109319. case 'shadowSpotLight':
  109320. config = deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  109321. break;
  109322. case 'extended':
  109323. config = deepmerge(config, extended_1.extendedConfiguration);
  109324. break;
  109325. case 'minimal':
  109326. config = deepmerge(config, minimal_1.minimalConfiguration);
  109327. break;
  109328. case 'none':
  109329. break;
  109330. case 'default':
  109331. default:
  109332. config = deepmerge(config, default_1.defaultConfiguration);
  109333. break;
  109334. }
  109335. if (config.extends) {
  109336. config = deepmerge(config, getConfigurationType(config.extends));
  109337. }
  109338. });
  109339. return config;
  109340. };
  109341. exports.getConfigurationType = getConfigurationType;
  109342. /***/ }),
  109343. /* 38 */
  109344. /***/ (function(module, exports, __webpack_require__) {
  109345. "use strict";
  109346. Object.defineProperty(exports, "__esModule", { value: true });
  109347. /**
  109348. * The minimal configuration needed to make the viewer work.
  109349. * Some functionalities might not work correctly (like fill-screen)
  109350. */
  109351. exports.minimalConfiguration = {
  109352. version: "0.1",
  109353. templates: {
  109354. main: {
  109355. html: __webpack_require__(12)
  109356. },
  109357. loadingScreen: {
  109358. html: __webpack_require__(13),
  109359. params: {
  109360. backgroundColor: "#000000",
  109361. loadingImage: __webpack_require__(14)
  109362. }
  109363. },
  109364. viewer: {
  109365. html: __webpack_require__(15),
  109366. },
  109367. overlay: {
  109368. html: __webpack_require__(16),
  109369. params: {
  109370. closeImage: __webpack_require__(17),
  109371. closeText: 'Close'
  109372. }
  109373. },
  109374. error: {
  109375. html: __webpack_require__(18)
  109376. }
  109377. },
  109378. engine: {
  109379. antialiasing: true
  109380. }
  109381. };
  109382. /***/ }),
  109383. /* 39 */
  109384. /***/ (function(module, exports, __webpack_require__) {
  109385. "use strict";
  109386. Object.defineProperty(exports, "__esModule", { value: true });
  109387. /**
  109388. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  109389. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  109390. */
  109391. exports.defaultConfiguration = {
  109392. version: "3.2.0-alpha4",
  109393. templates: {
  109394. main: {
  109395. html: __webpack_require__(12),
  109396. params: {
  109397. babylonFont: __webpack_require__(40),
  109398. noEscape: true
  109399. }
  109400. },
  109401. fillContainer: {
  109402. html: __webpack_require__(41),
  109403. params: {
  109404. disable: false
  109405. }
  109406. },
  109407. loadingScreen: {
  109408. html: __webpack_require__(13),
  109409. params: {
  109410. backgroundColor: "#000000",
  109411. loadingImage: __webpack_require__(14)
  109412. }
  109413. },
  109414. viewer: {
  109415. html: __webpack_require__(15)
  109416. },
  109417. navBar: {
  109418. html: __webpack_require__(42),
  109419. params: {
  109420. speedList: {
  109421. "0.5x": "0.5",
  109422. "1.0x": "1.0",
  109423. "1.5x": "1.5",
  109424. "2.0x": "2.0",
  109425. },
  109426. logoImage: __webpack_require__(43),
  109427. logoText: 'BabylonJS',
  109428. logoLink: 'https://babylonjs.com',
  109429. hideHelp: true,
  109430. disableOnFullscreen: true,
  109431. },
  109432. events: {
  109433. pointerdown: {
  109434. 'navbar-control': true,
  109435. 'help-button': true
  109436. },
  109437. input: {
  109438. 'progress-wrapper': true
  109439. },
  109440. pointerup: {
  109441. 'progress-wrapper': true
  109442. }
  109443. }
  109444. },
  109445. overlay: {
  109446. html: __webpack_require__(16),
  109447. params: {
  109448. closeImage: __webpack_require__(17),
  109449. closeText: 'Close'
  109450. }
  109451. },
  109452. help: {
  109453. html: __webpack_require__(44)
  109454. },
  109455. share: {
  109456. html: __webpack_require__(45)
  109457. },
  109458. error: {
  109459. html: __webpack_require__(18)
  109460. }
  109461. },
  109462. camera: {
  109463. behaviors: {
  109464. autoRotate: {
  109465. type: 0
  109466. },
  109467. framing: {
  109468. type: 2,
  109469. zoomOnBoundingInfo: true,
  109470. zoomStopsAnimation: false
  109471. },
  109472. bouncing: {
  109473. type: 1
  109474. }
  109475. },
  109476. wheelPrecision: 200,
  109477. },
  109478. skybox: {},
  109479. ground: {
  109480. receiveShadows: true
  109481. },
  109482. engine: {
  109483. antialiasing: true
  109484. },
  109485. scene: {}
  109486. };
  109487. /***/ }),
  109488. /* 40 */
  109489. /***/ (function(module, exports) {
  109490. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAA+UAA8AAAAAHHQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp9fVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAABnAAAAorruyj1jdnQgAAAEEAAAACAAAAAqCdkJr2ZwZ20AAAQwAAAA8AAAAVn8nuaOZ2FzcAAABSAAAAAMAAAADAAIABtnbHlmAAAFLAAAA+QAAAVa6mApOGhlYWQAAAkQAAAAMgAAADb+JuGqaGhlYQAACUQAAAAVAAAAJBABCAZobXR4AAAJXAAAACQAAAAkEd4EOWxvY2EAAAmAAAAAHAAAABwD3wWsbWF4cAAACZwAAAAcAAAAIACGANFuYW1lAAAJuAAABTsAAAvzMvOUeHBvc3QAAA70AAAAEwAAACD/UQB3cHJlcAAADwgAAACJAAAA03i98g542mNgZjdjnMDAysDBOovVmIGBURpCM19kSGMS4mBl5WJkYgQDBiAQYEAA32AFBQYHBt7vvBxgPoRkAKtjgfAUGBgAkl0GmgB42hXJUxQYBgAEwclf2qa2bdu2bdu2bdu2bdu2bTtlur15734WAwz4fwYZPHCIgWGoMHQYJqqD+mHDcGH4MEIYMYwURg6jhFHDaGH0MEYYM4wVxg7jhHHDeGH8MEGYMEwUJg6ThEnDZGHyMEWYMkwVpg7ThGnDdGH6MEOYMcwUZg6zhFnDbGH2MEeYM8wV5g7zhHnDfGH+sEBYMCwUFg6LhEXDYmHxsERYMiwVlg7LhGXDcmH5sEJYMawUVg6rhFXDamH1sEZYM6wV1g7rhHXDemH9sEHYMGwUNg6bhE3DZmHzsEXYMmwVtg7bhG3DdmH7sEPYMewUdg67hF3DbmH3sEfYM+wV9g77hH3DfmH/cEA4MBwUDg6HhEPDYeHwcEQ4MhwVjg7HhGPDceH4cEI4MZwUTg6nhFPDaeH0cEY4M5wVzg7nhHPDeeH8cEG4MFwULg6XhEvDZeHycEW4MlwVrg7XhGvDdeH6cEO4MdwUbg63hFvDbeH2cEe4M9wV7g73hHvDfeH+8EB4MDwUHg6PhEfDY+Hx8ER4MjwVng7PhGfDc+H58EJ4MbwUXg6vhFfDa+H18EZ4M7wV3g7vhHfDe+H98EH4MHwUPg6fhE/DZ+Hz8EX4MnwVvg7fhG/Dd+H78EP4MfwUfg6/hF/Db+H3MDj8Ef4Mf4W/wz/h3zAk/gPilQDpAAAAeNpjYGBgYmBkAAERBmYwy42BjcEISPMCRSAyhAATAwtDDJAWYhAAmsEE1KnwnO+5w/PMF0+/7fvO+/8/2DSF57xAsQywGM////+//H8k8V3imMR8cRVOH6AKdLtYgJiHgRsAFgccngB42mPQYghlKGBoYFjFyMDYwOzAeIDBAYsIEAAAqhwHlXjaXY+/TsNADMZzJLSEJ0A6IZ11KkOViJ3phksk1CUlDOelgNRKpO+AlIXFA8/ibhnzYgjMEf4utr/P+ny/c6f5yXx2nKVHKilWnDfhoNQLDurtmf35IU/vNmVhTNV5VvdlwWoJomtOF/VNsGjI0PWWTG0eH7acLWKXxY7w0nDShk7qbQB2qL/HHeJVPJLFI4QS30/xfYxL+rUsVobTiyasA/des/OoAUzFYxN49BoQf8ikP3VnE+NsOWXbwE5zgkSfygL3RJqE+0uPf/Wgkv+G+23Iv6tB9U3c9Bb0h2HBgrChl2fbUAkaYPkOhPxkxgABAAIACAAK//8AD3jaVVRNaBtHFH5vVrtjGWJnO1orWTtyV1v91CZSkLRSqLGjOCDs4CalF4MWuaHgHgo5GJJAculQCgbTUrB76LG1UeglOTQlpae69NJDQwqBHmroLaEXl+RSGmV30jeSUpJdZub9f9+s3hMwuAmQ+MS8BgZwgKrt2TnP9m4af0Z32d34vHmtt/VF4gIgCHzED62TYAJgOokN5DvtSESibexYJ0kyDtvRZYozmMFjK9RxSVZIIt+LOlGnbcRGzAxjN1prGypiVAQkSE4vHCHF9m30HM+u0hFwKXshdmMpza4KuYwldnuhZFKFZlcCo2zJgTJZHwVtQTDwDKTxdfReAiJyPv2HbbEtoFiJYJJhcD+s2r7GYlJKQxfpgdVf2i8BeDwCMAIOHKPYAgXyQpJpXp7O0odHF9qTe22cx/mnhgk9mQhZTipCTQDm1AEzduOQdXcpQv2sfDkC8YHKoWSgJOagj0VGYr8MHejCHfgJ7hNaaoz5XraMPD3h2FrJltg8FrhF1hILagtsDhslDGySqp7eKhnmUCBPawmzY6RlyLpAwSWGlXpQy89itoCenZogM+YXcA4rE07KmkUnxVFXthzyeY16tTKNGpcC64FdyAe1M9g3YkqHkV6vepUJ+xWND4sNDCOQqbWKz8EVOx88EFoutmoZuSNcJbWkLQ/fCZopvzTJoNjqBEGnVXTLZ4ufrWu/gsmSn9LeY6U3Jl7zTqHv5vOudIXajg/ybm4yMZKYzO33jeI5CJewSMb128J1xb7Iu27+UJBA2u1n3Tzh9v39fRhLe3NQlbZEU+OK7fUHr3CU2/+zv5i+9BZKzUtz1Zxn3m6eOvIp+dmXmqp2CW/2+FQl58SgGQi8rHHLS+8ulbW+72quWrrV5/aC9N8D0uIW6xOipR4NhT/6Oy2AUeqWQVcKKMAslKEKDZiDM3AOVqhrhj3gD1tEDH99f9gNwvaPM5opxwvMwHOQY8NEauk05vigvdHY7+zdaLVu7HVenItXVqvV1SuLi1dXK5XVqx9LGkAlLUDZ+z1UT9rmBfUkxKO9b3E8VI+t79uDebDg5SL6jIHSF18uZ+ohkP/SUjQuUj/MpFrttnoc4jiVPEoIGxs/xAcsp0eI/pxoLhnNy18wTt8gCyW6NbfRprvYNPoWD5JmyuJoClxAPQm8lvezZOANrFNyLFn99fhDo2k0z83HMr7INthG/HmimZmKq2pzjd07sVScWa5Pyzenx9zReCW7yb5z2EeSXcez0X31UOJKYhy/UpfUb6PZe+pH/Eb9gqfxdPR+4TyVWMPr7NcTU5lgeWa6kKT8zSy748B/J9hGtnjaY2BkYGBgOr5OfiXL8nh+m68M3BwMILD/78EGEH2dk7sORHMwgMU5GZhAFAA9tgkfAAB42mNgZGDgYAABOMnIgApYAQLNACAAAAAFKgCmAAAAAAIxAAAAAAAACAAAEwADAIACAAKAAIAAAAAAAIAAAAAUABQAFAAUACgAPQBaAHAAhQC5AdACUQKteNpjYGRgYOBluMDAxQACjGASxE4BsxgAGg8BWHjanVTNb9xEFB/XTpPQJCqUIlBVGFWotNXibcIh/RBCaSvRQtJKaVSp4jRrz66Hej3WzLjG4ozgwgkhJG6IUyUOIA4IJMQB/hGO/Be89zzeddKlAnblmd+8ee/3Pm3G2OaxfRYw+gUruLSQnYJTi4+x5eCMx2FPHvXwElsLznl8nD0fxB4vs6vBOx6vsNPBRx6fYJeCzz1eD/4IfvJ4g+QhC6IQ/K6FHxNeAnwy/JTwcZJ/RXiZ5N8SXiH8I+FVYErD3z0O2PnoDY+PsY1oz+OwJ496eIm9HH3g8XF2LrIeLzMTfenxCru0tOzxCXawtOnxevjZ0iceb8zkz/VyOYFxrq4TXuvJNxCvniV8EuNcvUj4FOAXVrcJv9jTP008dwi/1JO/QrYPCZ8hnQnhsz2d13r4ddKvCV8i3Mb/JuEvEK/04l/p+Vrrydd8Lk/41uXNbb6nEqOtHjt+U5tSG+GULmK+k+d8X00yZ/m+tNI8lmm8fluOjKz5vVIWB00p+a5odOV4ricq4YkuG4MWHJkvv8XP47Y94PsiLzN+WxSJTh6B9D2dFfx2lVr0c5Apy/M+z1gbfkONcpWInHuPoKPBKbe6MonkGG4tjORVkUrDXSb53p0DvqsSWVh5nVspuZyOZJrKlOetlKfSJkaVmB75SKUTKrfxDTFqcpDt3drd4jvWSmf35aTKhXkgjUXtrXj7itdCpVbnvpxoiYEJ7oxI5VSYR1yP22BmNZ0YXZUoTvS0FIWSNl5Y8My58tpwWNd1PO3uY7AZuqbUEyPKrBmOdeHscG5uq7LMFWSIFzF/qCs+FQ2vIFeHVUUxd5onRgonBzxVtoRKD7goUl4aBbcJqEjYheWlNFPlHNCNGkqiq5uDCyi/6cAYPQyeTrU0Oq0SN+A4LWA7QJvOgSp4nakk60VWg1NVJHkFTZpHr4u84RfUxbZ/PXVgeFa0bbtVMeFGWmdUglWdO0DzGdd1qsAFBV6cnGILjAKvqa6LXIv0cPVEWyoYM0hHgytYK1fCuKYS00SdTObl4YrCC1Q0Xh0bAoRQn0yNFMQcs7tMM8OmTLAc0Ig1wTqT7ENWsL/gmd/dZw72gqWwGvhQfh3+EP4a/gbPz+Ev4XfsCeNsi11mm2wb0B5TLAE9zSw8Y7Dl7CaxlbQKkChABYvhZgf4c9j3QTZhGdxZOknYJWg/hjUFzRtgBxFSpAV5ucV2wSsyWNJFS7SbsAq0MNIHxGC9N4wxhgivHOHqmPo894lHw8rBGiMS8DiKPgXplPgfgQwzxJuMdBflPqFzBdl32gnsUzhjTRVlGv+HqmGNHEivsSH8a/rHwHfUPvZ+hoAbYpkQTwkMDUjHxIbZDhd6txRzCVVS1AM+s8C+PaScOFWigb2i2rWVaCvWaaNMU9YGNDAPyQZwTkmvpF41JGlnjIPMwF1rm3gW6c+CuEvqLObs6A6tRhRH14mcMkKrLq7WwlIXzFOS8SyHwb/qaknnFGwSOA+oXu28tn4HMz9HM1A0izXVKYF1cc1qnylqJ5BNRXOXLqw92uSELoD+RdhxQke+LovY2xj+b23n7CkxTUBmaI4ddS6ZzeqiDDrvT8d1vTcDmEmbiyN/3VuA/G2uKUhqylzTW/ms2ROHpkpSX7Rf26xaXNGbVZElRtt1s+NBzZze5H+e0farVvjOzNm7N0T5KuP8YLwjqnTb2/kXWdAEd+c/4dT/WstD32T6Kh+6B+/Rq9Fm9H70bvQ2rFcPMRVgfxf0HlPdijbK4Pvgm5BRN3dA00C8mI34G3v+ha8AeNpjYGYAg/9+DOUMWAAAKSoByAB42tvAoM2wiZGTSZtxExeI3M7Vmhtqq8rAob2dOzXYQU8GxOKJ8LDQkASxeJ3NteWFQSw+HRUZER4Qi19OQpiPA8QS4OPhZGcBsQTBAMQS2jChIMAAyGLYzgg3mgluNDPcaBa40axwo9nkJKFGs8ON5oAbzQk3epMwI7v2BgYF19pMCRcAxAEoGgAAAA=="
  109491. /***/ }),
  109492. /* 41 */
  109493. /***/ (function(module, exports) {
  109494. module.exports = "<style>fill-container{display:flex}fill-container>*{touch-action:none}</style> {{#unless disable}} <style>fill-container{width:100%;height:100%;justify-content:flex-start;align-items:stretch;align-content:stretch}fill-container>*{flex:1 1 auto;flex-direction:row;justify-content:flex-start;align-items:stretch;align-content:stretch}</style> {{/unless}} <viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  109495. /***/ }),
  109496. /* 42 */
  109497. /***/ (function(module, exports) {
  109498. module.exports = "<style>nav-bar{position:absolute;height:48px;width:100%;bottom:10px;display:flex;justify-content:center}nav-bar .nav-container{display:flex;flex-direction:row;margin:0 10px;height:100%;width:100%;justify-content:center}nav-bar .animation-control{background-color:rgba(91,93,107,.75);display:flex;flex-direction:row;height:100%;width:100%;max-width:1280px;justify-content:center}nav-bar .flex-container{display:flex;flex-direction:row;justify-content:center;height:100%;width:100%}nav-bar button{background:0 0;border:none;color:#fff;margin:0;padding:0;height:100%;min-width:48px;cursor:pointer}nav-bar button:active,nav-bar button:focus,nav-bar button:hover{background:0 0;border:none;outline:0}nav-bar button:hover{background-color:rgba(22,24,26,.2)}nav-bar .control-text{font-family:\"Segoe UI\";font-size:12px;font-weight:400;pointer-events:none}nav-bar .icon,nav-bar img{pointer-events:none}.logo-button{display:flex;align-items:center;flex-direction:row;justify-content:center;background-color:rgba(91,93,107,.75);height:48px;min-width:48px;margin-right:4px}.logo-button img{height:20px;width:20px}.types{display:flex;flex-direction:column;width:48px}.speed .flex-container,.types .flex-container{align-items:center}.menu-options{position:absolute;bottom:48px;width:48px;background-color:rgba(22,24,26,.9)}.animation-label,.help,.logo-button,.speed,.types-icon{display:none}.types-icon:after{font-size:16px;content:\"\\F6BE\"}.up-icon:after{line-height:16px;font-size:12px;content:\"\\E70E\"}.play-icon:after{font-size:16px;content:\"\\E768\"}.pause-icon:after{font-size:16px;content:\"\\E769\"}.fullscreen-icon:after{font-size:16px;content:\"\\E740\"}.help-icon:after{font-size:16px;content:\"\\F70C\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer}.animation-number{margin:0 6px}.speed-text{margin-right:6px}.progress-circle{width:12px;height:12px;border:2px solid #fff;border-radius:50%;background-color:#5b5d6b;cursor:pointer;position:relative;bottom:10px;pointer-events:none}.default-control{display:flex;flex-direction:row;height:100%;background-color:rgba(91,93,107,.75)}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button:hover{background-color:transparent;color:#fff}.menu-options .animation-number{margin:0 18px 0 6px}.menu-options .speed-text{margin-right:18px}.menu-options{visibility:hidden}.open .menu-options{visibility:visible}.types .menu-options{width:144px}.types .menu-options button{padding:0 8px;justify-content:left}.types .menu-options button>*{display:flex;margin:8px}.types .menu-options button span.animation-number{display:none}@media screen and (min-width:540px){.help,.speed,.types-icon{display:inline-block}.logo-button{display:flex}.types{width:84px}.progress-bar-container{margin:0 12px}.speed{width:64px}.speed .menu-options{width:64px}}@media screen and (min-width:1024px){.animation-label{display:block;margin-left:6px;text-overflow:ellipsis;overflow:hidden}nav-bar button.animation-buttons{padding:0 8px;justify-content:left}.icon.up-icon{margin-left:8px}nav-bar button.animation-buttons>div{display:flex;pointer-events:none}.animation-number{display:none}.progress-bar-container{margin:0 12px}.types{width:144px}}.progress-wrapper{-webkit-appearance:none;cursor:pointer;width:100%;outline:0;margin:0 12px;background-color:transparent}.progress-wrapper::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:-10px}.progress-wrapper::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:#fff}.progress-wrapper::-moz-range-progress{background-color:#fff;height:2px}.progress-wrapper::-moz-range-thumb{width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1)}.progress-wrapper::-moz-range-track{background:#fff;height:2px}.progress-wrapper::-ms-track{height:2px;background:0 0;border-color:transparent;border-width:10px 0;color:transparent}.progress-wrapper::-ms-fill-lower{background:#fff;border-radius:5px}.progress-wrapper::-ms-fill-upper{background:#fff;border-radius:5px}.progress-wrapper::-ms-thumb{width:16px;height:16px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:0}span{display:inline-block}</style> {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} <style>nav-bar .nav-container{justify-content:flex-end}</style> {{else}} <style>nav-bar .nav-container{justify-content:space-between}</style> {{/if}} {{/if}} {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=nav-container id=navbar-control> {{#unless hideLogo}} <div class=logo-button title={{logoText}}> {{#if logoLink}} <a href={{logoLink}} target=_blank> <img src={{logoImage}}> </a> {{else}} <img src={{logoImage}}> {{/if}} </div> {{/unless}}{{#unless (or (not animations) hideAnimations)}} <div class=animation-control> <div class=types> <button class=\"flex-container animation-buttons\" id=types-button> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{selectedAnimationName}}</span> <span class=\"control-text animation-number\">{{selectedAnimation}}</span> {{#if (gt (count animations) 1)}} <span class=\"icon up-icon\"></span> {{/if}} </button> <div class=menu-options> {{#each animations}} {{#unless (eq ../selectedAnimation (add @index 1))}} <button class=\"flex-container animation-buttons\" id=label-option-button data-value={{this}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{this}}</span> <span class=\"control-text animation-number\">{{add @index 1}}</span> </button> {{/unless}} {{/each}} </div> </div> <div class=progress-control id=progress-control> <button class=play-pause id=play-pause-button> {{#if paused}} <span class=\"icon play-icon\"></span> {{else}} <span class=\"icon pause-icon\"></span> {{/if}} </button> <input class=progress-wrapper id=progress-wrapper type=range min=0 max=100 step=0.01> </div> <div class=speed> <button class=flex-container id=speed-button> <span class=\"control-text speed-text\">{{selectedSpeed}}</span> <span class=\"icon up-icon\"></span> </button> <div class=menu-options> {{#eachInMap speedList}} {{#unless (eq ../selectedSpeed id)}} <button class=flex-container id=speed-option-button data-value={{value}}> <span class=\"control-text speed-text\">{{id}}</span> </button> {{/unless}} {{/eachInMap}} </div> </div> </div> {{/unless}} <div class=default-control> {{#unless hideHelp}} <button class=help id=help-button title=Help> <span class=\"icon help-icon\"></span> </button> {{/unless}} {{#unless hideFullScreen}} <button class=fullscreen id=fullscreen-button title=Fullscreen> <span class=\"icon fullscreen-icon\"></span> </button> {{/unless}} </div> </div>";
  109499. /***/ }),
  109500. /* 43 */
  109501. /***/ (function(module, exports) {
  109502. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCoCixHw/fE0DIKiKAIE+vM4qlDi1I531/fYRDdOPHf/dn9/HwAAAAAmb5bkNMnSKAAAgD74HyMAAAAAmJwqJVyfJqmbP4+a/9m3JIskH40JAADo0m9OZgMAAACM2ukTr6MX/OtEbQAAoFNiNgAAAMB41FkH6yrJ2R7+d4raAABAJ8RsAAAAgOFZPd+6znpl+MmB/2+K2gAAQKvEbAAAAIB+q/LjmvDjDv//EbUBAIBWiNkAAAAA/bFaD746df3S51t3QdQGAAAOSswGAAAA6Mbj09ZnA/33IWoDAAAHIWYDAAAAHF6dzXB9MsJ/j6I2AACwV2I2AAAAwP7MsrkivOvnW3dB1AYAAPZCzAYAAADYTZV1sK6bvz42lv8StQEAgFcRswEAAAB+bRWtq6xPXR8Zy4uI2gAAwE7EbAAAAIBNddbh+jTJmZHshagNAABsRcwGAAAApmr1fOuHrxNjOThRGwAAeBExGwAAAJiCVbiusw7Xnm/dLVEbAAB4lpgNAAAAjE2VdbCu4/nWfSdqAwAATxKzAQAAgCF7vCbc862HS9QGAAA2iNkAAADAUNRZR+sqwvVYidoAAEASMRsAAADon4fPt66an0+MZXJEbQAAmDgxGwAAAOhSlR9XhR8bCw+I2gAAMFFiNgAAANCW1Xrw1anr0yRHxsILidoAADAxYjYAAABwCHU2T117vjX7ImoDAMBEiNkAAADAa9XZXBPu+da0QdQGAICRE7MBAACAl5plc0W451vTB6I2AACMlJgNAAAAPKXKOljXzV8L1/SZqA0AACMjZgMAAACnT7yOjIWBErUBAGAkxGwAAACYljolVlfNn2dGwkiJ2gAAMHBiNgAAAIzT6vnWD18nxsIEidoAADBQYjYAAAAMX9W86qzDtedbwyZRGwAABkbMBgAAgGGpsg7WdTzfGrYlagMAwECI2QAAANBfj9eEe7417I+oDQAAPSdmAwAAQD/UWUfrKsI1tEXUBgCAnhKzAQAAoF2zbK4Ir5KcGAt0TtQGAICeEbMBAADgcKr8uCr82Fig10RtAADoCTEbAAAA9mN1yvrhqesjY4HBErUBAKBjYjYAAABsr87mqWvPt4bxErUBAKAjYjYAAAA8r87mmnDPt4ZpErUBAKBlYjYAAAAUs2yuCPd8a+ApojYAALREzAYAAGCKqqyDdd38tXANbEPUBgCAAxOzAQAAGLvTJ15HxgLsiagNAAAHImYDAAAwJnVKrK6aP8+MBGiJqA0AAHsmZgMAADBED59vXTU/nxgL0AOiNgAA7ImYDQAAQN9VzavOek2451sDfSdqAwDAK4nZAAAA9EmVdbCu4/nWwPCJ2gAAsCMxGwAAgK6cPnp5vjUwZqI2AABsScwGAACgDXU2w7XnWwNTJWoDAMALidkAAADs0yybK8KrCNcATxG1AQDgF8RsAAAAdlXlx1Xhx8YCsBVRGwAAfkLMBgAA4CVWsbrK+tT1kbEA7I2oDQAAj4jZAAAAPFZn89T1mZEAtEbUBgCAhpgNAAAwbXU214R7vjVAP4jaAABMnpgNAAAwDbOUWF3H860BhkTUBgBgssRsAACA8amyDtZ1PN8aYAxEbQAAJkfMBgAAGLbTJ17CNcB4idoAAEyGmA0AADAcdUqsrpo/z4wEYLJEbQAARk/MBgAA6J+Hz7eump9PjAWAJ4jaAACMlpgNAADQrap51VmvCT82FgC2JGoDADA6YjYAAEB7Hq4Ir+P51gDsn6gNAMBoiNkAAACHcfro5fnWALRJ1AYAYPDEbAAAgNersxmuPd8agL4QtQEAGCwxGwAA4OVm2VwRXkW4BmAYRG0AAAZHzAYAAHhalfVJ67r562NjAWDgRG0AAAZDzAYAAFhH6yrrU9dHxgLAiInaAAD0npgNAABMTZ3NU9dnRgLAhInaAAD0lpgNAACM1er51g9fnm8NAE8TtQEA6B0xGwAAGINVuK6zDteebw0A2xO1AQDoDTEbAAAYmirrYF3H860B4BBEbQAAOidmAwAAfXb6xEu4BoD2iNoAAHRGzAYAAPqizjpYV0nOjAQAekPUBgCgdWI2AADQtofPt66an0+MBQAGQdQGAKA1YjYAAHBIVfOqsz51fWwsADB4ojYAAAcnZgMAAPuyWg++OnXt+dYAMH6iNgAAByNmAwAAuzh99PJ8awCYNlEbAIC9E7MBAIBfqbMZrj3fGgD4GVEbAIC9EbMBAICVWTZXhFcRrgGA3YjaAAC8mpgNAADTVGV90rpu/vrYWACAPRO1AQDYmZgNAADjt4rWVdanro+MBQBokagNAMDWxGwAABiXOutwfZrkzEgAgB4RtQEAeDExGwAAhmn1fOuHL8+3BgCGQtQGAOCXxGwAAOi/Vbiusw7Xnm8NAIyBqA0AwE+J2QAA0C9V1sG6judbAwDTIGoDAPADMRsAALrzeE2451sDAFMnagMA8F9iNgAAtKPOOlpXEa4BAJ4jagMAIGYDAMCePXy+ddX8fGIsAAA7EbUBACZMzAYAgN1V+XFV+LGxAADsnagNADBBYjYAALzMaj346tT1aZIjYwEAaJWoDQAwIWI2AAD86PFpa8+3BgDoF1EbAGACxGwAAKauzma49nxrAIDhELUBAEZMzAYAYCpm2VwR7vnWAADjIWoDAIyQmA0AwBhVWQfruvlr4RoAYPxEbQCAERGzAQAYulW0rrI+dX1kLAAAkyZqAwCMgJgNAMCQ1FmH69MkZ0YCAMAzRG0AgAETswEA6KPV860fvk6MBQCAHYnaAAADJGYDANC1Vbiusw7Xnm8NAMAhiNoAAAMiZgMA0KYq62Bdx/OtAQDohqgNADAAYjYAAIfyeE2451sDANA3ojYAQI+J2QAA7EOddbSuIlwDADAsojYAQA+J2QAAbOPx862rJCfGAgDASIjaAAA9ImYDAPAzVX5cFX5sLAAATICoDQDQA2I2AADJ+pT1w1PXR8YCAMDEidoAAB0SswEApqfO5qlrz7cGAIDnidoAAB0QswEAxq3O5ppwz7cGAIDdidoAAC0SswEAxmGWzRXhnm8NAACHI2oDALRAzAYAGJ4q62BdN38tXAMAQPtEbQCAAxKzAQD67fSJ15GxAABAr4jaAAAHIGYDAPRHnRKrq+bPMyMBAIBBEbUBAPZIzAYAaN/q+dYPXyfGAgAAoyFqAwDsgZgNAHBYVfOqsw7Xnm8NAADTIGoDALyCmA0AsD9V1sG6judbAwAAhagNALADMRsAYDeP14R7vjUAAPArojYAwBbEbACAX6uzjtZVhGsAAOB1RG0AgBcQswEA1mbZXBFeJTkxFgAA4EBEbQCAZ4jZAMBUVflxVfixsQAAAB0QtQEAniBmAwBT8HBFeN38fGQsAABAz4jaAAAPiNkAwNjU2Tx17fnWAADA0IjaAAARswGAYauzuSbc860BAIAxEbUBgEkTswGAIZilxOo6nm8NAABMj6gNAEySmA0A9E2VdbCu4/nWAAAAK6I2ADApYjYA0KXTJ17CNQAAwPNEbQBgEsRsAKAtdUqsrpo/z4wEAADgVURtAGDUxGwAYN8ePt+6an4+MRYAAICDEbUBgFESswGA16iaV531mvBjYwEAAOiEqA0AjIqYDQC8VJV1sK7j+dYAAAB9JWoDAKMgZgMATzl99PJ8awAAgOERtQGAQROzAYA6m+Ha860BAADGRdQGAAZJzAaA6Zhlc0V4FeEaAABgSkRtAGBQxGwAGKcqP64KPzYWAAAAImoDAAMhZgPA8K1idZX1qesjYwEAAOAXRG0AoNfEbAAYljqbp67PjAQAAIBXErUBgF4SswGgv+psrgn3fGsAAAAOSdQGAHpFzAaA7s1SYnUdz7cGAACge6I2ANALYjYAtKvKOljX8XxrAAAA+kvUBgA6JWYDwOGcPvESrgEAABgaURsA6ISYDQD7UWcdrKskZ0YCAADAyIjaAECrxGwA2M7D51tXzc8nxgIAAMCEiNoAQCvEbAD4uap51Vmfuj42FgAAAEgiagMAByZmA0CxWg++OnXt+dYAAADwMqI2AHAQYjYAU3T66OX51gAAAPB6ojYAsFdiNgBjVyU5zzpce741AAAAHJaoDQDshZgNwNhVSa4iYgMAAEDbRG0A4FX+ZgQAjNxtyonsP40CAAAAWnWc5F/NvfncOACAbTmZDcCUnKd8G/zIKAAAAKB1TmoDAFtxMhuAKblKOaV9bRQAAADQOie1AYCtiNkATM1tkjrJB6MAAABG6M4IGABRGwB4ETEbgKlaJPlHfNADAAAM23XKl3X/N8nfk8yaex0bqRgCURsAeJZnZgMwdbOU9eNnRgEAAPTcTZKvSZbNn19/8ffXKV/kdb/DUHimNgCwQcwGgOIiyR/GAAAA9MS3rIP1snntap4SCI+NlQH9538RURsAJk/MBoC105RT2j7gAQAA2nadzRPXtwf4vzGPqM2wiNoAMHFiNgBsmjU3yW+MAgAAOJBt14Xv20VKIDzyj4KBELUBYKLEbAB42jzJZXy4AwAAvM4+14Xv0ywlal+472Fg/31aRNQGgMkQswHg506bG+QTowAAAF6ojXXh+yRqM0SiNgBMhJgNAM+bpZzQfmsUAADAI12vC9+nKiUOuvdhSERtABg5MRsAXua8uTl2UgEAAKapr+vC962KqM0w//u5iKgNAKMjZgPAy1VJrmLtOAAAjN1dfjxxfTuxGZymbKk68x8HBkTUBoCREbMBYHuXSd4ZAwAAjMZNNsP1VyP5rzolDoraDImoDQAjIWYDwG6sHQcAgGFarQtfPviTX6tTvthrUxVD++/7IqI2AAyWmA0Au5ulrB13QgEAAPrp8brwZZLvxvIq85Q4eGwUDIioDQADJWYDwOstkrw3BgAA6Jx14e2ZR9RmeERtABgYMRsA9qNOOaVt7TgAALTDuvDuzZJcNC/3Qgzt98ciojYA9J6YDQD7M2tuhN8YBQAA7JV14f2/FxK1GSJRGwB6TswGgP27SPKHMQAAwM6sCx+mWUoYfGcUDIyoDQA9JWYDwGGcpqwd9/w4AAB4nnXh41OlhMG3RsEAfx8tImoDQG+I2QBwONaOAwDAJuvCp6VKcumeiAEStQGgJ8RsADi8ecoHOJ4dBwDA1FgXTpLUKWHwzCgYGFEbADomZgNAO06bm98TowAAYKSsC+dX6ojaDPf32yKiNgC0TswGgPbMUk5oe24cAABDZ104r3He3BsdGwUDI2oDQMvEbABo33lz42vtOAAAQ2FdOIcwTwmDojZDI2oDQEvEbADoRpXkKtaOAwDQP9aF07aLlDDoC78M8fflIqI2AByMmA0A3bpM8s4YAADoiHXh9MUsJWpfRNRmeERtADgQMRsAulennNL2gQ0AAIdmXTh9J2ozZKI2AOyZmA0A/TBLCdpnRgEAwJ5YF86QVSlR8K1RMNDfv4uI2gDwamI2APTLIsl7YwAAYEvWhTNWVURthkvUBoBXErMBoH/q5kb32CgAAPiJ66zXhC+T3BoJI3ea5DK2WTFMojYA7EjMBoB+mjU3uW+MAgBg8r5l8znXSyNhwuqUKChqM9Tf54uI2gDwYmI2APTbRZI/jAEAYDIergtfNj9bFw4/qlNOap8YBQMkagPAC4nZANB/p0muYu04AMAYWRcOrzNPiYLulxgiURsAfkHMBoBhmKWcOnhrFAAAg2VdOBzOPKI2w35/WETUBoAfiNkAMCzzlKh9ZBQAAL1mXTi0b5byqKYL90wMlKgNAI+I2QAwPKfNja1nwwEA9Id14dAfojZDJ2oDQEPMBoBhmjU3tu+MAgCgddaFg/smaOv9ZhFRG4AJE7MBYNjOm5tapw0AAA7DunAYviolCL41CgZK1AZgssRsABi+KslVrB0HANgH68Jh3PdOi4jaDJeoDcDkiNkAMB6XsT4PAGAb1oXDNNUpQfDMKBjw+9ciojYAEyBmQzdmSU6bV/Xg56Mkn5PMY20dsJs65ZS2teMAAJusCweeun9aRNRmuERtAEZPzIbDei5a/+pC9DzlwxWAXX73XMUHMgDAtFkXDrzUecqmq2OjYKBEbQBGS8yG/dg1Wv/K783NFMAuFkneGwMAMAHWhQP7MG/uo0Rthvx+uIioDcCIiNmwvTr7j9bPuU75hrD1d8AuTlNOafswBgAYC+vCgUObpxwu8PgmhkrUBmA0xGz4uTolWFcPfu4qBt2lBO2lfyzADmbNDewbowAABsi6cKCr+6iL5iVqM1SiNgCDJ2ZDv6L1r/zZ3EQB7OIiyR/GAAD0mHXhQN+I2ozl/XURURuAARKzmZI6w4nWz7lJOaV96x8psIPT5ub1xCgAgI5ZFw4MSZUSA98aBQMmagMwOGI2Y1RnHNH6OXcp3wh24QnsYpby/DcfwgAAbbIuHBiDKqI2wydqAzAYYjZDdtq8qow3Wv/Kp5So7fQCsIt5StS2Kg8A2LebbIbrr0YCjEyVEgLPjIIBE7UB6D0xmyFYBeuH8dp63LWblCDlwyFg19+xH/1eBQBe4S7rYL360xdugamoU2KgqM2QidoA9JaYTZ+I1q/ze8oJS4BdXCZ5ZwwAwAus1oUvmz9vjQQgdXNf5bMshkzUBqB3xGy6IFofzueUU9pOQQC7OG9uWK0dBwBWrAsH2M48JQYeGwUDJmoD0BtiNockWnfjLiVILY0C2EGV5MrvawCY7L3EMtaFA+zDPKI2wydqA9A5MZt9qLIO1qJ1f3xoLjYBdrFI8t4YAGDUrAsHaOfe6iI2YDFsojYAnRGz2UbVvOoHP58ZS69dp3wT+NYogB3UKae0fegCAMNnXThAd2YpQVvUZuhEbQBaJ2bzlCqi9ZjcpQTtK6MAdjBrfn94HwCAYd0DLGNdOEAf768WSd4ZBQMnagPQGjF72qqI1lPyZ3OR6UMsYBeLWDsOAH1lXTjAsFTNPdZbo2DgRG0ADk7Mns4FchXRmrJacB4rBYHdnKac0j42CgDo9JreunCAcagiajMOojYAByNmj+8CuIpozfPuUp7R5OIS2MWs+f3xxigAoJVr92WsCwcYuzolBPocj6ETtQHYOzF7mGYpp+NOU4L16ucjo2ELn1NOafswDNjFRZI/jAEA9sq6cIBpqyNqMw6iNgB7I2b3m2hNGxeW57GaENjNaXNjemIUALA168IB+JnzJJfxiCeGT9QG4NXE7H4Qrenah+bCEmCX97DLeMYbADzHunAAdjFP+bxG1GboRG0AdiZmt0u0ps+uU77560M1YBfzlKjtPQ0ArAsHwP0WPEXUBmBrYvZhiNYM1V1K0F4aBbCDKslVrB0HYFqsCwegDbMkF83LZ4wMnagNwIuJ2a9Xp3x4Xz342eofhu7P5uYIYBeXSd4ZAwAjZF04AF0TtRkTURuAXxKzX66OaM203KSc0r41CmAH583NqA9XABgy68IB6KsqJQK+NQpGQNQG4KfE7B/VEa1h5S7lm74uJIFdVM3vjzOjAGAArAsHYKj3XYuI2oyDqA3AD6Ycs+uI1vBSn1KithWKwC4WSd4bAwA98i2b4XppJAAMXBVfJmZc12qLiNoAZBoxu45oDfu6iDyPEyrA7u/HV7F2HIBuXGd92tq6cADGfu+1iKjNOIjaAIwqZp+mhOrTBz+f+EcMe/d7kktjAHYwSwnaPlQB4JBW68KXWcdrAJiaOuXzG5+PMgaiNsCEDTFmi9bQvc9J5rF2HNjNRZI/jAGAPbAuHACeN0+JgDZVMpZrv0VEbYBJ6XPMFq2h3+5S1o4vjQLY8X3+Kj5QAWA71oUDwG7mEbUZD1EbYEL6ELNFaxi2D83FI8C2Zs2N5xujAOAJ1oUDwP4tUrZlHRkFIyBqA0xAmzFbtIbxukk5pX1rFMAOLpqbTx+mAEyXdeEA0J5Zcx8majOma8lFRG2AUTpEzK6aV511vBatYfzuUlZWXRkFsIPT5qbTNQPANFgXDgDdW0Xt90bBSIjaACP0mphdZTNaV0nOjBQm78/movG7UQBbmiW5TPLWKABGxbpwAOi3KuWzHPdijIWoDTAiL4nZVURrYDs3Kae0fVAJ7GKeErWtuwMYHuvCAWC4qojajO/adBFRG2DQHsbsKqI1sD93zcXipVEAO6hSHltg7ThAv1kXDgDjU6d8puOzYcZC1AYYsN/u7+/nSf5lFMCBfE45ZWntOLCLyyTvjAGgF6wLB4BpqSNqMy6iNsAA/XZ/f79I8t4ogANfKJ7HB57Abs6bG01rxwHavX6zLhwASErU/pjk2CgY0bXuIqI2wCD8dn9/Xyf5YhRACz40F4oA26qam0wnAgAOw7pwAOBX5imf64jajIWoDTAAv93f358m+csogJZcp5yytHYc2MUiNsoAvJZ14QDAa8xTHgllexZjIWoD9Nhv9/f3SXJvFECL7pobnyujAHZQN78/fHAC8GvWhQMAhzBLctG83JsxpmvnRURtgF5ZxezbWA8DtO/P5qYHYFuz5ubyjVEAbLAuHABo+95M1GZsRG2AHlnF7GU8gxLoxk3KKW3rLYFdXCT5wxiACV9HWRcOAPTBLGX1+FujYEREbYAeWMXsjy40gA7dpQQpF4bALk5T1o7bMgOM2Wpd+PLBnwAAfVOlxD+fNTO2a/FFfHYJ0IlVzF4keW8cQMc+pUTt70YBbMnacWBM7vJjuHZ9BAAMSdXco9kGypiI2gAdWMXs8yT/Ng6gJxeF57EmE9jNPGW1nWe1AUNyk81V4a6DAICxqFPin6jNmIjaAC1axew6yRfjAHrk95QgBbCt0+aG8sQogB6yLhwAmKI6ojbjvLZfRNQGOKhVzE6Se+MAeuY65ZS2tZrAtmYpX4jxnDagS9aFAwBsmqfEv2OjYEREbYADehizv8dKTqB/7lKC9tIogB2cNzeTrnGANlgXDgDwMvOI2oyPqA1wAA9j9jLWvAD99aG5GATYVpXkKtaOA/tlXTgAwOstklzEF5AZ373CIqI2wF48jNlXSd4YCdBjNymnLG+NAtjBZZJ3xgDswLpwAIDDmaUEbVGbsRG1AfbgYcxeJHlvJEDP3aWsoroyCmAH1o4DL2FdOABA+1ZR22fUjI2oDfAKD2P2PMm/jAQYiE/NDY5TUcC2ZilfiPF4FSCxLhwAoG+qlPD31igY4b3HIqI2wFYexuw6yRcjAQbkJuWLOE5LAbtYxDf+YWqsCwcAGI4qojbjJGoDbOFhzJ4l+Y+RAANz11z8XRoFsIM65ZS2teMwTtaFAwCM475tEdu1GB9RG+AFHsbsJLk3EmCgPqec0na6CtjWrLlxfGMUMGjWhQMAjFsdUZvx3sssImoDPOlxzP6a5MRYgAFf+M3jw2tgNxdJ/jAGGATrwgEApqtOiX7HRsHIiNoAT3gcs5fxzTZg+D40F34A2zpNWTvuQxHoF+vCAQB4bJ7y+Y/7N8ZG1AZ44HHMXiR5byzACFwnOY9TWsD2rB2HblkXDgDANuZJLpMcGQUjvDdaRNQGJu5xzLZeExiTu+aG5soogB3M4wMRaOO92rpwAABea5by2faFezhGSNQGJu1xzK6TfDEWYGT+bG5mALZ12twsnhgF7IV14QAAHJKozZiJ2sAkPY7ZVZL/MxZghG5STln60BzY1qy5WXxnFLAV68IBAOjyPu4yyVujYKT3WouI2sBEPI7ZSXJvLMBI3aV8M9eFHrCL8+b3h2/3w9PvsatgvWx+ti4cAICuVSnRT9RmjERtYBKeitm3SY6NBhixzymntH3IDmyrSnIVa8fhOus14cvmHgIAAPp8L3eZ5I1RMEKiNjBqT8XsZZIzowEmcJF3HmvHgd1cxtpxpvWeucxmvAYAgCGqU6Kfz78Z673bIqI2MDJPxWwfzgJT8nvzew9gW3XKKW1rxxkT68IBAJjK/dwiojbjJGoDo/JUzF4keW80wIRcp5zS9mE9sK1ZStD2AQhDfg+0LhwAgKmap3we7rGbjJGoDYzCUzG7TvLFaICJuUsJ2kujAHawiC8D0n/WhQMAwNPmEbUZ973gIqI2MFBiNsCmP5NcGAOwg7q5MfThB31gXTgAAGzvIiX6eZwUYyRqA4P0VMxOknujASbsJuWU9q1RAFuaNTeFb4yCllkXDgAA+7uvu2heojZjJGoDg/KzmP3dGzUwcXcpK6aujALYwUWSP4yBA7EuHAAADm8VtT1SijHfWy4iagM997OYvUxyZjwA+dTcuFjNCmzrNOULMdaO8xrWhQMAQLeqlOD31igYKVEb6LWfxeyP3pwB/usm5ZT2V6MAtjRLcum6ii1YFw4AAP1URdRm3ERtoJd+FrMXsT4F4LHfU6IUwLbmze8Pj3HhIevCAQBgeE6b+zubTRnzveoiojbQEz+L2edJ/m08AD/4nBKlrHgFtnXa3AieGMUkWRcOAADjUqcEP1GbsRK1gV74Wcyuk3wxHoCfXsjN4wQdsL1ZcyP4zihGz7pwAACYhjol9h0bBSMlagOd+lnMniX5j/EAPOtDcyEHsK3z5ibQ2vHx3NgvY104AABM2TzlcyJRmzHf+y4iagMt+1nMTpJ74wH4pevmZuXWKIAtVUmuYu340FgXDgAAPGceUZtxE7WBVj0Xs5fxvA+Al7hrblSujALYwWWsHe8z68IBAIBtzZJcNC8buRgrURtoxXMx+yrJGyMCeLE/mws4J/SAbdXNtZcPObq/EV/GunAAAGA/RG2mci+9iKgNHMhzMXuR5L0RAWzlJuWU9lejALY0SwnaNuO0w7pwAACgzfu9yyRvjYIRE7WBg3guZl8k+cOIALZ21/wOdeEG7GIRXyg8hNW68GXz562RAAAALauaez5RmzETtYG9ei5m10m+GBHAzj6nnNJ20g/Y1mnKKe1jo9jJTTZXhduWAQAA9EmVclLbYz4ZM1Eb2LowcQIAACAASURBVIvnYnaV5P+MCODVF23nEVKA7c2aGz4fbjzvLutgvfrTl4gAAIAhqFNin8dNMWaiNvAqz8XsJLk3IoC9+NBctAFsy6NfNlkXDgAAjE0dUZvxE7WBnfwqZn9NcmJMAHtxnXJK24lBYFunzc3e1K7LrAsHAACmZJ4S+zxyijETtYGt/CpmL+PbYAD7dJcStJdGAWxplvJMtbcj/v24jHXhAAAA84jajJ+oDbzIr2L2Isl7YwLYuz9TVgcDbGueErWPBv7vw7pwAACA512kfEZ/ZBSMmKgNPEvMBujOTcop7VujALY0tLXj1oUDAADsZpYStS8iajNuojbwpF/F7DrJF2MCOJi75mbERRqwi8sk73r4e20Z68IBAAD2aRW1HT5j7ERtYMOvYvZpkr+MCeDgPjU3JIIPsK3z5gavq2/oWxcOAADQniol9L01CkZO1AaS/DpmJ8m9MQG04iblWbjW7wLbqpJc5fBrx60LBwAA6M994CKiNuMnasPEvSRm3yY5NiqA1vyesjoYYFuL7G/lnHXhAAAA/Xea8jnSmVEwcqI2TNRLYvbSGyFA6z6nnNIWjoBt1SmntLddO25dOAAAwLDvBRfxWT7jJ2rDxLwkZn+MVSUAXbhLeRbu0iiALc1SgvbPPsSwLhwAAGCc6pST2idGwciJ2jARL4nZi+xvXSUA2/vQ/C4G2NYiyUWsCwcAAJiaeXNP6BGijJ2oDSP3kph9nuTfRgXQqevmJuTWKAAAAAB4oXlEbaZB1IaR+tsL/h4ndwC6d5ZymvLcKAAAAAB4oY9JTlM2/90ZByN2nORfKYeB5sYB4/GSk9lJcm9UAL3xZ8q3DH3ZCAAAAICXmqU8iuoiyZFxMHJOasNIvDRmf/fmBtArNynfMPxqFAAAAABsYZYS+d4ZBRMgasPA/e2Ff59YAtAvJ0mWKd+kBQAAAICX+p7ymdLfk3wyDkbO+nEYuJfGbKtsAfrnKMkfSa5SvlELAAAAAC91mxL3/p7ks3EwcqI2DJST2QDD96b5PX1qFAAAAABs6TbJeZJ/JLk2DkZO1IaBeWnMvjUqgN5fhP2V8vwXAAAAANjWMkkdUZtpELVhIMRsgHF539x4WDsOAAAAwC6WKVH7f5N8Mw5GTtSGnrNmHGB8zrJeDwUAAAAAu7hKUiX5Z0Rtxk/Uhp56acz+blQAg3KU5N9JLo0CAAAAgFf4mBK1f09yZxyMnKgNPfPb/f39S//er0lOjAxgcG5STmnfGgUAAAAArzBLctG8joyDCfiWZJHypQ6gA3/b4u91OhtgmE5SvpA0NwoAAAAAXuF7StirknyIk9qMn5Pa0LFtYvbSuAAG66i56PqY8g1aAAAAANjVKmqfJvlkHEyAqA0dcTIbYFreppzSPjUKAAAAAF7pNiXs/T2iNtMgakPLtonZX40LYDQXXH+lPNsIAAAAAF7rNiXs/b8k18bBBIja0JJtYvatcQGMyh9JrmLtOAAAAAD78TVJneQfEbWZBlEbDuy3+/v7bf7+eyMDGJ27JOdJlkYBAAAAwB7VSS6TnBgFE/Et5XnyH40C9uNvO/yXEIBxOUrypbnIAgAAAIB9WSY5TfLP6AtMg5PasGfbxuxbIwMYrfcpq6AqowAAAABgjz6mfOYkajMVojbsybYx+6uRAYzaSfO7/twoAAAAANizjykntT+kPPoOxk7UhlfaNmZ/NzKA0TtK8u/m5mJmHAAAAADs0feUx91VEbWZDlEbdrRtzF4aGcBkvM36uUYAAAAAsE8Po/afxsFEiNqwpb8ZAQDPOEkJ2hdGAQAAAMABfE/57OnvST4ZBxMhasML/XZ/f7/tv+be2AAm6XNzYeWREwAAAAAcSpXkMskbo2BCvqVsKvhoFLBpl5PZnl8BME1vknxNUhsFAAAAAAdym+Q8yT+SXBsHE+GkNvzELjH7q7EBTPqi6kvKtwQBAAAA4FCWKYcqRG2mRNSGR3aJ2bfGBjB575sbiplRAAAAAHBAy5So/b8pq5hhCkRtaIjZAOzqLOu1TwAAAABwSFcpz9P+Z0RtpkPUZvLEbABe4yjJv5NcGgUAAAAALfiYddS+Mw4mQtRmssRsAPbhXZKvSU6NAgAAAIAWfEyJ2h8iajMdojaT89v9/f22/5pZkv8YHQBPuEty0dxMAAAAAEAbZimfSV2kbBKEqfiWZBGfxzJiu8TsJLk3OgCe8am5efhuFAAAAAC0pEoJe2+NgokRtRmtv+34r7s2OgCe8TbWjgMAAADQrtuU1ct/TzlsAVNh/TijtWvMdtIOgJdcQP2VckIbAAAAANpym3XUdjiPKRG1GZ1dY/ZXowPghf5Iskx5dhEAAAAAtOU2SZ3kHxG1mRZRm9FwMhuANpw9uHkAAAAAgDYts47aN8bBhIjaDJ6T2QC05SjJlySXRgEAAABAB5ZJTpP8M8k342BCRG0Ga9eYfWt0AOzoXcqXoiqjAAAAAKADH1M+mxK1mRpRm8ERswHowklK0D43CgAAYGKqlA+PL5v7ovvm55nRALTuY/N7+UOSO+NgQkRtBuO3+/v7Xf+1X1NiBAC8xqckF0m+GwUAADBCdfM6bf48+snfd5dkEY9mAujKLOUzqotnflfDWH1rrkM+GgV985qYvUxyZoQA7MFNyjcAvxoFAAAwYFU2w/UuB0G+pYSUK+ME6MQsJeq9MwomSNSmd14Tsy/9Mgdgz36PUwgAAMBw1HnZqetdXKd8mLw0ZoBOVM3v4bdGwQSJ2vTGa2L2Isl7IwRgzz6nnNK2dhwAAOiTKq8/db2LTymfw936RwDQ2e//RURtpknUpnOvidl1ki9GCMCBLpLOY+04AADQnTqHO3W9rbuULVaX8cVfgC7fFxbx+FWmSdSmM6+J2adJ/jJCAPZ4QbRMCdirPwEAANpQpZtT19u6S3me9kf/yAA6U0fUZrpEbVr3mpidJPdGCMAO7rKO1svmZ6cLAACAttTpz6nrXXxLeTzT0j9KgM6cp2zMODYKJkjUpjWvjdm3flED8AI3WUfr1QsAAKANVYZx6noX1ylR+9Y/ZoDOzFOinlbCFInaHNxrY/YyVmkA8OMFzCpYL+OkAAAA0K46wz51vYtPKevHbbwC6M485aT2kVEwQaI2B/PamP0xyVtjBJi062w+5/rWSAAAgJZUGe+p623dpUSUy4jaAF2ZpXy56CKiNtMkarN3r43ZiyTvjRFgUhcjy2zGawAAgLbUmd6p613u2xbxITJAl0RtXI+4HmFPXhuzz5P82xgBRukum6vCv8a3+wEAgPZUWUfr03jU3bauUz5EXhoFQKfvZYvYcMt0idq82mtjdp3kizECjMJN1tF69QIAAGhLnc14fWwke/E55WTgrVEAdKaKqM20idrs7LUxO0nujRFgcO6yuS58aSQAAECLqjh13bY/Uz5EtnELoNv3v4/e95gwUZutidkA03Cdzedc3xoJAADQojpOXffBXZLLlA+RAej2fXERUZvpErV5sX3E7KVfuAC9uxBYZr0qfGkkAABAi6o4dT2E+8aLJFdGAdCpOuVLRidGwYSvSRYRtXnGPmL2VZI3RgnQibtsnrhexso4AACgXXWcuh6q65QPkJdGAdCpefP72HsoUyVq81P7iNmLJO+NEqAVN9mM11+NBAAAaFEVp67H6FPKZ3y3RgHQqXlEbaZN1OYH+4jZ8yT/MkqAvbvL5onrpZEAAAAtq+PU9ZR8SFl3a+MXQLcWKY+DODIKJkrU5r/2EbPrJF+MEuDVrrN56vrWSAAAgBZVceqa8sXqi/jwGKBrs+b3sajNlIna7CVmz5L8xygBtn4TXma9KnxpJAAAQMvqOHXN8/etc/erAJ1bRW2Pe2Xq1yWLiNqTtI+YnST3RgnwU3fZPHG9jJVtAABAu6o4dc1urlMiylejAOj8vXyR5K1RMGGi9gTtK2Z/TXJinABJkptsxms3/AAAQNvqOHXNfn1Kidq+nA3QrSqiNojaE7KvmL2Mb/QC03SXzRPXSyMBAABaVsWpa9q7B75sXqI2QLfqlJjnfZ8pE7UnYF8xexHPawCm4Tqbz7m+NRIAAKBldZy6pls+OAbo13XBIqI2rk1cm4zUvmL2RZI/jBMY4Rvg42ddAwAAtKmKU9f0103K54LulwG6V6eEPF9yY8pE7RHaV8yuk3wxTmDgrrMZrq1MAwAA2lbHqWuG53NK1L41CoDOzVNinmsIpkzUHpF9xezTJH8ZJzAgN9k8df3VSAAAgJZVceqacfkz5YNjXw4H6N48yWWSI6NgwkTtEdhXzE6Se+MEeuoumyeuv7qxBgAAOlDHqWumcQ9+mfLBMQDdmqVszriIqM20fWv+e3BlFMOzz5h96yYM6InrrE9bL2PNGQAA0L4qTl0zbT40BugPUZupWj1adPVigPYZs5duzICObo4fnrj2hgQAAHShjlPX8JTrlFPa7tcBujdL2Z7x1igYqZusw7Uv1I3EPmP2ZZJ3Rgq0cBO8zDpcWxcOAAC0rYpT17CtTylR+9YoAHpxLbOIqM3wPYzXy+gFo7TPmL1I8t5IgT2/ET08df3VSAAAgA7Uceoa9uVDyqEYHzYDdK9K8jG+mMdwfMvmyWvXExOwz5hdJ/lipMCO7rIO18vmZ29EAABA26o4dQ1tfAawSInaAHSvbn4vu+6hbx7G62VseJkkMRvoymr9x1dvQgAAQIfqOHUNXfmWZB7P0wbo03XRIqI23bnL+tT1MroB2W/MTpJ7IwV+cnP6cF24m1QAAKALVZy6hj66TnIRjxcD6It5StT2JT8ObRWvVy/XAvxg3zH7e5IjYwU3odl8zvWtkQAAAB14GK7r+EAW+u5TSjy5NQqAXphH1Gb/Pke8Zgv7jtnL+FYzTM1N1tHamw8AANCVWTbDtc8nYJjuUp6lfZlycAaA7i1SNmg4zMguVoffVi/Yyr5j9sckb40VRn1D+TWb35pyYwkAAHTBqWsYt28p8eSjUQD0wiwlaIva/Ip4zV7tO2Yvkrw3VhiNm2w+5/rWSAAAgA44dQ3TdZMSTpZGAdCb67KLaEFsvlcvH7wcgGOv9h2z50n+ZawwWKtnVXx1kwgAAHTIqWvgseuUzx5vjQKgF6qUA4629U6PeE2r9h2z6yRfjBUGdSP48E0HAACgbU5dA9v4MyWe+OAcoB+qiNpj9y3rhnDlPZi27Ttmz5L8x1iht24evekAAAC0zalr4LXuklymxBMA+qFufi/7YuLwPYzXy9iKQsf2HbOT5N5YoXdvOlex7gMAAGifU9fAIX1LCScfjQKgN+qI2kNzl81DcLdGQp8cImYv/ZKCTt90ruIbUwAAQDecuga6cJ0STpZGAdAbdcqXjVwP9s/DeL1M8tVI6LNDxOyrJG+MFrzpAAAAo+bUNdA3n1Ki9q1RAPTGvPndLGp36zrrg3A6AoNyiJi9SPLeaOGgbzrL5o3Hmw4AANAWp66BofiQ8kxtj1sD6I9587v5yChaseoIqxcM1iFi9kWSP4wW9uYmm8+9BgAAODSnroGhu0s5dHNpFAC9usa8aF6i9n7dZPMRpDAah4jZdZIvRguvetNZPnj5FjEAAHBoTl0DY/UtJZpcGQVAb4jar6cjMBmHiNlVkv8zWtjqpurhm86tkQAAAAfk1DUwRdcp0cQj2wD6dV16meStUfySeM1kHSJmJ8m90cJP3T14w7mKeA0AAByWU9cAa59S1o/fGgVAb1TN72ZRe80hOGgcKmZ/TXJivPBf11k/r8I3gAEAgENx6hrg1+5STgJexsk2gD6pmt/Nbyb47128hp84VMxeumFm4q4fvfEAAAAcglPXALu7S1k9/tEoAHqlTjmpPebOZIMrvNChYvZlknfGy4R4XgUAAHBoTl0DHMZNStReGgVAr9QZT9R+GK+XscEVXux/DvS/V8hj7B6u/Ljyn3kAAOAAnLoGaMdJki8pm/bmcToOoC+WzXXwPCVqD+16eLXB9SriNezsUCez6+YCEMbi7sGbztJNDQAAsGdOXQP0x6eUk9oOLwD0yzz9jtoePwoHcKiYfZrkL+NlwKz8AAAADsmpa4B+u0t5lOLCKAB656L5/XzU8f8fq8ePrg7BAQdwqJidJPfGy8D41hQAAHAITl0DDNe3/8/e3V61kaRtAL6HM/9hI0BvBDAR0BOB2QiQI7AnAuMIzESAHIFxBBYRGCIYEcFABLw/qlksA0aCltQf13WOz3jXNh+3RHdVP1VPpRRMJqIAaN0Y+339a11F7bvi9d0vHTxgDVZZzJ7FynLa7ccbz5k4AACAhth1DdA/5ylF7akoAFrlrqj9YQUf+yr3u66nUbyGjVhlMXsaq81pFzceAACgaXZdAwzL15SiyUwUAK0ySll0dPSKj3GV+Z3XrvXQAqssZk9eedGA13LjAQAAmmbXNQBJ8jHlTG2bJQDaZZTFi9pqCNABqyxmH2c1bR3gKTc/3XguRAIAALzCTu6L1lXsugZg3k3KM9ATUQC0zn59fT746bo9jRoCdMoqi9mHSb6ImBU7z/2Z1248AADAa+xnfuf1nkgAWMBVSuvxM1EAtM7d2H4aNQTopFUWs6sk30RMwy4zf+41AADAS/y863o/ybZYAHiF85SitmIJAEBDVlnMTpJbEfNKl5lv++EcIgAA4CXsugZgXT6ntB+fiQIA4HUUs2mbq8wXrw36AQCAZdl1DcCm3aSc1XoSmzMAAF5s1cXsaZIDMbOAy5Rz1meiAAAAlmTXNQBtdZPSenwiCgCA5a26mH2W5I2YWcBlykMnAACAX7HrGoAuukoyTtn8AwDAglZdzD5O8kHMLPp+FAEAAPATu64B6JPzlKL2TBQAAM/7fcUf36AMAACARdl1DUDfHST5J8nnlPbjztMGAPiFVe/MrpJ8EzML+o8BPAAADIpd1wAM2U2Sk/qXZ2IAAI9YdTF7J8m/YmZBf8a5QQAA0Fd2XQPA465SjmuciAIAYN6qi9lJcitmFqSYDQAA/WHXNQAs5zylqD0VBQBA8fsaPsdlPLRgMSMRAABAJ9l1DQCvd5ByZOPXlPO0ZyIBAIZuHcVs572wqJEIAACgE+y6BoDVeVP/+jtlp7bnqwDAYK2jmD1NWVUIAABA99h1DQCb8S7JOKWgfSIOAGCI7MymTfZFAAAArRiX23UNAO2wneRTStvx90nORAIADMk6itkXYmZBOyIAAIC1j8HtugaA9ttN8iXJecpO7alIAIAhsDMbAABgOOy6BoBuO0jyLcnnlKL2TCQAQJ/9dnt7u47PcytqFn1PigAAABph1zUA9NtNylnaJ7GhCADoqXUVs2cprXDg2fekCAAA4EXsugaAYbpJOU97IgoAoG/WVcyeprTAgWffkyIAAIBn2XUNAPzsKsk4ztMGAHrk9zV9nosoZrOYyoAbAAAesOsaAHjObsp52ucpRe2ZSACArltXMduZLQAAAIux6xoAeI2DJP8k+ZzSftyzWQCgs9bVZrxKWRUIz/lvkjMxAAAwIHZdAwCrcpPkpP6lqA0AdM7vIqBl9qOYDQBAf9l1DQCs03aSDyltx4+TTEQCAHTJuorZU1EDAAADNMp84dquawBgE3aTnKa0HX8fz2sBgI5Y587sm9hxwPNGIgAAoMOq3BeuK3MgAKBl9lKOg/yaUtSeiQQAaLN1nZmdlNV+ByLnGecpD/0AAKDtRpkvXNt1DQB0zd8p7cedpw0AtNI6d2bPopgNAAB0VxW7rgGAfnmXcp72SUpRGwCgVdZdzIbnjEQAAEBLxqVV7LoGAPpvO8mHlKL2+yRnIgEA2kIxm7bZFQEAABtQxa5rAGDYdpN8STkG8Djl2EgAgI1a55nZVZJvImeR96UIAABYoVHsugYAeM7nlKL2TBQAwKass5i9k+RfkbOAP5JciAEAgIZUsesaAOClPqacqX0tCgBg3dZZzE6SW5GzgD+jjREAAC8zil3XAABNu0k5T3siCgBgndZdzJ4mORA7z1DMBgBgUftJDmPXNQDAOlwlGcezOwBgTbZEQAtVIgAAYEGjlF1Cb6KQDQCwartJvqUUs/fFAQCs2rqL2VORAwAADTpLeZB6KQoAgLU5SPI9pe34jjgAgFVZdzH7WuQAAEDDZikF7b9FAQCwVkf1WOw4itoAwAqsu5h9IXIWUIkAAIAXeJ/kv0luRAEAsDbbST6kPPsdiwMAaNK6i9kzkQMAACuk7TgAwGbsJjlNKWpX4gAAmqCYTRtpSQQAwGvnHdqOAwBsxl6Sb0mmSUbiAABeY2sDn9MOCRYZ8AIAwGtpOw4AsDkHSf5JchKbVwCAF9pEMfta7AAAwJpoOw4AsFnvUjrnHIsCAFjWJorZF2JnASMRAADQkFm0HQcA2KTtJB/qcdlYHADAouzMpq1GIgAAoGHajgMAbNZuktOU87QrcQAAz9lEMXsqdgAAYEO0HQcA2LyDJN+STGJTCwDwC3Zm01YGsQAArMos2o4DALTBUZJ/Us7T3hEHAPAzZ2bTViMRAACwYtqOAwC0w9152u9FAQD8aGtDn9fDIgAAoA20HQcAaIftJJ9SitqVOACAZHPFbLuzec6+CAAAWJNZtB0HAGiL3ZTztKfxjBAABm9TxeyZ6HmGM3IAAFg3bccBANrjIMn3JJM4khAABksxGwAA4J624wAA7XKU0unzODbAAMDgaDNOWx2IAACADZlF23EAgDbZTvIh5bnyWBwAMBybKmZfix4AAGg5bccBANplN8lpSlG7EgcA9N9vt7e3m/rct+LnGf+JhQ8AAGzeKKX9+J4oAABa5Txlp/ZMFADQT1sioMX2RQAAQAvMou04AEAbHST5J8lJnKcNAL20yWL2ufgBAIAO0XYcAKCd3qUsQDwWBQD0yyaL2dpH8xyrKQEAaJuzlF3al6IAAGiV7SQfUoraY3EAQD9ssph9IX6eoc04AABtNIu24wAAbbWb5DTJNEklDgDotk0Ws2fiBwAAOkzbcQCA9jpI8i2ls85IHADQTYrZtJlBJgAAbaftOABAu71J8k/KedqONQSAjlHMps1GIgAAoANm0XYcAKDt7s7Tfi8KAOgOxWwAAIBmaDsOANBu20k+pTybPhQHALTf1oY/v1Z8/Mq+CAAA6BhtxwEA2m83yZck03gGCQCttuli9rWXgF/YFgEAAB00i7bjAABdcJDke5JJHHkIAK206WL21EsAAAD0lLbjAADdcJTkIslxkh1xAEB72JlN22nzAwBAl2k7DgDQDdtJPqR02RmLAwDaYdPF7AsvAc+wEhIAgK6bRdtxAICu2E5ymvLsuhIHAGyWndkAAADroe04AEB37CX5lnJU5kgcALAZdmbTdpUIAADokbOUh6HnogAA6ISDJP8kmUQXSQBYu60WfA1XXgYAAGBArlMWbX4UBQBAZxylHB9zLAoAWJ82FLNnXgZ+wWpHAAD66jjJn9F2HACgK7aTfEh5pj0WBwCsXhuK2VqN8yv7IgCgxXaSHKYUpKbxMANY3jTajgMAdM1uktN6LFeJAwBW5/cWfA3XXgYAoCOqlIVWd//d/enPD1KK22NjHGDJOVGVsjDmgzgAADrjIMm3JF+TvI8upADQuN9ub283/TUcJvnipeAJl7E7G4DNGOW+aL2f8pBiUVf1GEcHGmBZVZKzlBaWAAB0y98pCxQtbgaAhrShmF2lrF6DJ9+nIgBgxXZyv+O6qn/fRCHpryQn4gVecE06y3KLaAAAaIeblIK2uSAANKANxewkufVS8Kv3qQgAaNiPrcL3k+yt8HN9jbbjwMscR9txAICuukppPX4mCgB4ubYUs6+jjR5P+784bwaAlxtlvni9iZ2ONyltx6deDmBJVbQdBwDosvOURYrmgwDwAm0pZk+jhR5P+9NgD4AlVJnfdb3boq/tY8pDDIBlaDsOANB9n+v54EwUALC4thSzJ0mOvBw8QTEbgKfs//CrymrbhTflPGWXtrbjwLKOo+04AECX3aScpX1iTggAi2lLMfs4HsrwtL/qAR4Aw7aT+x3Xd//tatvdm5RztJ2dBiyrirbjAABdd5NynvZEFADwa1st+TpmXgp+YUcEAINU/TC5nyX5N8mXlAVwB+l2IWe7/l4s1gKWNU0ySunyAABAd+eEp/VctxIHADzt95Z8HTMvBQAM2ijz51wP5VzYd/X3fWg8BCzhur52HEeHKwCALttN8i1loeLYvBAAHmpLm/GdlN1W8JivKQ/5AeiHncy3Cq+iXa4Wc8BLVdF2HACgLz7Xc0PnaQNArS3F7CS59XLwhPNotwPQZT8WrveT7InkSR5cAC+xk1LQPhAFAEDn3aQcSXVibggA7SpmT+PhC49TzAbojlHui9aVe/uLXKa0l7sQBbCk42g7DgDQF1f1+G4iCgCGTDGbzrxXRQDQSlXmd13viqQRNykPLU5EAbzguqztOABAf5zX88OpKAAYojYVs49jFwG/eK+KAGDj9jO/61q78NX7mrJLW2s5YBnajgMA9HN++D7JTBQADEmbitnvk3zykvCE/8SDfIB12sl90bqqf2+X32ZcJTmMtuPA8o5jwTAAQN/8XY/zPCsFYBDaVMyuknzzkvCEP6OVDsCq78M/7rrWLrx9/oq248DLru/ajgMA9IujqQAYjDYVs0dJ/vGS8ATFbIBm77l3Rev9aEPbJecpu7StwAeWoe04AEA/XaV0PD0TBQB91aZidpLcekl4wtskEzEALO3HduF3/7U7r9tuUgraU1EASzqOtuMAAH10Xo/1zBMB6J22FbMvkux5WXjEx3pABsCv/dgqfN991b0R4CdVtB0HAOirz/U8cSYKAPqibcXsabS+43Ee2AM8NMp88do9dHjOk4zjQQWwHG3HAQD67WPKedqOqAKg87Za9vVceEl4wkgEAKlyfxbWLMk/Sb6ktIxVkBimg3r8dCgKYAnX9T3loygAAHrpQ8pzg7EoAOi6tu3MPo4ztCiaogAAIABJREFU3HjcecoDN4ChGGX+nGvtwnnO3ymLHQCWUUXbcQCAPrtKKWpPRQFAF7WtmF0l+eZl4RGK2UCf7eS+aF3Vv1dU4CUuU3Zpz0QBLHkf0nYcAKDfzlMWQOuOCkCntK2YvZ/ku5eFR9ykPGQD6IO7wvXdf3dFQsP3zPdJJqIAlnQcnbIAAPrucz1ndJ42AJ3QtmJ2ktx6WXjq/SoCoINGmS9e2/XGunhAAbxEFW3HAQD67ibJSf3LnBGAVmtjMfs6HpzwxPtVBEAHVJnfde2exiZdppyNpo0csAxtxwEAhuEqpTvPRBQAtFUbi9nTeGjC4/6s3x8AbbGf+V3XeyKhhW5SHk6ciAJY0nG0HQcAGILLlM5eU1EA0DZtLGZPkhx5aXiEYjawSTuZ33Ft4RVd8zVll7YWcsAyqmg7DgAwpHnj+yQzUQDQFlst/JrcKAFog6qewJ3V96Z/k3xJ2aGmkE0XvUlpN74vCmAJ0ySjJOeiAAAYxLzxn5TOXjviAKAN2ljMdqYjT6lEAKzIKGXH6kl9H7pN8i3Jp3oitysiemI3yfeUhRoAi7qux+IfRQEAMAjvUhb2H4sCgE1rY5vxKqWAAD/7aAAFNGAn963Cq/r3WqcyROdJDqPtOLD8fE3bcQCA4bjKfec6AFi7Nhazk7IjDn72d+wkA5Z3V7jer3/tiQT+5yaloD0VBbCEnZSHmY7dAAAYjvOUjUbmjwCs075iNl0bMFViAH5hlPnitYfssBjdT4CXOE7yQQwAAIPyuR4HzkQBwAqMct9V9TDJrK3F7GkUIHhIMRv42U5Kx4a7XdfOtobX3WfH8UACWE4VbccBAIboY5KTOLoKgNfZyXzx+udn/OdbLf3C3QB5zEgEwCP3i1GSN1HIhtc6SHJRDxoBFjWt78XnogAAGJQPKYuhHQsJwLKqlC4fF0n+TfIlybs8/ox/2tZi9oXXkUcoVAGPGSd5KwZoxHY9eDwRBbCE63oi+lEUAACDm0N+SilqV+IA4An7KYufzlKOmv6Wsihqb5F/3NY24+Mkp15bHnvPigD4xb3jJNqcQlMuU59LIwpgCVW0HQcAGKrzlGKFzWoAwzbKfOvw1zwj+LOtxewqpSoPP/u/eKgOPG0/pd2pB+jQjJuUBxETUQBL2EkpaB+IAgBgkD6ntI+diQJgMM8Bqjx97vVr/NHWYvYoyT9eex7xZ0qhCuAp+ykP0B1NAM35nFLUvhYFsITjlLZhAAAMz01KB70Tc0mAXqpyX7zeW+Hn+a2txeyk9EyHnylmA4vYqa8Ve6KAxlymtPPXLg5YdnKr7TgAwHBdpSxynIgCoNP2c1/AfrOmz3mTZGerxaFcel/wxA8LwHOu65vqV1FAY/ZSFom8FwWwhGlK561zUQAADNJuktOUhdGVOAA6Y5SysWWS8rz9e5JPWV8hO/W9I20uZms9wmN2RAAscR85TGmPDDRjux60nrknA0vek6skH0UBADBYe0m+5X6xIwDtspPyPP0kySzlOOjTJEfZXLe1WdLuYvbU+waABoyT/CUGaNSblJWROqYAyzhOOTboShQAAIN1kFIgOYlF0gCbVtVz9WmSf5N8SfIupatGG8wSO7Pp5g8WwLJOkrwVAzRqN6W9kLbjwDKmKQthHAUCADBs71KKFMeiAFib/ZRneWcpddhvST6kLDRqo9a3Gb/wngKgQZMkfyS5EQU06lNKccqKemBRd0eB6JwCADBs2ylFlFlKZz0AmjXK/bnXs8yfe73dga//Okl+u729besXuF+HCj+6jJamwOvvL9OO3KyhS25SilNTUQBL3pfP0p4WZgAAbM557tvdArC8nZQOx3e/9jr+/fwnyXWbi9lJcut9xyN+EwHQwE192oObObTRx2gTByx/X56krAwHAIDP9bxyJgqAZ1U//Dro2ff2W9Lundmpb1ZW6PPomxfglXZSdoIdiAIad57SwmgmCmAJ71PanQEAQFIWS5+kbjMLQJLS4az64VdfO5Ce199f64vZ0ygy8NB/DGCABk2SHIkBGneTUtA+EwWw5KRc23EAAH6cWx6nFLUBhmiU+eL1UObL/ytmb7X8C73wHuURzswGmjROWekLNGs7yZd44AAsPwfcT/JVFAAA1HPLTymdvypxAAOwk+Qw5ZnaRZJ/kpymbMga0sLv6d1v2l7MtvsWgHU4TvJWDLAS7+qB90gUwBLzwMMkf4kCAIDabpJvKcUNm52AvqlSnlFPk/ybskHkXZK9gT8bSGJnNt00EgGwApMkf6a0rwKatVeP68aiAJZwkuSPJFeiAACgdpDke8pznJE4gI7aT/I+5Zit65TFOh/i6OUf/a9GbGc2XWSQAqzKNGUVnII2NG87pSXSJKVdEsCik1dtxwEA+NlRPVY8NscEOmAnZZPHJOXYhO8pRyi8SXlmxkOzu9/8dnt72/Yv9tbrxU8+1oMUgFUOLqYZdhsXWKXLegCvCw+wjPf1ZB8AAH50U48VJ6IAWuQwZeNUFc+ZX+K3//2mA8Xs61iVwLyv9UUAYJUUtGH1/kppIwywqP2UNmy7ogAA4CeXKUXtqSiADc1X7wrY2oW/zlV+6NK81YEv2I4dfqZtDLAO1/UA5LMoYGU+pRSl3NuBZeaH2o4DAPCYvZRzZ6dxVCWweqPMn3v9Pc69bsrsx//RhWK2c7MB2KRxkr/FACvzJvfFKYBF54iHKd0dAADgZwdJ/klpO27xNNCUn8+9/ifOvV6VuY3OdmbTRR52A+v2PslbMcDK7KasXj0WBbCEkyR/pLQfAwCAnx2lFJzMNYGXOqznnhdJ/k1yWl9bHH21WnMbnbtwZva4fnPA3HtXBMCGBi+TWGkHq3Re/6zpzgMsaqe+P78RBQAAT7hKKWpPRAH8gnOv2+G/Ke3bk3SjmF2lnHMBP1LMBjY5oJlGQRtW6aaeOExFASzhfUqLNwAAeMp5SlHbfBNIyrnXd8XrKp75tsWfP16nu1DM3knZug9PvpEBNjDIOUuyJwpYqY/RDg5Yzn59j9byDQCAX/mashhyJgoYlJ3MF6/NHdtpbkNrF4rZSXLrdeMnitlAGwY+0yhow6pd1pOMmSiAJe7Rk2g7DgDA8z6mnIfrqCvorx+L157ltt9NPa//n62OfOHnXjt+siMCYMOu6wHQZ1HASu0luagnHgCL3qMPk/wlCgAAnvEhZfH0e1FAb+zXP9PTlM2yX5K8i0J2V1z8/H9syYQOX4wANu06yTgK2rBq2/XE40QUwBJOkvyR5EoUAAA8M+f8lFLUtpAaumeU8oz2LOV57ff6Z/pANJ30oFNGV4rZU68dAC02TvJWDLBy71JWZ1rUBizq7prxVRQAADxjN2Uh9dS8E1rt7tzrScoilH+SnKYcNbUtnl7M4+d0pZjtvAoeu1gBtMkkpaB9IwpYqb2UBwtjUQBLzCe1HQcAYFEHKTs7Jyk7PoHNq1K6b10k+Tdl4clRyiIU+mX28//x2+3tbVfepN+8fvzgvH5fALTNfkqhzSpAWL3PKWcgWfgILHOfPosHHgAALOamHkPORAFrn7tVKQuTtQsflj/zU8furhSzRyltAuCOYjbQ9sHWJGUHKbBalym7tC9EASxop75PvxEFAAAL+E0EsHKj3Bevq9goNGT/yU8bV7pSzE6SW68fP7iKFi9Au+2krCBT0Ib1+Cul3RTAot4n+SQGAACeoZgNzdvJfPFa9yyevOZ2qZg982bGIALo4KDsJOX8FmD1vqbs0tZ2HFiUtuMAAPzKZT1mBF6vyn3x2gYgFr7mbnXoG5h5DQHomOuUwtpnUcBavElpN+5BA7Cou2vGV1EAAPAIi6Xh5fZTOmJNU7ovf0vyLgrZLHnN7VIx2zmIPHYhBOiCcUoLZGD1dpN8T3IsCmCJyfKhezUAAE+MFYHFjFKeg57VPzvfU452OhANC5o+9n/+7qZBh+2IAOiQk/pedioKWIsPuW9fZRwJLHqvnkbbcQAA7tlkB09z7jVr0aWd2VMvFwAdN0nyR5IbUcBaHKQcVVOJAliQtuMAAACLOUvyJclRFLJpxvSx/7NLxWw7aviZNuNAF12kFNauRAFrsZ1yJtOxKIAl5p7ajgMAkNiZDb8yEgErmI8/4MxsukybcaDLE6H9JJeigLX5UP/smWgBizpJ6ahiARoAwHDZZAdPsxubpj1aC97q2DehLSsAfZoMVdHGFNZprx4UH4oCWGIire04AMBwKWbD42w2pGlPLiTvWjHb7mx+VIkA6MGE6DDJZ1HA2mynnOd0Igpgyfu1tuMAAMOjJgGPcwwsTZs99QdbfflGAKDDxkk+igHW6l3ud1wCLELbcQAAAFiN2VN/oJhNl2ljAfTJcZK3YoC12ksyTVlQArAIbccBAIbjUgTwpEoENGz21B9oM06X7YkA6JlJkj+T3IgC1mY7yWn982ehHLAIbccBAIYz7gNgPZ6sAXetmO3mAUDfTVNWNipow3od1T9/2o4Di9J2HACg39Qj4GmVCFjXNdfObLpuJAKghy7q65t2VrBee0m+J3kvCmCJe7a24wAA/R3rAbDha66d2XTdSARAT12nrHA8FwWs3ackZ9F2HFj8nq3tOAAAMCQ627GKufWjtjr4zXioD8CQbuBVks+igLV7k/sdlwCL0HYcAKBf7MyGp22LgAb9svbbxWK23dn8aCQCYADGST6KAdZuN6Xt+LEogAVpOw4A0B9qEfA4C/9Z6/W2i8Vsq6H40UgEwEAcJ3krBtiID0mm0XYcWHwSru04AEA/xnXAQ56P0LRf1n67WMyeeU0BGKhJkv8muREFrN1BPQ6tRAEsSNtxAIBus7EOHjcSAQ3r3c7smdeUH2hnAQzNWUoxTUEb1m87ybdoOw4sTttxAACgb0YiYAVz5ycpZtN12lkAQ7257ye5FAVsxIf659DkDVjEj23HLUYDAOgGz1zgaSMR0LDZr/5QMRsAunuDr0yuYGP2Ugrah6IAFnTi3g0A0BnOy4anjURAw2a/+sOtjn5TJv/cORABMPCJ1X6Sz6KAjdhO8iWlQAWwiIuUgrZ7NwBAuylmw9N0zKVJV8/9ha4Ws91IAODeOMnfYoCNeZf79v8Ai8xnx0neRttxAIC2uhABPGlPBDRo9txf6Goxe+q1BYA571MeigObm8hNUwpUAIuYRNtxAAAAhu3ZxUNbMqIHKhEAJCkPxe3ygs3ZTnJa/yxquQUsOmmvou04AEAbx2nAQ5UIaNiz3bjtzAaAfpnUg0oFbdico3q8qu04sOjEfRwL0gAA2jZGA2D1ps/9BWdm0wd2PgHMu9vlpW0pbM5eku8pRwAALGLi/g0A0BpqEPC4SgSsW1eL2Vp88CO7ngAev1dW8UAcNu1TkrNYfAcsd//WdhwAYPPjMgBWb/rcX+jymdlXXl8A+KXreCAObfAm5UGIBXjAovfvcbQdBwAA2sezDZq00Jy3y8XsmdeY2kgEAE+6eyCuoA2btZvSdvxYFMCCJtFlBQBgE4y/4Gk6z9GkhbpgbPX9G2QQRiIAeNY4ZYcXsFkfUtonmfwBi857q1iUBgCwTs7LhqfZmc3ar7dbff8GAYD/mUTLUmiDg5QuQ5UogAXnvmP3cACAtY6/gMdti4AG2ZnNYIxEALCwSUoBzcNw2Pzk71uSE1EAS97Dtb0EAFgttQd43EgENGy2yF+yM5s+2BUBwNKTsirJlShg497VP5MmhMAy93BtxwEAgHUbiYCGzRb5S10uZk+9xgDwYhcpZ9zY3QWbt1f/TB6KAliAtuMAAKtlZzY8biQCNnG93er4N2nizp19EQAs7Tpld9dXUcDGbSf5ktJ2fEccwAIm0XYcAGAVdIWFx41EwCaut10vZlshxR0PfQFePmA4jHal0BbvUjoQWagHLDonrtzHAQAapZgNj1OHoUkLL8zuejHbTQUAmjFO8pcYoBX2UgraY1EAC86Lx9F2HACgKTbRweMsvKfpuexC7MymLyoRALzaScqDcGDztpOcprQRtvIZWMQk2o4DAADQDdNF/2LXi9kzrzUANGqS5I/Y2QVtcZSygNPqZ2AR2o4DALyOhYHwtAMR0KDB7Myeea0BoHF3D8IVtKEddpN8T/JeFMCCDwTG0XYcAOClYykAVm/h7tvajNMXlQgAGr/HjmJFMrTJpyRn0XYcWMwk2o4DACxLMRseV4mATV1vt4byjQIAL7rPVknORQGt8Sb33RMAnqPtOADA8uMnAFp0vd3qwTfrATuJHUoAq3JX0PYQHNpjN8m3JMeiABa8l4+j7TgAAPBy+yKgQVfL/OUtedETeyIAWKlxko9igFb5kGQai/qAxUyi7TgAwHPszIbHefZAk2bL/OU+FLOnXnMAWIvjlF1dQHsc1BOAShTAArQdBwD4NUebwuPszKZJs2X+ch+K2W4u3BmJAGDlJkn+jDal0CbbKW3HT0QBLDiHHkfbcQCAp8ZKwEN2ZtOk2TJ/uQ/FbG0/uDMSAcBaTFN2dXkADu3yrh4bGxMBi5hE23EAgJ+pN8DjRiJgU9faPhSzZ15zANjIgGMUD8Chbfbqn89DUQAL3s+raDsOAAD82q4IaNBSXTAUs+kTZzYArH/QUUVBG9pmO8mXlLbj2oABi9zPx9F2HADA8w143EgENGy6zF/e6sk3feV1Jx7WAmzCdcpiIju6oH3e1ZMDC/6ARUxikRoAMGzOy4bHjUTAJvWlmD3zUgLARo2T/C0GaJ29lIL2WBTAArQdBwCGTDEbHmcjIU06X/Yf9KWYfeG1J3YdAWza+5QWpUC7bCc5Tdl1aQIKPEfbcQBgqNQZ4HFqLzQ951zK1lC/cXrJw1mAzZsk+W88/IY2Okp5OGMSCix6T6+i7TgAAADNWXrhUF+K2VOvPQC0xlnKw28FbWif3STfUzopADxH23EAYGhjH+ChSgQ0yM5sBu1ABACtmgDux24uaKtPKQtPdLYBFplvj6PtOAAwjHEPAKu19MKh325vb/vyzd96/UnymwgAWmUnpYPKniigla5SilRTUQAL2E9pP+6+DgD00R+xOxseo/5Gk/4vyWyZf7DVo2/eCnESu4sA2uY62pNCm+0m+ZbkWBTAArQdBwD6PtYBYLVmy/6DPhWz3WhIyk4BANrlrj2pB9/QXh9SdmdbGAgsel/XdhwAAPpPzYUmvehIyj4Vs2feAwDQauOUB99AOx3UY+pKFMACJvX14lIUAEAPGNPA4yx6p0nXL/lHitm4sAKwTpPYyQVttp3SdvxEFMACtB0HAPriWgTwKDuzaXoOuTRtxnFhBWDdJikPvhW0ob3e1ePrkSiAZ2g7DgD0ZUwDPGQDIRu/1m4NPQAAYCPudnJp4wXttVf/rB6KAljAxL0dAOgwm+XgcSMR0KDpS/6Rndm4sAKwyXt3FQ+9oc22k3xJaTtuNTaw6L1d23EAAOiHkQjYNDuzcWEFYNP37yoeekPbvUtZPetIF2CRe/s42o4DAN1isxw8biQCGjR9yT/a6lkI594HANA5dw+9FbSh3fbqScdYFMACJtGBBQDoDpvl4HG7IqAhL17s3LdithsOdgsBdNc4yV9igFbbTnKaUqTSdhx4zl3b8b9FAQC0nNoCPGTeT9PzwxfZEgQ9sy0CgE47SWlLCrTbUT32tpAQeM51kvdJ/httxwGA9lJbgIfM+WnS7KX/cEsQAEDLTJL8EQ+8oe12k3xPKVIBPOcs5WGYtuMAAADDM3vpP1TMpo+sFgLovru2pFeigNb7lFKk0n4MWGTOvh9txwGAdrHYDh5XiYCG54MvophNH3mQCtAPdy2MTSqh/d7kfhEKwHO0HQcA2sR52QCrN3vpP1TMBgDaPqGsknwVBbTebpJvSY5FASxA23EAoC0Us+FxlQho0MVL/+FWD8MwEcYFFqB/k8rDJJ9FAZ3wIck0uuUAz5tF23EAYPMuRACwci9eOLQlDACgI8ZJPooBOuEgpUhViQJYgLbjAADQPvsioCGv2ojcx2L21Hti8OwCAuiv4yRvxQCdsJ3SdvxEFMACzlIWrgEArJud2fD0vB6a8KqNyFvyo4esFgLot0mSP2P3FnTFu5SHQyNRAM/QaQ0AMAaBdlBnoUnT1/xjO7MBgK7e76soaENX7KUUtA9FAQAAtIxiNjykAy6tuc46MxsXWQC66m6n56UooBO2k3xJ6a5gvAYAALSFNuPw0EgEtOU6uyUQemhPBACDcZ2yQ/tcFNAZRyndFbQsAwAAgHYaiYAG2Zn9iCvvCwAY1GCoSvJZFNAZeykF7bEoAACADdLtDR43EgENsjP7ETPvCxdaEQAMzjjJRzFAZ2wnOU1yFm3HAQCAzXBsKTxuJAIa8uoNyH0tZms1jgstwDAdJ3krBuiUN/X4XdtxAABg3RSz4XEWndOU2Ws/QF+L2W5AADBckyT/TXIjCuiM3STfk7wXBQAAsEY2xsHj9kRAW66zdmbTV3b2AAzbWco52gra0C2fou04AAAAQF+8egOyndn0lQegANy1Lb4UBXTKm5QWVJUoAACAFbMxDh4yH6dV19m+FrOn3hsAQO4LYgra0C3bSb4lORYFAACwQjbGAbT8OrvV43C0FR22SgQA/DBg2k/yWRTQOR9SFqrqugMAAKyCYjY8VImABk1f+wH6XMzWHgQA+NE4yd9igM45SOmycCgKAACgYeoIAC3X52K2FVUAwM/eJ3krBuic7SRfkpyIAgAAAFZqXwQ05LyJD2JnNn11IAIAnjBJKWg7kgS65109zh+JAgAAeKVLEcCjHPVFUxrZeNznYvbMewQAeMIk5fwfBW3onr2Ugra24wAAwGvo7gqPszObpjSy8Vgxmz6zegiA5wZTVazEhi66azs+MeYDAABeSDEbnp5zQxNmTXwQbcbpM6uHAFhkvFBFQRu66ijJ1LgPAAB4ATUEeGgkAho0a+KD9LmYbVUVALDomKFK8lkU0El7KQXtsSgAAADgVUYioEGzJj7IVs9DssvKRRcAFnGdUghT0IZu2k5ymuQs2o4DAACLsTMbHhqJgAbNmvggfS9m253togsAyxgneSsG6Kw3KQ+ktB0HAACeo34AD41EQEMa23Dc92L21HsFAFjSJKWgfSMK6KTdJN+TvBcFAADwC4rZ8JBuZ7TuGmtnNn02EgEALzRJOUdbQRu661O0HQcAAJ6mzTg8pNMZrbvGbgmKHhuJAIBXjiOqJFeigM56k3I+UyUKAAAAgLWxM3tBM+8VAOAV7s7evRQFdNZ2km9JjkUBAADUzPPhcQcioCHTpj6QYjZ9ph0GAE24TtnV+VUU0EnnSf5KaTkOAABwN9cHoAPX2d8HENZVkl3vmUHaFgEADQ6+DlPO0j4SB7R+/H+WsgJ4Gg+pAACAx+f5wLxKBDSosaOgh1DMnkUxGwBoxrgeiH0SBbTGTUrR+q6APRMJAADwjAsRAKzMTZMfbAjF7Ivo8T9kVRrsyw8ASU5SVnCfigI25jLzu68BAACA13F0K01pdMHQEIrZ2oUAbRsQWPkJ3Tepf5ancawFrMNV5ndfG+MDAACv4fkcPLQjAhoya/KDbQ0gsKn3DNAid2fuAv2Y+FZpuG0O8D9fk/yV5I8ko5Q2/2dRyAYAAF7PvAIesjObpsya/GC/y5Oeq2JBA+1zlPJQ/tDAGTrvov55nibZEwe8ymXu24afiQMAAFghz+TgITuzacqsyQ82hGL21HsGaKGD+vpUGTxDLybAVUrx7UAcsLCbzJ97PRMJAACwJtqMw0MjEdCQWZMfbCg7s2/iPMuhspKINg+U9+qLemUADZ13V9CepHRfAB53nvud1+59AAAA0B67IqAhjT7z+X1AodkpNUzOeKBtft6FvZ37Hdoe6kP3jVMWqXwQBSRJrjK/+1o3EgAAYNMuRQAPjERAgxp9/jOUYvYsitlAe20n+Z7kbcquTqDbjuuxx6koGKCbzJ97PRMJAADQMhbZwkMjEdCQ86Y/4JCK2bgAQ9udprTGPxEFdN6kHn+cxVEn9N9l5ndfAwAAtJliNjzkyFZaa0htxhkmZzzQNtNn/vxTSnv8saigFz/vVf1fBW365Crzu689CAIAALpEvQAecmQrTZk2/QGHUsz2gA3okqOUlXBj1y/oxQR5VA/i9sRBh33NfQHbgx8AAADoFzuzaUrjNQ07sxmCUbSap3ve5H5Xp4I2dH8AV0VBm265zPzuawAAgL5QL4CH7MymtdfYrYEEpxA0bCMR0DI3C/69vZQigoEE9GMssp/ksyho8b3pc5K3Sf6vfr++j0I2AADQzzk6AB25xv4+oPDOkxx4DwEtcLHE9eiuoF3FqlHog3E9oHsnCloyPp6mFKzdYwAAgKFQzIaH1M9oSuPPmIZUzHaDGq79rODAeVij7fo9/D7JRBzQee/rQd2pKFizq5TC9bT+ZXwMAAAMkcW8AKtxtYoPOqRi9kXKGbQMz44I6IHt3Be+JuKAzpukFBIn9c83rMJN5s+9nokEAAAA+IljLmnKbBUf1M5sgM1c0F/atuU0peX4WIzQeWf1z/M0Cto05zL3xeupOAAAAB7MmYB5NgTSlJV0vvhdgAxAJQJaZvbKf39U/3csSujF+GQ/pfC4Jw5e4Crzu68t4AQAAHiaORM8ZGc2rb7GDqmYPfMeAnrkqB5kVAbh0IsxSpVSjFTQZhHnud95bcEmAADA4jxHg4fszKYpdma/0sx7yIUYemYvpZBx6BoHvZhMV0lOct99Ae7ctQ6fphSxAQAAeBkLguGhkQhoiJ3ZDbiMHU9D5DWnz4PmvfrjVQbj0IvB3rj+vYL2sN1k/tzrmUgAAACAFRmJgIZMV/FBh1bM1kIE6OO1aDv3O7Sn4oXOG9c/y6eiGJTz3BewLU4CAABYDfMteGgkAtpsaMXsaZIDL/sg7cRiBvptO8m3JG+TTMQBnXf3c3xS/3zTP1eZ331tnAIAALB65l7w0K4IaMD5qj7w77JlIPYfkDXXAAAgAElEQVRjxyrDGDSfpqykOxYzdN4kZcX4NArafXDXOnyaUsCeiQQAAGDtFLNh3o4IaPv1dWtgQU69l4AWWHU7ow+xOxv6dL2oklyKopMuk/yd5M96cniYstt+JhoAAICNzbOBe/sioO3XV2dmMxQjETAwR/X7/tC1D3oxEKxSFuXtiaPV7lqHT1N2X7v+AgAAAG1mZzZNma3qAw+tmG3V1XCNRMAAHaQUVKooqEDXXdc/yycpi1Voj/Pcn3ttrAkAANBeup7BQ3Zm05TZqj7wEM/MvorD7IHhXIv2Uoorh1Fkga67TjKuf6+gvTmXmd99DQAAQHfm1QCsxmxVH/j3gYapmD08Vhcx5GvRbu53aCtoQ/eN65/lT6JYi5vcF66ncd41wCoZqwIAq6SYDQ9VIqAhs1V94KEWsw+8pwbHuQ8M3XaS70neJpmIAzrvpJ6En4piJS5TitdnUVgBWCcPmAGAVTK/A1iNlR7jMNRiNsBQnaYs7jgRBXTepJ6IT1MWrPByV5nffa2YAgAAAAyBrrY0YaXP0oZYzLb6ygUZ2nIt2lSXiE/1z8TYywC9uJZUKUVYx6gs52vuC9gzcQAAAAxiDg3Ms0GCJkxX+cGHWMy208YFGVyLkqP6v+9dF6EXk/H9etC4J44nXWZ+9zUAAADD4hkYzLMJkE4YYjF76mUHSFIK2vspuzoN5qH7E/IqpfX4G3EkSW5yX7g+c50DAAAwdxYBzNkRAQ2ZrvKDbw001Bvvq0GqRAAP7NU3GqvwoB+T8sMknwecwXmSv5L8UU/IxikFfg8sAAAA0GYc5o1EQENW+uxtqMVsNy1g06Yt+loUtKFfxkk+DuR7vUryd5L/JvktZeHaibEeAAAAwLNGIqAhK30W9/tAQ7U7Z5i0zICnbacUtN+n7GIEuu04ySzJac++r5vMn3s981IDAACwgEsRwAMjEdCAlXfDtjObIbHrFH5tO6XwNRYF9MIkyZ/p/vEqlyk7ze9ahx/W39vMSwwAAMCCbHCDh0YioAErr7kOdWf2zHsLMIB+0mnK4o/3XibovGlK6+1pyoKVLrjK/O5rDxwAAAB4LXNLeEg3W5owW/UnUMzGhRk2o+0dIt7VPzNjLxX04nozSikM77X0a/ya+wK2cRoAAACrmBsD8/ZEQANmq/4EQy1mu3ENkzbjsJyj+uemitWr0HXX9c/yWZKDFnw9l5nffQ0AAADA+tj8R1O0GV8RRRmAxeylFJoOY7ck9GH8U6WcN3205s99k/vC9ZmxGAAAAGtmgxvMs/mPpqz8Od/vAw73MlooDM1IBLTMVZLdDnyde/WAvzLwh14YpyxO+bDiz3Oe+wK2awcAAACbZFE1wGrYme3mRYN2RUDLzDr0vtzO/Q7tqZcOOu+4vgadNvgxr3JfvJ4aawEAAAC0ViUCGmJn9gpN044zIwG6YjvJtyRvU9oUA902qQebk/rne1k3mT/3eiZSAAAAWmoqAoDGna/jk9iZzdDsR6tTeK3TlLb9x6KAzjtLWYk7zWIF7cvM774GAAAAoHucmU1nDLmYraA5TDsioGXXoa52iPiQUtAeexmhF9ei/ZQi9d5Pf3aV+d3XFgMCAADQNVcigAfUSmjCdB2fZMjF7Jn3GLBhXS8KHdWDnnEUuKAP46Iq9+3Cp/Uvi/8AAADow5wXmGdnNk1YS11AMZshXqCnYoDGvKl/pqooaEMfBp8mMgAAAAD9ty0CGrCWjTBbAw9Ze5Hh0ToDmreX+zbFAAAAANAmUxHAnJEIaMhsHZ9kS8gABtIN2K2/HwVtAAAAAID2GomAhszW8UmGXsx2DuTwVCKAldlO8j3lDG0AAAAAaIOZCGDOSAQ0YG3dr4dezHa+K0DzTqOgDQAAAEA7zEQAc0YioEvX1qEXs6fea4PjzGzapM8Lak6TTLzEAAAAAACtok5CE9bW/XpL1gzMnggY4sV+Q45SCtoGRwAAAABsylQEMGdfBDRgbZv17MwGYJWO6mutgjYAAAAAwOZ5VksT7MxeoxsRDM5IBLBWeykFbSv+AAAAAFinKxHAAzrY0gQ7s9foQgSDMxIBBtQbGSBNo6ANAAAAwPrMRACwEtN1fSLFbDczwDVoXbbrG9yhlx0AAAAAYO0qEdCAtXa9VsxWzB6ikQhgY7aTfEkyFgUAAAAAKzYVAUDj1tr1WjFbm/EhGokANu40yYkYAAAAAADWxjGQNOF6nZ9MMXvNgQP8ZMgLat4lmXgLAAAAALAiMxHAnB0R0AA7s/scOK1g5RFtMvQFNUf1ddggCgAAAICmzUQAc9RH6Ny1VTFbIWmIFM2gXfZSzi/yswkAAAAAsDqewdKE2To/mWJ2cS4CYEMsqCn26huglYEAAAAANGUqApgzEgENmK3zkylmF4pJw3IgAlrEUQf3tusJRiUKAAAAAIDG7YqABszW+ckUswvFJIB22E7yLclYFAAAAAC8wpUIYM5IBDTgct2fUDG7sDMboF1OkxyLAQAAAIAXmokA5oxEQAPWXlNVzC7szB6eSgQYVLfehyQTMQAAAAAAvNqOCGjAdN2fUDG7mIkAcP1ppaMkZwZaAAAAACxpKgKYsy8Cukgxu5iJYHAUxqA73tSTDz+3AAAAAAAv4/kqTZiu+xMqZt+7FMGgWIEE3bKXciSEn10AAAAAFjETAczxbJUmODN7SOED1CymWcxuyqovgy4AAAAAnjMTAUDjLtb9CRWz701FMCgjEdAiFtMsbru+Xo9FAQAAAACwsAMR8EpXm/ikitkM1UgE0FnbSU6joA0AAADA06YiAGjUbBOfVDHbjQ2gq06TTMQAAAAAAPBLjm6kCbNNfFLF7Hva/A7LSAS0yFQEL3aUUtDeEQUAAAAAtSsRwBzPT2nCbBOfVDH73oUIBmVXBNAbRykLAgzIAAAAAEg2VHCBFrMzmyZspJaqmD3Pai2AbtpLKWiPRAEAAAAAMMdGIJqwkS7XitnzZiIYFCuRGPQNoIf2UlaG+dkGAAAAGLapCGDOSAQ0wM7sFpiJYFCsRGLQN4Ce2q4nK4eiAAAAAABIophNM+zMboGZCAA6bzvJlyRjUQAAAAAM0kwEMGckAl7pfFOfWDF7nt2Rw1KJAHrtNMmJGAAAAAAGZyYCmLMrAl5pY8elKma35IUADK5ZiXdJJmIAAOiMKxEAAECjHLlKEza2IVgxe95UBMAGzESwUkf19d2gDQDA2BgAGIapCOB/9kVAA+zMbpEbEQxGJQIYjIMoaAMAAAAAw+OZKE2wM9uLAcCK7aXs9LESEQAAAKC/HFsC8zwPpQmzTX1ixeyHnJs9HFYj0SaXIliL7ZQd2pUoAAAAAHppJgKA/lxbFbMfsjN7OPZEQItYSLM+20m+JRmLAgAAAADouUoEvNJGO14oZj80EwHAIJwmeS8GAAAAgF6ZigCgUbNNfnLF7Ja9IKzdSAQwaJ+STMQAAAD8P3v3ely3laYL+K2u+b85EQgTATkRaGdgnghIRWB1BO2JwOoISEfQ6ggGjMBkBAeM4JAZnB/YJC1bF1z2BVjreaqmNDUey8BLCbcX3wIAQKF8M5u5TrqqtTJ7YT8Qjq4RAQvRiuBkrpJ8TnImCgAAAIDV60QAX9iIgJlO+plUZfbCfiAAnMRP6V8oUGgDAAAArFsnAnhlKpt9aE/5H1dmf92DCBzIgeqc707KjgsAAAAAQAkM77B6yuyvM53tQA6OO3VSaAMAAACsWysCeNWIgLUfV5XZTnbAMtyLYDE2u/PAtSgAAAAAgBVrRMBMz6feAGX215mQrIfpS+BrNkluotAGAAAAWJNHEcAXGhEw08kH8ZTZC/3BcDSWGQe+5ybJrRgAAAAAVqETAXyhEQEznXwAWJm90B8M4EKbxbiKQhsAAAAAWB8DfcxlMtsPhhN7LwIWohPBol3tzg0u/gAAAACWqxUBfOFcBMzUnXoDlNnf5tsaAPz5wq+NpXkAAAAAgOUzmMM+dKfeAGX2gn84OKADi3OefkL7QhQAAAAAi9OJAF55hsk+WGZ8wVoROKDDkT2IYBU2u3PEpSgAAAAAFqUTAcBePZ16A5TZ3/ZLkjsxADWdFBhsk+RfSa5FAQAAAAAs0FYEzLSIATxl9vddxqRkDSwzDkx1k/7lJwAAAABOrxUBwN4sYgBPmf3jH9I2yaMoimaZcZwYmOMfSW7FAAAAAAAsiO6DudolbIQy+8ee0k9oP4sCOLB7EazW1e7EbqUHAAAAgNMwlAZf8qySIiizh7mPbwuUrBEBsAfvo9AGAAAAOJVOBPAFk9nM1S5hI5TZw90n+SCGIjUiAPbkfHfj5EIRAAAAADiljQiYyTezV+g2Cm3gcDoRFHOR2EahDQAAAHBMrQjgVSMC9mARn0ZVZo93m+Q3MRRF4cRSdCIoxibJ70muRQEAAAAAHFkjAmZ6XMqGKLOnuY5CuySW2gAO5SbJRzEAAAAAHFwnAnjViIBSjqnK7Ok+JnkQAwA/8Gv6VT0AAAAAOJxOBPCqEQGlHFOV2dM9JdlGoV0KS42zBPciKNZVks9JzkQBAAAAAByY55DM1S1lQ5TZ8zwluUzyLAoHdtjTMYVy/ZSkdbwBAAAAOIhWBPDKAB9zLWb4Tpk9X5d+QluhDcCPnO9urFxMAgAAAACHYqCGuRYzfKfM3o/7JNdiWLWtCIAjUWgDAAAA7NejCOAL5yJgpnYpG6LM3p/PST6IAZjpTgRV2OwuBq5FAQAAADBbJwKAMimz9+s2yf+IYZUsuQEc2ybJTRTaAAAAAMD+bEXATIsaulNm798vSX4Tw+pY7hc4lZskn8QAAAAAMFkrAoC9eVrSxiizD+M6lgoGCjhJcDQ/p1/dAwAAAABgDsN7zHW/pI1RZh/OZZIHMayGZcZxkuDUrnY/f8cjAAAAgHE6EcArzxeZy2R2RT/obZJHUazCuQiAhRyL2iSNKAAAAAAG60QAr0xmM5fJ7Io8pZ/QfhYFAAOd7y4WXHQCAAAAAGOZzGaubkkbo8w+vPv0E9osXyMCnCRYiE36CW3nDwAAAIAfa0UArxoRMFO3pI1RZh/HfZIPYnCAh7WdJDipTZL/TXItCgAAAABgoHciYIaHpW2QMvt4bqPQBmC8myS/iAEAAADgqx5FAK8aETDT09I2SJl9XLdJfhPDYvk+LbBU/9idQwAAAAD4UicCeNWIgJnul7ZByuzju45Ce6nORIATBQt2lf77T45VAAAAAMDXeHbIXCazSZJ8zALXnAecKFi891FoAwAAAPxRKwJ4ZQVaijumKrNP4ynJNgrtpdmKAFiB8/QT/C5MAQAAAIA/MgRDcZTZp/OU5DLJsygAGOld+jfkFNoAAABA7ToRwCvPC5mrXdoGKbNPf5LdRqENfOlOBAywSfJ7kmtRAAAAABXrRACwF4vsK5XZp3cfRcRSvBcBsEI3ST6KAQAAAACqp+dgjvslbpQyexk+J/kgBgAm+jXJrRgAAACACrUiANiLbokbpcxejtsk/yOGkzsTAQvwJAImuNqdSxzHAAAAAKA+vpfNXN0SN0qZvSy/JPlNDA72VO9eBEx0lf5tZIU2AAAAUINHEcArzwSZq1viRimzl+c6yZ0YAJjoPH2h7eUcAAAAoHSdCOCV54EUeUxVZi/TZZIHMZxEIwKgAAptAAAAAKiLyWzmWuSqscrsZXpKso0lUk6hEQEL0ImAPdikL7SvRQEArEgrAgDAtQNM0oiAmZ6WuFHK7GX/gblM8iwKqE4nAvZkk+QmCm0AAAAAKF0jAmZY7IrRyuxlu08/oY2DPcAcN0k+iQEAAAAoTCcCeNWIgBmelrphyuzlu0/yQQwO9gAz/ZzkVgwAAABAQToRwKt3ImCGdqkbpsxeh9sotKEm9yLgQK52f77ORAHAd1zEJyoAAADWxPM+5jKZzWy3SX4Tw8FdiAAnDQp3nv4tOxe4ALxo0pfXn3fXIb9HmQ0AwDq0IoAkug3mW+yQ3X/42azK9e7XK1EczEYEQAXO0y/DtY2VAABqdbk7D1zGUnQAAABrZ3CFuRY7ZKfMXp+P6d+wORcFFO05Xq7gsDbp316+jLeYAWpwkbfy+r04AAAowKMI4It7PphjsUNPlhlfn6f0D6EeRHEwWxHgxEElNkn+N5aSBSjR2e74fpt+NY7fk/waRTYAAOXoRACwF4t+Ochk9jo9pZ+ouI/JTQDmu0n/vdRfRAGwatu8TV9byQkAAKCu+0GYqlvyximz1/0Ha5t+aViFNgBz/SN9oX0tCoDVaPJWXm/dFwAAUJlWBAB70S154ywzvm73UTocwlYEOHlQqaskn9MvTQvAMl0m+bS7Vvi/6VfX+CmKbAAAgJr5ZjZzdEveOJPZ6/c5yYf0D7EAJw+Y66f0bzZv03/WAoDTusjb9LXvXQMAwJtOBPDKC87Mcb/kjVNml+E2/UOun0WxFyYSgdqd7y5gLpd+IQNQ6LXoy7Lhl/FAAgAAvqUTASQxlc18ix5qUmaX42P6B19XonDgB9iDd3mb0FZoAxzWNm8F9rk4AAAAGMGAHnO1S944ZXZZrpM0sfwglEB5yBJskvye/nMWt+IA2Jsmb+X1NqavAQBgilYE8HqPCcVSZpfncncSN9HhwM+6+VYxS3Kz+/VWFACTnOWtuL5Mv/oFAAAA7EMjAma4W/oGKrPL85T+IVkXEx5TebgI8Fc3u/PLtSgABrnIW3lt5SQAANivRxHAq0YEzLD4wTpldrl/8LbpJ7QV2gDsy9Xu14+xegDAn53lbenwS9fhAABwUJ0I4FUjAmZY/CdPldll/+Hbpv/WKdMO/i6IOKVWBCzUVd6mDRXaQO22eSuwfeYHAACAUzgTATN0S9/Av/kZFe0+yQcxTNKIAOCbztO/cHEhCqDCa8SPST6nf6Hnf5P8HEU2AAAcWysCeOWelDm6pW+gyezy3aZ/K+dXUQCw54vkNv004r04gEKd5cvp63ciAQAAYGH3rTBHt/QNNJldh09JfhPDKKYNWYJnEbBwm/SF9qUogMKuA3/ZHd/+X5J/pf/EgiIbAACWoxMBvN7DQtHHU5PZ9bje/XolikG8zcQS3Cd5LwYWbpO+6PmQfjUQgLVp0k9db9O/nLMRCQAALF4nAoDZHtawkcrsunxM/5aO7ycAsG83u3PMR1EAK7DN29Lhro0BAABY8/0tTPW0ho1UZtf3h3KbfslED+2cAAD27ef0K1tciwJYmCZv5fVP4gAAgNVrRQAw2/0aNlKZXZ+n9CVDG0sowtJ1scw463OVfkJ7m5W82QcU6SxfTl/73jUAAAAl8s1s5jCZzWLd521CW6H9db6ZzRJ0ImClznfnmG0U2sBxb+BfymsvgwEAQLkeRQCvdBnM0a5hI5XZ9bpPP6H9L1F8lWXYAeYfR7v0pdK9OIADaPLl9LWXNAEAoA6dCOCVyWzmMJnN4n1O8iHJjSgAOIBN+rf7LuNbVsB+vBTX23j5EAAAALzYzRy+mc0q3KZ/c+dnUfzFWSyPixMJ7OOC+n/Tvzx1Kw5gpIu8ldc/iQMAAIgX5uFFIwJmeF7LhiqzSZKP6YvbK1F84cKFESfmZQpKcrM713wSBfAdZ/ly6fB3IgEAAICvakTADKsZplNm8+J6d+B7LwoADuTX9C8KXYsC+IOL9OX1ZSwdDgAA/FgnAkiizKaSY6kymz96+aaph4hOBACHcpV+8vI6Vh+Amq+xtnmbvvZ9LwAAYIxOBPB6fw3FH0uV2fzRU/oHil08VHQiYAlaEVCon3Z/vrdRaEMtXorrbbw4CQAAAPtwJgJm6Nayocps/uyl0G6j0AbgcM7Tf5flMiv6Pgsw2EXepq99xgYAANinVgTweu8NU3Vr2VBlNl9zn/7h4+9OBAAc0Lu8TWgrtGHdzvLl9PU7kQAAAMDB78VhqtU8j1Vm870/xB+S3DgRwEk9xyoJlG2TvtD+mORWHLAq27xNX1s6HAAAOIZHEcAr9+LMsZrPPyqz+Z7b9IXur6KAk7mP5Vkp3yZvL0/digMWq8lbeb2Nl60AAIDj60QAMNvdmjZWmc2PfEq/3PZVhftumXGA47qJMhuW5qW4voylwwEAAGAptiKgFspshrje/VpboW3aCACozUXeymsrgwAAAEvTigCgrmOpMpuhPqZ/uOkbDHBcXZQJ1OUi/fL6wHGc5W36ehvT1wAAALAGVpZljqc1bawymzF/sLfp39aoqdB+2Wc4lU4EVOZMBHCU65uXAtuLigAAwJp0IoAknqExz6qGiZTZjPGUfsnxNpbgBgBYiyZfTl+7jgMAANaqEwEkMZnNPCazKdp93qaVa3gQ6u0mAGCN1y/bvE1gWzocAAAAyrv3h6lMZlPFH/LrJP+qYF8vknz2I8dJBYAVXLNs05fX78UBAAAUqhUBJOlXYYMpHte2wcpspvqc5EOSG1HAQT2JAICvOMvb0uGXsXQ4AAAA1MQqbEzVrW2DldnMcZt+CujngvfRUh0Ax9WIAL5pm7cC+1wcAABAZR5FAEk8P2Oe1a0Gq8xmro/pC9+rQvfvwo8YwMU4nPDvw0t5vY3pawAAoG6dCCCJ52fMs7rVYJXZ7MP17uDp+4ywf60IAKpxlrfi+jKWDAMAAAD+yoqyzGEym2pdpi/dSlvysvGjBQAO6CJv09deDAQAAPi2VgSQxIqyzGMym6r/8G/TL/VS0hKYJqIAgH1q8uX0taXDAQAAgDFMZjNHu7YNVmazTy+FdhsPZmGfHuPFCoA12+Zt+vpcHAAAAJN0IoAkJrOpjDKbfbtP/6D298JODPd+tJz4Ql2ZTS28WUoJmryV1z+JAwAAYC86EQDMcrfGjVZmcwj3ST4kuSlkfxQrAMfjzVLWeq2wzVuB7QUkAAAA4FDei4CJnta40cpsDuU2/YPdX0UBABToIm/ltZtIgP2xKhYA8C2tCADqu99SZnNIn9I/6L1a+X5cuFBiAScYRQnAaTXpi+tt+hJ7IxKAg3gSAQAAfJNVDZmjW+NGK7M5tOvdr2sutC0zzql5oAdwGi+T19sk5+IAAAA4mUcRQBJ9BfN0a9xoZTbH8DH920IeAgMAa3CR5HcxAAAALEYnAkhiMpsKj6V/83PjCJ7STzQ9rHT7t36EAFAVbzkDAAAAS+SZBXN0a9xoZTbH8pR+yfFnUcBorQioiO/Ds5TrFgAAAJbjXgSQJGlEwERrHThVZnP0C45t1ldoe9MJAOq7ZgEAAGA5vHQMvUYE1HYcVWZzbPfpv6G9Jr71DQAAAABwOsps6DUiYKLVDm8oszmF2yQfxAAu1gEAAABgACtoQe+dCJjIZDaMdJvknyva3saPDBfrAAAAAACciE+iMke71g1XZnNKH5P8tpJtbfy4AAAAAABOwrAHJBciYAaT2TDRdZIHMQDgwpyFeRQBAADAYvgMH5jMZh7fzIYZtll+od34MXFiShVcmMNxdSIAAABYhGcRQBIDIFR6HFVmswRP6QvtJf9lavyYOLFOBAAAAABUyBLjABUfR5XZLMUaCm0AAAAAAIBT2IqAibo1b7wymyW5T3K50G2zfAcAAAAAwPGZzAaYp1vzxiuzWZo2yYcFbpfvt+KiHQAAAACO70kEkMTQHdNZZhz27DbJ38UALtqpViMCXOQDAACw47kY9DYioMbjqDKbpfqU5LcFbc97PxKAo2lEgIt8AAAAdrxsDKayqfg4qsxmya6T/FsMAAAAAABAxXwKlTlMZsMBXSd5EAOkFQEAAAAAFTKZDVYyZLq7te+AMpule0qyzTIK7a0fBwAAAADAUfkMFCizqZgym7VcrFwneRYFAAAAAEA1PBOGXiMCJmrXvgPKbNbiPv1k9CkvXnyTglPyBio1cbzFhT4AAACJJcbhRSMCJlp9t6DMZm0XLh9P+N+/8CPAhTs43gIAAADAkRn+YKrVdwvKbNbmNskHMQAAAAAAFM+AB/TORcBE3dp3QJnNGt0m+ecJ/ruN6AEAAAAAjsan98BUNvN0a98BZTZr9THJb0f+bzZi58QeRQAAAABARZTZ4JN8TFdEp6DMZs2ukzyIgYp0IgBwzAUAAKiIZcYBputK2AllNmu3zfEK7UbcAOBiHwAAAOCItiJgoiJeCFJms3ZPuwP58xH+W+/EDXAU70UAAAAAxGQ2wBxFfKpBmU0pfxm3OU6hDS7eAQAAAOA4fDMbfDOb6Uxmw8L+Ql46aeDiHQAAAACKYHgJemciYCKT2bAwbZIPThoAAAAAAKtnlULoGbJjqraEnVBmU5rbJH8XAwCwBw8iAAAAAE5sIwImKGZ1C2U2JfqU5LcD/d5b8XJCrQgAjsrnHQAAAE7HZDYkjQio/RiqzKZU10n+LQaA1bJ8EgAAANTNC8agzMYxVJlN0a6z/+VBfTMb4DgcbwEAAKBuymxQZjOdyWxYycXONvsttE0KckqdCAAAAACohGXGQZnNdF0pO6LMpnRP6Se0n0WBkw8AAAAAACti9UKm6krZEWU2NbhPP6G9j0LbiQMA6tGKAAAA4GRMZoPVYpmuK2VHlNnUdOHzcQ+/z7koAQAAAAAOzjezwYAd03Wl7Igym5rcJvkgBlbuQQRUohEBAAAAVMtnI6FnwI4piuoRlNnU5jbJP2f+Ho0YOSFvpFILx1oAAAColyXGAaYrqkdQZlOjj0l+m/HvNyIEAAAAAAAOaCsCJmpL2hllNrW6juWaAYDv60QAAABwEiazAUiizKZu20wrtC9Exwm1IgA4mk4EAAAAJ+FTe6CLYLq2pJ1RZlP7BdE2yfPIf+9MdAAAAAAAB6PMBl0EjqFJlNkwtdAGwMU6AAAAcBiWGQeT2TiGJlFmw8tf6ksnEFbCW6m4WAcAAACA8hn2YIrihjeV2dBrk3xwAmEFvJUKAAAAQOk8A4OkEQGOn8ps+KPbJH8XAwBQ6sU/AADASlidEJJ3ImCCrrQdUmbDlz4l+e0H/z/vxQQAVfDwBAAA4PieRQCmspmsKwtJEGYAACAASURBVG2HlNnwV9dJ/i0GnIgAAAAA4OiskgXKbBxDXymz4euukzx855/7bjan0okAAAAAAKBoOgimKm6lQWU2fPsv+zbJ4zf++YWIAA7KJx0AoN57MQCgbiazQQeBY+grZTZ821OSy/hGCwAAwLF4eA0AeLkNTGbjGPpKmQ3fd59+QvvZiYQFeRABwNHciQAAAOColNlgMptpinyOpcyGH7tP8tGJBBf0AAAAAHBwVmoBmKbI7kCZDcPcJvkgBgAAAAAA4MDei4AJinwZSJkNw90m+W33vzfiAAAAAADYO5PZANOYzAZynb7QbkTBCbUioBI+6QAAAAD18Yk9aueZGFOZzAaS9IW2twMBDu9MBCyAhygAAADH8ywC8EyMyboSd0qZDdN8FAEAVMELbAAAAO7B4JhMZjNVV+JOKbMB1seUIAAAAABAmUxmM8VjqTumzAZYH2+oAgAAAFAiz70gaUTABF2pO6bMBgAAAAAAlsCKhKDMZppiXwZSZgMALtwBAACAJVBmg2diOH5+QZkNsD6dCHDhDkdjiTsAAAD3YHBM70TABG2pO6bMBlifTgQAR2MqAAAAADiWMxHAl5TZAAAAAADAEpjMpnYXImCittQdU2YDAAAAAABLYHUsamcymymeS945ZTbAOj2IAAAAAICCPIsATGYzSdGrWiizAdbJW6rUwJuoAAAAUA9LjANMU3RfoMwGAJbKm6gsQSsCAAAA4Ei2ImACk9kAAAAAAAAHZDIbYJqu5J1TZgOsUysCAAAAAAris3pgpUKm6UreOWU2AAAAAABwaspsSDYiYALLjAMAAAAAAByQZcapnalspir6ZSBlNsA6dSIAOJpnEQAAAAAHdiYCJngofQeV2QDr1ImACrwXAQthOgAAAMC9FxxaIwImKP4TDcpsAAAAAADg1Hwzm9o1ImCCtvQdVGYDAAAAAACn5PNOoMyGr1JmA6yTZZcAAAAAKIVnXaDMZpq29B1UZgOsk2WXAAAAAADKcSYCJvDNbAAAqFwnAgAAgIMymQ3JuQhw/PwrZTYAsGQXImABOhEAAAAclFUIqZ2pbKZ4rGEnldkA63UnAlzIAwAAAAVQZlM7Ax1M0dWwk8psAAAAAADglCwzDjBeV8NOKrMBAAAAAADgdLYiYIKuhp1UZgOsl+WXAAAAACiByWwAx86vUmYDOFEB8H2tCAAAAA7K0Aa1881sHDu/QZkNACxZIwIAAAAo2rMIIGciYAKT2QAAJ9aIAAAAAIpm9UEwmc00JrMBWLROBAAAAAAAq7cRASPd1bKjymyA9epEAAAAAMDKmcymdo0ImOCplh1VZgMAgJsDAAAA91xwGo0ImKCaF4GU2QAA4OYAAADgVJTZ1K4RAY6d36bMBlgv5QoAAAAAa+cZF7VrRIBj57cpswHWy1ur1GArAgAAAAAKdiYCJuhq2VFlNgAAAAAAcComs6ndhQiYoKtlR5XZAAAAAADAqVh9kNqZzGash5p2VpkNsG53IgA4ikcRAAAA7N2zCCDnImCkql4CUmYDAMCPdSIAAADYO0uMAzh2fpcyGwAAAAAAAI5vKwImMJkNgJMWLMSFCAAAAKBYJrMBxmtr2lllNoALfliyjQgAAACgWAY1qJ1BDvgBZTYAAAAAAHAKymxqdyYCJmhr2lllNgAAuEkAAAA4BasOUjuT2Yz1XNsOK7MB1q0TAQAAAADAKpnMZqzqXgJSZgOsWycCAAAAAFbKZDa1a0TASF1tO6zMBgBc1AMAS3InAgCohm9mU7t3ImCkrrYdVmYDAEvXiAAAAACK8ywCKteIgAm62nZYmQ2wbpZiAjgO0wIAAAD75bkWtWtEwARdbTuszAZYN+UKwHF4yAIAAADs05kImKC6Z1TKbAAAAAAA4Ni8NEztLkTABNUNuCmzAQAAAACAY7PiILUzmc1YDzXutDIbYP3uRIALewAAAGBllNnUzmQ2jpsDKLMBABf2AAAAwLFZZhxgnLbGnVZmAwDAj3UiAAAAAPbovQgYyWQ2AE5gAHxVJwIAAIC9MpkN4Lj5Q8psACcwAAAAADg2AxrUzGf1cNwcSJkNAAAAAAAc07MIqNyZCJjAZDYAAAAAAMCBWWmQ2pnMZqzHWndcmQ3g4h+WbisCAAAAAApiMpuxulp3XJkNsH6+LwRwHA8iAAAA2AvDGdSuEQEjdbXuuDIbAACG8fIQAACA+yvYh0YEjNTVuuPKbAAAAAAA4JiU2dSuEQEjVbuihTIbYP1aEQAAAACwIpYZp3bvRMBI1b4EpMwGAAAAAACA4zgTARO0te64MhsAWLoLEbAQlsEDAADYD5PZ1MyzLhhBmQ1QhmcRULCNCFgID1sAAAD2w8vC1MxkNmPd1bzzymyAMihYAAAAAFgDQxnUzmQ2Y1X9ApAyGwAAAAAAOBZDGQCOm4MpswEAAAAAAOA4tiJgJJPZAKxeJwIAAAAAVsBkNoDj5mDKbIAydCKgcI0IcKwFAAAowpMIqJxvZjNWV/POK7MBgDVoRIAbBwAAgCIos6ndRgSM1NW888psAAAAAADgWCwzTs1MZTPWQ+0BKLMB3AQAAAAAAHB4ZyJgpOpXs1BmAzihAQAAAMCxGMqgZo0IcMwcR5kNAAAAAAAci6EMataIAMfMcZTZAMAaWIKJJTA9AAAAMM+zCKhcIwJGamsPQJkN4IQGa3AhAhbA9AAAAMA8XhKmdo0IYBxlNgAAAAAAABye1QcZq609AGU2AAAAAABwDCazqd25CBjBpxmizAZwYgMAAACA4/D5JmpmKpuxvAAUZTaAExsAAAAAHIcym5pdiICROhEoswEAYIw7EQAAAExmGANguE4EymwAYB22IgAAAABgxbYiYKROBMpsACc2AAAAADgOk9kAw3UiUGYDOLEBAAAAwHH4ZjY1881sxvICUJTZAAAAAADA4T2LgMqdiYCRvAAUZTYAAIzRiQAAAGASE4bUzmQ2Y9yJoKfMBnBDAMBwnQgAAACACTYigPGU2QDlsOQIJfPmKgAAAKybQQxq1oiAkVoR9JTZAMAaeHMVAAAA1s0gBjVrRIBj5jTKbAAAAAAA4NAUM9SsEQEjWc1iR5kNUI5WBAAAAAAslGKGmjUiYCQvAO0oswEAYDgPXwAAAICxzkTASJ5B7SizAQBgOG/FAgAATNOJgIpdiIARHkXwRpkNUJZnEVCwRgQAAACwWp0IqJjJbBwvJ1JmA5TF0iOUrBEBAAAAACt0LgJG8Jz/D5TZAAAAAADAId2JAGAwn7n7A2U2AAAAAAAAHMZWBIxkMvsPlNkATnIADNeKAAAAYLROBACDmcz+A2U2gJMcAAAsiRc0AaA8nQio2IUIGKkVwRtlNgCwFmciAIAqeEETAICSeKYFMyizAYC18BYrAAAArFMrAirmmRZj3IngS8psADcGAAAAAAAchslsxrBS1Z8oswEAYJxHEQAAAIzSiYCKNSJghHsRfEmZDQAA43QiAAAAcB8FA70TAY6X0ymzAcpiCRIAAAAAgGVoRMBInQi+pMwGKIslSAAAAABYkjsRULFGBIzUieBLymwAYC22IgAAAABgRc5EwEidCL6kzAYAAAAAAA6lEwEVuxABIzyI4K+U2QDleRQBwEH5pAMAAMBwnQiomMlsxngSwV8pswHcIADgxgIAAADYP5PZjGGA4iuU2QAAAAAAwKG0IgAYxADFVyizAQAAAAAAYP/ei4ARWhH8lTIboDyWIqFUlmUCAACA9elEADCIyeyvUGYDOOHBWmxEAAAAAKvTiYBKGcxgLINqX6HMBgCAcVoRAAAAAD9wJgJGeBbB1ymzAQAAAACAQ7gTARUzmc0YprK/QZkNUJ5WBAAAAAAAJ2UymzE6EXydMhsAAAAAADiETgRUrBEBjpfzKbMBADcBAAAAwCF0IqBijQhwvJxPmQ1QnicR4CYAHGcBAACAk2pEwAidCL5OmQ1QnnsRADjOAgAALEArAir2TgSM4HnTNyizAQAAAAAAYH/ORMBIVgL8BmU2AAAAAABwCJ0IqNSFCBjhTgTfpswGKNOjCAAAAAA4sU4EVMpkNuyJMns9bkUAuFEANwIAAAAALJ7JbMZoRfBtyuz1uEpyLQYA3AjAIjyIAAAA4LssmwswjO9lf4cyez0ektxEoQ0A4CYDAAAAWLKtCBjhXgTfpsxej5cHpgptwMkPAAAAgKXrRADgeDmXMns9/lhMfYplVoHvMzEIAAAAwCl1IqBiOhwcL/dEmb0efyymNuk/Bu9gCAAAAAAAsCwbETDQowi+T5m9Hu1XDoRtFNoAAAAAACxPKwIqpbdhjE4E36fMXrdNktskZ6IA3CxQia0IcJwFAAAAFkxnwxj3Ivg+ZfZ6tN/4v5/v/pmDIwAAAAAAS9GJgEo1ImCEJxF8nzK7DAptAAAAAACWpBMBlWpEwAgms39Amb0ud9/5Z+dJPokI2PE2FwAAAADA8TUiYATP8n9AmV2Wq/Tf0AbwNhcAAAAAp3InAirWiIARWhF8nzK7vD/QCm0AgMPz1iwAAADwNT4Jy1DPIvgxZXaZrpJ8FAMABboQAQthBQwAAIBv60RAxc5FwECeLw2gzF6XdsT/769JrkUGVXsQAQXaiAAAAAAWrxMBlTKVzRhW/htAmV22myi0wYkQAAAAAIBjsKogY5jMHkCZvS7thH/nxsETAAAAAIAjakUA8EOdCH5MmV3PhYNCGwAAAAAA4HC2ImCETgQ/psxen7sJ/84mCm2oUSsCgIOxDBQAAMC3dSIAcKzcB2V2PTZJPic5EwUAK9eIgAV4EgEAAMA3dSKgUoYKcazcM2X2+rQz/t13u39foQ3AmjUiAAAAAGCB9C8M9SCCYZTZ9TmPQhtqYWoQAAAAgGO7EwEVM5nNUJ7fD6TMXp92D7/HeZJbUULxfM8VAAAAAOB4NiJgoFYEwyiz6/VTFNoAAAAAAOxXJwIq1YgA9k+ZvT7tHn+vqyi0AQCmsnQeAADAX3UioFKNCBihFcEwymyukvwiBnDjACtyJgIAAAAAFqYRASP4ZvZAyux12vcU0D+SXIsVitOJgEJdiAAAAAAWqxUBlWpEwAj3IhhGmc2Lmyi0AQAAAAAAprCaIEM9i2A4ZfY6tQf6fW+SbMULAAAAAMBEnQiolNUEGcpU9gjKbP7sswMuFOVBBAAH49tGAI6vAMBfdSKgUiazcZw8AGX2OrUH/L03u99foQ1l8CAQ4HC8RQvg+AoAAC/ORcBAnQiGU2bzNS+FtreIAAAAAAAY6k4EAD/kBd4RlNnr1B7hv6HQBmCptiIAAAAAYEG2ImAEK6qOoMzme86j0Ia1a0UAAAAAwJF0IgD4IZPZIyiz1+tYy7WcJ/ksbgAAAAAAfqATAZW6EAEjmMweQZnNEO+T3IoBAOALnQgAAACAWOGW4e5EMI4ye73aI//3rqLQhjXyhhfA4XQiAAAA+EIrAiplMhsORJnNGFdJfhEDrIpvbwAAAAAAHJbJbIZqRTCOMtsf9rH+keRa/ACckDddAQAAYJk6EVCpRgQMZDXVkZTZTHEThTYAp7MRAQAAACxSJwIq9U4EDGQ11ZGU2evVnvi/f5Pk0o8B3EAAAAAAAFSsEQEjdCIYR5nNHLex1Cs4MQLUqxUBAADAqzsRUKlGBIzQiWAcZbaLgzk26R/iKrQBAAAAAIAanYmAgR5FMJ4ym7leCu1GFAAAAAAA1epEQKUM/OE4eUDK7HVrF7IdmySf4+0jWKoHEVCgRgQAAACwKJ0IqJRuhKHuRTCeMpt9OU9frjtow/I8iYACNSIAAAAAYAFMZjOUZ/UTKLPXrV3Y9pwvcJsAAA7pWQQAAABJPBsGcJw8AGU2+3ae5FYMAEAlLA8FAAAAdXsvAjgcZfa6tQvdrqsotMGxAgAAAICadCIA+K5WBOMpszmUqySfxAAAAAAAUIVOBFTI97IZyqfqJlJmr9/dgrft5yTXfkQAHMCZCAAAAAA4Mc+oGMqn6iZSZnNoN1Fow6k9iYACeesVAAAAluNOBFTKMyqG8px+ImX2+rUr2EaFNpyWN74ADqcTAQAAAFTLZDZDeU4/kTKbY/kUbygBAOXpRAAAAODeiGo1IsBx8rCU2evXrmQ7N7ttVWgDAAAAAJSlEwGVakSA4+RhKbM5JoU2OEkCAAAAAJSiEQEDWWZ8ImX2+rUr295Nktv4jgQcUycCAAAAAA6oFQGVeicCBnoSwTTKbE7hfHdxo9AGYKqtCAAAAAA4IR0HQz2IYDpldhnuVrjNCm0AoASWiAIAALAyIHXySVWGMpU9gzKbUzpP8kkMcBR3IgBwMwIAAHAgnQiokGE9hmpFMJ0y21+CU7tK/w1tAAAAAACAtTCZDUegzGYJFNoAAAAAAOtkRUCA72tFMJ0y21+CpbhKcu1HCQdjGVwAAAAAgP3ZioCBPJ+fQZnNktxEoQ2Hci8CCmMZJ9yMAAAALEMnAoDv8nx+BmV2GdqC9kWhDcAQGxHgZgQAAODkHpN8FgOVMmzB0OMkMyizWaJPTgIAAAAAAIv0mOSfSf47SRNlNvUybMEQnQjm+Q8RFOMuyfuCTgBt+u9NmHYCJ0wAAAAATutlAvs2ntlCYiCP4ToRzKPMZqkU2uCECQAAAMDpKLDh285EwECdCOZRZpejTTmT2S82u4uliyRPfsQAAAAAAAelwIZhGhEwkGPpTMpslu5d3ia0FdoA/PmmoRMDC/C4u2YBAABY6z2NAhvGaUTAQLqtmf4mgmK0Be/b+W7/LNsB07kRwU0DHE4nAgAAYGUek/wzyX/v7q8/xvMjGKMRAQM5ts5kMpu1OE//ZuClKGASb38BAAAA1O0h/QT25yhXYK5GBAzk2fxMyuxytBXs40/pC+1rP24AAAAAgB96SP9M9XOsKgX7ZCVZhrgTwXzKbNbmavfrtSgAAAAAAP5CgQ2Hdy4CBjCVvQe+mV2WWt7wuEr/DRfAMQIAAACAvsD+e5L/SnKR5FMU2XAoprIZyicd9sBkNmv1a/o3Wm5FAeDGARZwY/JeDAAAwJGZwIbTuBABA5nM3gOT2WVpK9vfm1huHMCNA7gxAQAA6mECG2A9TGbvgcls1u5mdzBwQIAfU7YAAAAArI8JbFiWrQgYyDF7D0xml6WteL9N58GPeekDAAAAYB1MYAOsn+P2HpjMpgSb9IX2Nso6AAAAAGCdTGDDOhiuY4hHEeyHMrssbcX7/lJoN7GUMgBwXK49AACAqf6dvrz+7N4CVuNMBAzQiWA/lNmU5I8T2i78wMkT4FisDAMAAIyhwIZ1M5nNEJ4X7Ykyuzx3Sd5XvP/nUWjDt3QioDBbEQAAALASCmwox0YEDOBYvyfKbEp0vrso3IoCAAAAADgRBTaUpxEBA7Ui2I+/icBfjkK9T3IrBgAAAADgiP6d5EOS/0xymf4ZpSIbytGIAI7LZDYlu9r9ei0KSOIbHQAArEMrAgBWxgQ21KMRAe5rjstktr8cpbtK8osYIHEzBXAwnQgAAKA6JrChTo0IGOBZBPtjMpsa/CP9Q+ZbUQAAB9CJAAAAqmACGzgTAQNYJXWPlNnlaUXwVTe7X29FAVCMCxEAAABwQM/pi+s2Cmyg53kUQzhf7JEym5rcpJ+cakVBxe6SvBcDhdiIAAAAgD17KbBf/gfgj0xmM4TJ7D1SZpdJWfVtn5NsHUgAAAAAgB0FNjDUuQgYoBPB/iizqc0m/WT2NgptAAAAAKiVAhuAQ+lEsD9/E0GRWhF810uhbTkQauRbHQCH8SACAABYvOckvyX5P+mfDV5HkQ0MtxUBAxmm3CNlNrVSaOMkCsA+eVkIAACWSYENwLF5TrRHyuwytSIY5DwKbYC1a0QAAADAnyiwgUO4EAEDWL1vz3wzm9q9FNpOQgDr1MQ3aAAAAPANbODwDMYxhKnsPVNml6kVwSjnSW7Tv6EJpetEAAAAABRCgQ0ck6E4hmhFsF/K7LIv5DZiGOxq9+u1KChcJwIAAABgxR7TF9e3Se7FARyRyWyGMJm9Z76ZXS4XcuNdJfkkBgBgglYEAABwMI9J/pnkv9N/bupjPP8Ejq8RAQM4P+2ZyexyefNjmp93B5pbUQAAAADAyZjABpbmnQgYQD+3Z8rsct0n+UkMk9zsfr0VBQVqRQAAAAAslAIbWKpGBAzk/LVnyuxyefNjnptdhp9FAbBo23hJAwAAYM0U2MAaNCJg4DmNPVNml8uF33y36UsSWQIAAADA/iiwgbU5EwEDdCLYP2V2uUxmz7dJP+23dVFNYZ53f74BcLMCAADHosAG1uxCBAzQiWD/lNnlckG4Hy+F9oWDEIUdH96LAcDNCgAAHJgCGyiFyWyG6ESwf8rsspm+3I/N7qJ7GxPvAAAAAPA9D+mHQ26jwAbKYTKbIZz3DkCZXf5fGtOX+3GetyXHFdoAAAAA8OYhfXn9OabSAKiX/ugAlNn+0jCcQptSdPGiC+XwViwAAMBpKLCBmnieyhCtCPbvbyIomuUM9u88yScxsHJuMCmJ7xUBAAAcz0OSvyf5r/QvF3+K5wwAwAGZzC6b6eHDuNr9ei0KAGDHS4QAAJTKBDZQOysDMsSdCA5DmV02D1UPR6ENAPyRlwgBACiJAhvgjZUBGcKzoQNRZvuLw3RX6b9/cCsKVsaLLgAAAMCfKbABvs5kNkN47n4gymx/cZjnZvfrrShYES+6AAAAAIkCG2AIk9kM4bn7gSizy/ecZCOGg1JoA5xOIwIAAIBRFNgA4zQiYAADpgeizK7jL897MRzcp13WDlYAx/VOBAAAAD/07/TldRsFNsBYjQgYwPn1QJTZ5bOswXFsdjcD2yi0Wb5WBAAHcRcvEQIAsBwvBfbneEYIMEcjAgboRHAYfxNB8RSrx/NSaF+IAgAAAIAT+HeSD0n+M8ll+uXEFdkA81gZkB95EMHhmMwun4vV49rsbhK2sgcAAADgCExgAxzOmQgYwPn3gJTZ5TOZfXzneVty/P+zd4fHbVvruoDf6zn/xVRgngqkVCCeCsxdgegKrFRgpwIrFYipIHIFoSswVcGGKohUwb4/FrilOLZFSSSxADzPjEYzd+7ZgV+KJIAX61s+wKjVXcrDFwAAAED/KLABDsMkVrahi9sjY8aHz8lsNzaFtqe28OUK++ezFgAAGAMjxAEOz30ntuH7eI+U2cOnsOrOcZILMQDsnSdkceECAMBQKbABuuW+E9tYiWB/jBkfB+OEu3PW/l6IAgAGb53kjRgAAHghI8QBAFrK7HFYJzkVQ2cU2tSo8bkAAAAAVbhLWdGlwAaoz0wEbGElgv1RZo+DE+DunaU8VGDsOLVoRAAAAACduct9eX0lDgDo9Xc6e6TMHgcjL+vwMeXBgqUoAAAAAEZHgQ3QP/bM5jFrEeyXMnscrMyux2X7eykKAAAAgMFTYAP025EIeEQjgv1SZo+Dp0Lqctm+Jl4XfC7AbsxiXxp8tgIAUA8FNsAwWJXNNhoR7JcyexyszK7PKqV8cdMbnwsAPlsBAOg/BTbA8ExEwBYaEeyXMnscFKb1OYpCGwAAAKDPFNgAwzYVAVtoRLBfyuxxnVzb26EuR+2Fzkms5AIAAADoAwU2wHhMRcAWLFjcM2X2uN5Mp2Kozuvcr9BWaHNIKxEAAADAVhTYAOM0FQFb0O3smTLbm4nuHUehDQAAAFCTm9yX1ytxAIzSVAQ84loE+/dKBKNhzEHdjpMsxQDwLCcioBIrEQAA9NpNkt+S/JxSYJw7xwMYtYkIeIQFigdgZbY3FPV4k1JoL0TBgdyl7N0OLiwAAICx2qzAXsZiEAD+7lgEPGIlgv1TZo+Hk/F+OGt/L0TBgT4XTsUAAADAyCiwAXiMxRNsw0LSA1Bme0NRn7MkTZIPogAAAADYCQU2AE9hWzu24ZziAJTZ3lDU6X1Kob0UBQAAAMCzKLABgH2ykPQAlNnjYn/cfrlsfy9FwZ40MWYcwPkWAMCwKLAB2IWZCNiCc40DeCUCbyqqdulLkz1qRMBATEWA8y0AgFG7SfJbkp/b64Nz52UAwAHOPzgAK7PHxbiDfrpKKbRdhAF822sRAADA6FwnWcUKbAD2w57ZPKYRwWFYmT0uTuz76ai9OPPlCQAAjIVVDsC3XCf5Jcn/ptwnsQIbgH2ZiIBHOAc5EGX2uFiZ3V+bQtsXKLu0EgEAAJVqRAC0vi6wL3xGAHAAFpfxGJ3bgRgzPi6eEum3TaE98yEJAAAADNh1yvjwqyiuAejGkQh4hM7tQJTZ46IA7b/jKLQBoPYLmVMxAAA8mQIbgFpMRcAWdDQHosweF0+JDMNxe2E3EwW+bOG/Jv6m8dkKANA7CmwAajQVAVtYieAw7Jk9PnciGITT9mIPXsIDLgyJfYwAAKAf7IENQO2mIoB6WJk9PkZfDsdZ+3shCgAAAKBiVmAD0CdTEfCIzyI4HGX2+Bh9OSxn7UXgB1EAAAAAFVFgA9BXExHwCF3bASmzx2ed5I0YBuV9e1G4FAXPcJPktRgAAADYgU8p5fUqCmwA+st2djzGFp4HZM/s8fG0yDBdxrhxnqcRAcBOrUQAAIzMpyRvk/yUZJ7ysL1rTQD6zMpsHuNc54CszB4fT4sM12XKwwpXogAAAAD2aLMC+yoWTgAwPMci4BGNCA5HmT0+LjCGbZlkFg8tAOMzixWxAACwTwpsAICiEcHhKLPHR8k5bEcpZc7Ma80TPhNOxQAAAMA3KLABGJuZCNhCI4LDUWaP011K6ckwbQrtEx+obMHNCAAAAB5SYAMAfN+1CA5LmT1OVmIO31F70Tlz4QkAB+V7FwDoIwU2ABQnIuARzpUOTJntjcZwHed+5LjXHAAOwzYfAEBfKLAB4J8mIuAR7v0c2CsReKMxaJtCG77H3wcAAMA43KUU2G+T/JRknmQZRTYAPGRlNo9x7nRgVmZ7ozF8x+3F6UIUgAsNAAAYlbvcr76+EgcAPMrKbB6zK/xArQAAIABJREFUEsFhKbPHycrs8Tlrfy9EAbjQAACAQVNgA8DzTUXAIywYPTBltjca43HWvvbnosDnAQAAwKAosAFgN16LgEdYMHpgymxvNMblXfv6L0WBzwOAvblx8QsAHIACGwB2ayoCtjj/4sCU2eN+wx2JYZQu299LUQDAXjRRZgMA+6HABoD9mYqAR1gc1gFl9rjfcKdiGC2FNgAAAPSDAhsADmMiAh7RiODwlNnjZZ9cLlIeavAkEcbhMgRTEQAAMCAKbAA4vBMR8IhGBIf3SgSjpcDkKMnKFzS+gBkID2QAANB3d0l+T/KvlJVhiyiyAeCQrMzmMY0IDs/K7PGyMpvkvtCexQMOAAAAcGg3uV99vRIHAHTKwi8e04jg8JTZ46W4ZOMoZe/sWTzkAAC7sEpyKgYA4Ds2BfYy7s8AAPSJc7cOKLPHS2nJQ8e5X6Htb2OcX8BKFwAAgP1RYANA/dwj5TH6kw4os8fLhRNfU2j7AgYAAGB3FNgAAMPxWQTdUGaP213KiGnYOE5ykWQhCqCHJvFwBgAA3VJgA0A/2S8bKqXMHjejhfmWs/b3QhRADy86VmIAAODAFNgA0H8TEfCIlQi6ocweN6vX+B6F9vi+hN+LAcA5FgCwNQU2AAyLldk8xv2ejrwSwai52OJHzqLMBgDnWADAxk2S35L8nGSa5Nz3PgAMhpXZPMZ5X0eszB43T5HwmMv291IUAAAAjNB1yjSrZdzABIAhm4qAR+jUOqLMHjcXYWxDoe1LGAAAYEyu22vgqySNOABgFKYi4BE6tY4os8dNgcW2LtoPah/WvoQBAACGSIENAOM2FQE/cCOC7iizx02BxbaOUsaqzfzdABWbtZ9VAACwDQU2ALDxWgT8gHPFDimzuUspKuExCm0AcIEDAH2nwAYAvjYRAY/QiXTolQi8AUXAExy1F/y+3IfHmBSA3WlEAABVuU7yS5L/TXKSspWW72sAYONEBDzCtr0dsjIbb0Ce6nXuV2j7+xmOJkbpAAAAw2EFNgCwLYu3eIyFoR2yMhtvQJ7jOKXQ9iUPAABALazABgCew8psHmNhX4eszMYbkOc6TnnKfS4KAAAAOmIFNgAA+7YSQXeszMbKbF7iTcpNA3wZQw08RQsAMA6fkryNFdgAwG7MRMAP3ImgW1ZmY2U2L3XW/l6IAuiYrQ+oyeckp2IAgJ35lLL6+iruZQAAcDgWhXZMmY03Ibtw1v4tXYgCAACAHVFgAwCHYNofP+I8tGPKbJIyIuFIDLzQx/ZDfSkKX8gAAADPpMAGAA5NP8KPWBTaMWU2mzeiMZjswmX7eykKX8gAAABbUmADAF2xKpvHNCLoljKbuFBkxy5TilHlKAAAAN+jwAYAajARAY9oRNCtVyIgSkd2bxVPtAGHNxUBFXFTHgD+6VOSt0l+SjJPmerlOxMA6NJUBDyiEUG3lNnEhSN7cBSFti9kOLzXIqAiHhYEgEKBDQDUbCoCHtGIoFvGjJO42cp+bArtadyo8IUMAACMiRHiAEBfTEXAD1yLoHvKbBIl1hjcpJsVi5tCexY3MAAAAIbqLvfl9ZU4AIAemYqAH9BrVMCYcRJl9hjMU24udOE4pdCeeBkAAAAG4y7J70n+1V7vLaLIBgD6x31rfmQlgu4ps9m4EcGgrVNuLHTlOG5q9IGRKQAAwI8osAGAoTkWAdRNmc1GI4JBm6bcYHjb4TGcJll6KapmZApD4GlanFsBwG4psAGAoXIficesRNA9ZTYbjQgGbdr+XqbchOjKWRTawH6diADnVgCD4EHLbimwAYAxcB8J1yU9oMxmoxHBaCySfO7wv3+W5IOXAQAA+IG1CA5OgQ0AAK5LqqPMZqMRwajM0+3+yO/T7R7efNtKBAAAMCoKbABgzGYi4JFzZSrwPyKg1YhgVG5TCu11kqOOjuGy/b30cgAAABzMXUphvfkBAAD+yarsSiiz2WhEMMrXfJbkS4fHcNkex8rLAQAAsDc3KcX1KgpsAIANe2bzI40I6mDMON6U4zD7zv/7Osnbjo/tyklDNW5FALAznt4FoGs3SX5L8nOSaZLzKLIBAB6aiIAfaERQB2U2X1/oMj7LlBscXTlKWR2g0O6e4oUhmImASnhACICuruu/LrCd5wMAfJt70vyI8+hKGDPOQ02S12IYpfOUp9DOOvrvbwrtadz8BwAAeIrNCPFl3HADAHiKIxHwA7qKSliZzUONCEbtPMl1xycOqxjtAgAA8BgrsAEAXmYqAh7h/LoSVmbzUCOCUbtNGc/bpLsn0o5TCu1ZPPXkMwAAAHjICmwAgN2YJ1mIgUfoKCqhzOahRgSDNX3Ch/MspVDuutC2X4nPAIC+u4uRZQC8jAIbAGA35g9+XKvzmM8iqIcym4caEQzW9An/f9cpT6X90eHxHqfcrFl46QDosXWSUzEA8EQKbACA3ThJucc8T/JaHNBPymweakRA6yrJL0k+dngMZ+3vhZcDeOJFCgBA3yiwAQB2Q4HNLqxEUA9lNg81IuCBi/aL/6zDYzhLGX1+7uU4mOuUlfHQVxMRAAA9OvdeppTYrscBAJ5Pgc2u2S+7Ispsvnbjw54HFu2JQJfl5ruUlQlLL4cvaQAA6DkFNgDAbkxTFkEpsNkH05Iqoszma40Pfr4ySxmp0WWhfdn+Xno5AACAnlFgAwDsxjSlvF7EdEn2y3l7RZTZfOsNeiqGwXnJa3rbnhyskhx1+G+4bI/lyssJgPMqACqnwAYA2I1pFNgcnnP4iiiz8QZlG+v2hOHPjo9jmbJS3IiP/VlF8QLgvAqA51BgAwDsxjQKbLpzI4K6KLP5mgtuvmeV5G3uR3534ag9jlkU2sD3L3YAAA5FgQ0AsBuT3BfYFtvQJef1lVFm403KUyyTnCR51+ExbArtE3+vwDe8FgEAsGcKbACA3dgU2PMkb8RBJSykq4wym6+5EOcx5ykrH7s8uThKuXE0S9lHm92RJwAA/JMCGwBgNxTY1M498soos/mai/Lhmu7w9V2krI7ucr+S49yPHPflsjueOgMAgOJTe82hwAYAeBkFNn3iHnlllNl8y02MaR2iaXZ3A+a2PfFYp6yS7opCGwAXPwDs0qeU8vrKNQYAwIvNH/wciYOecB1QGWU239JEmc12fyezlDK560L7ImW1OAC4+AHgqRTYAAC7o8Cm71YiqIsym29pkpyKgS2sU/bQvuz4OM7a3wsvyU7e/9B3k7gRDQD8mAIbAGB3FNgMxZ0I6qPM5lsaEfAEy5QR5u87Pg6Ftvc/bJzEE5QAwD8psAEAdmeWci9Wgc2Q2DKuQspsvqURAU/0IaXQPuv4OM5SCqyllwQAAIgCGwBgl05yX2DbqpQhcs1QIWU239KIYJBm2e9KxUV7MnPc8b9zM/J86SUHAIBRUmADAOyOApsxsTK7QspsvqURAc80az/suz6pUWi/zHW6fygBYAhWIgA4GAU2AMDuKLAZq0YE9VFm483KLt22JzirdL9PykVKse5Jque9jgAAUDsFNgDA7kxTCuxFFNiMVyOC+iiz+Z4bX1g807o94fmj4+M4SinVZ1FoAwDAENzlvry+EgcAwItNUxYnLWJSIyS6hCops/meJspsnu8qydvcj/vuikL7eaxqoe9mMd4ZAIZCgQ0AsFvTKLDhe9wbr5Aym+9pkpyKYXAnKYe0TCmUzjr+dx89OBZfRNtZJ3kjBgAAOrRqz0sV2AAALzeNAhsecy2COimz+Z5GBIM8YTm0Rfvf7frBiOPcr9BWaANwSLZuAXielQgAAF5kklJgz2PhCmxDd1CpVyLgOxoRsCPz1PFE06bQnnhJAHBOBQAAwABNUhYYXSX5K2UbSEU2bGclgjops/meRgTsyG1KoX1XwbEcJ7nwknj/AwAAAMBAKLCBQTNmnO9pRMCO/55mSb5UcCybPbwXXhbvfwAAAADoqUWMEIddWomgTspsvqcRATu2TvI25cnArim0YdhORAAAAAAM0PzBz5E4YKfsmV0pZTY/cpPktRgG47SCY1imlEzvKjiWs5SC3dhxGJ6JCAAAAICBUGDDYaxFUCdlNj/SRJnN7p2nFE1nFRzLx5SnrZZeFl/aAHv8TD0VAwAAAE+gwIbDuhFBvV6JgB9oRMCenCe5ruRYLmPc+NeMUwHwmQoAAMBhnaQsurlN8kfKYiBFNhxGI4J6WZmNNy9duE0ya//Gajghu0xZOWdFMgAAAABwKCcpC23mMSUVutSIoF5WZuPNS1c2hfZdJcezak8eAQAAAAD25STJRcr99y9J3kWRDV1rRFAvZTbevOMyrex41qlnxPdRFNoPfRYBPusAAAAAdkKBDXUztbViymx+pBHB4EwrPKarJL9UcixH7fFM/KlAr7kYBAAAALo2TXIeBTb0wa0I6qXM5kcaEXAgF0l+r+RYXqes0FZoA7ALKxEAAACMxjSlwF4n+XeSj1FgQx9YmV0xZTaPuREBB7JIcl3JsRxHoe1JNAAAAAB43DT/LLCPxQK94n54xZTZPKYRAQc0S12F9nLEr4Un0QAAAADg2yZRYMNQfBZB3ZTZPKYRAQd0m7JC+66S43mTcRfaAAAAAEAxSbl3eZXkryiwYSisyq6cMpvHNCIYlFkPjnGdZF7R8ZxFoQ19vcAEAAAAeImvC+zLlAUwwHCYUlo5ZTaPaURAB1ZJ3lZ0PGdJPnjvQ6+ciACfpwAAADyDAhvGxcrsyv2PCHhEIwI6skwpo95Vcjzv2/fD0nsfAJ+nAAAAgzNPKbEV1zAuVmZXTpnNYxoR0KHzJNOKTiAv299LLw0AAAAA9N78wc+ROGCUGhHUTZmNNzG1W6SMHT+u5Hgu2/fFyksDAAAAAL2jwAYeakRQN2U227hJ8loMgzDt4THfJpm1Xyi1nFxetcc05PEjRqsAAAAAMBQKbOBbbkRQv1ciYAuNCAZj2tPj3hTad5Ucz1HKyuyTAf+t3Hq7AAAAANBjJ0kuUu5z/ZHkLIps4O8aEdRPmY03M32xTtlDuxabQnvipYEqzURARa5FAAAAcBCbArtJ8iXJuyiwge8zobQHjBlnG40IqMQyZXX5+0qOZ1Noz2IlMwDf5zsCAABgf06SLFJGiNsuE3gK92x6wMpsttGIgIp8SPJ7RcdznOGu0P7szw0AAACACn1rBbYiG3iqlQjqZ2U222hEQGUW7QnrcSXHc5zkKsYaAwAAAMC+TFNWXy9Sz31BAPbMymy20YhgME4H9G+ZJbmpLNulPzEAAAAA2JlpkvOUfW3/neRjFNnA7qxEUD8rs9lGIwIqdJvyJOYqZe/qGpy1vxcDyhgAAAAADmkaK7CB/bsTQT9Ymc22bkRAhdbtiW1NzlL29R5KvtBXJyKgIisRAAAA/NAkpby2Ahs4FPe/e0KZzbYaEVCpVZK3lR3T+wxndTb0+SIYAAAAqPvafZHkKslfSS6jwAYOx2TSnjBmnG01GdZ+ywzLMmUP7bOKjunywbEBAAAAAKXAnrc/b8QBdMjK7J5QZrOtRgSDMR3o67lo/201PXRxmfJ015X3PQAAAAAjpcAGatSIoB+MGcebenymA/63zZNcV3ZMy/R3717vewAAAACea55yb2wzQlyRDdSkEUE/WJmNNzVDctueJK+THFVyTEcp+3rPYmwJwJi/nwAAAMZg/uDnSBxAxdyv7wllNttqRECP/lZnSb5UdEybQvvEewkOZioCXBwBAAAchAIb6COLD3rCmHG21YiAHlkneVvZMR2l7J096VmO0FevRQAAAAB7sxkhfpvkjyRnUWQD/XEtgv6wMpunuIlygP5YpqzMfF/RMR3nfuR4H5768mQaAAAAABsnSRYpRbb7xECfuffdI1Zm8xSNCAZhNqJ/64ckv1d2TJtCGwAAAABqd5LkIuXe8Jck76LIBvpvJYL+UGbzFI0I6KHz1Dcy5Dhl5Xgf3PkTAgAAABgVBTYA1TBmnKdoREAP3aasRm9S1749Z+3vReX5rZOc+jMCePFnKQAAQM2mKYtCjBAHxmAlgv5QZvMUjQjoqU2hvUp9hfZte6EA7N4k9r+hnu8hAACA2kxTyutFyiRBgLFwr6ZHjBnnKRoR0GPr1LkK+l3qX50NfXUiAgAAAPibacrCinWSfyf5GEU2MD6m6PWIMpunaEQwmBPWsbpK8kuFx3WZegtt73sAAACAfptGgQ2wcSOCfjFmnKdoRDCYk9cxu0hZrXlW2XFdtr+X3vcAAAAAvNAk9yPET8UB8F+NCPpFmc1T3SR5LQZ6bpFS6td2In+R8oSsEScAAAAAPNWmwJ4neSMOgG9qRNAvxozjTc5YzZNcV3ZMR0lWsc8vwBB9FgEAALAHk5SFG1dJ/kqZ/qfIBvi+RgT9oszGm5yxum1P9O8qO67aCm2rxAEAAADqosAGeD73vHtGmc1TNSJgYF9a8wqP6yhl7+xJBcdy68+EHpuJAAAAgAGZp9wzaqLABngu97x7RpnNUzUi6L1TEfzNKsnbCo/ruD22iZcIAAAAYLQ2BfZtkj+SnKUshADgeVYi6Jf/EQFP1IiAAVqmjPV+V9lxbQrtWTwtBgAAADAW8wc/imsARs3KbJ6qEQEDdZ7kU4XHdZzkosP//sqfBsBOeCgJAAD4kVmswAbYt88i6B9lNk/ViIABWyS5rvC4ztqLGQD6ay0CAADgKycpixiaJH9GgQ2wbxYb9JAx4zzHTZLXYmCgX2Sz9gKitguHs/b3wssEAAAA0FsnKfd35nGPFeDQLDboISuzeY5GBL03FcF3bQrtuwqP7SzdlNl3/izo8Q0CAAAAqOH6dLMC+0uSd1FkA3TByuweUmbzHI0Iem8qgh9ap+yhXaPLHL7Q9rQafTURAQAAAB2ZJvkQBTZATdzr7iFjxnmORgSMwLK96Hhf4bFdPjhGAAAAAOowTRkfvkhyLA6A6jQi6B9lNs/hyRXG4kN7EXJW4bFdtO9F70cAF0sAAEB3plFgA/RFI4L+MWac57CnAGOySHJd4XEdJVnlMHsC+4IH8FkKAADcm6ZsUbdO8u8kH6PIBqjdtQj6ycpsnsNKUMZm1v7d17av0abQnu35fdn4EwAAAABGbpKyAnue5I04AHrHQs2esjIbb/hxmongyX/z8yR3FR7bUZKr9oIK+DvvCwAAAF56XblIuffyV5LLKLIB+uZzkrcp9/jpISuzea7rGJ3DuKzbL7s/Kzy217lfoe1hE7jnewoAAICnsgIboP9ukizbn0Yc/abM5rkUZozRKuUJrssKj+04+yu0bS0AAAAADN0iCmyAvvs9ZZrGlSiGw5hxnku5xVgt2y/EGh23x7drHl4BeLmVCAAAoDrzlHsptzFCHKCvrlMWof2U+60hGBArs3ku5RZjtkgyTXJa4bG9aS/CFl4mAAAAgH+YP/g5EgdAL92klNYXMUZ88JTZPJeV2f02FcFOLnxWqXNP3rP298LLBAAAAKDABhgIY8RHSJnNc1mZ3W9TEezkPTBPebCjxougs/bYLnbwv7XycgMAAAA9c5LkPApsgL67TrnPfRXd1Cgps3kuK7OhjC+ZJflS6fF9bL/cl14qRmwWD2QAAACMxUnKpLp5ktfiAOgtY8T5L2U2z+XpFyjWSd4muaz0+DbHtfRSAXTuLlaEAADArimwAYbDGHH+QZnNS1ynzv2C4dCWKaPb31d6fJcppftLJiooYABebp3kVAwAAPBiCmyA4TBGnB9SZvMSPlTg3oeUQvus0uNbpYxbfm6hrYABAAAAujRNKa/Po8AG6Lu7lEVixojzKGU2L6Hc6i+v236cpzwZXOPEgqO8vNAGAAAAOKRpSoG9iAmRAEPwKaXENkacrSmzeQkrs+Gf74lZypNkNY7k3hTaU+9fAAAAoFLTKLABhuQ6pcBexn1pnuGVCHgBqzvhnzaF9l2lx7cptCdP/L9rvLT01IkIAAAAqjdJmXi3TvLvJB+jyAbos7skvyX5OeX+3EUU2TyTMpuX8MED37ZOeXq4Vsd5eqHdeFnpqYkIqIjPUgAA+Pv12iJl1OxfUWADDMGnJP/K3x9SghcxZpyX8CEE33eV5Jf2QqxGx+0xzrxUAAfTiAAAgJGbpIwQnyd5Iw6AQTBGnL1SZvMSPpT6bRo31fftImWEylmlx3fanmAsvFQAAADAniiwAYbnLvcFtoWP7JUym5e6jvE/fTWNMvsQFm3Wp5Ue39mD4/wRJyQAAADAU8xT7jcosAGG41NKgX0lCg5Fmc1LWZ0N2128rVLvgx9nKQ82fPBeBwAAAF5g/uDnSBwAg2CMOJ1SZvNS69S74hRqcZvyJPKq4gu59ymF9tLLxcBMRQAAALBXCmyA4TFGnGoos3kpT+HAdtbtRd2fFR/jZft76b3OgExFQEVWKQ8PAQBA3ymwAYbpU8oI8aUoqIUym5fyRA5sb5Xkbe5L4xpdpqzQXnmvAwAAAA+cpEyeW0SBDTAkN0kuUkrsRhzURpnNS1mt2V+z/LOwZP+W7cXfu4qP8ar9+1BgAwAAwLhtCux5ktfiABiMu5T7wBdxH5jKKbN5KR9y8HTnKaOP31R6fEcpDzrMvMcBAABgdBTYAMNljDi9o8zmpazMhudZpBTGx5Ue36bQnj54n9+4iAUAAIBBUmADDJcx4vSaMptduE69hRzU6jZl5XOTeveZerhC+7Y9Vhe09M1EBFT22Q8AALWYppTXi7i3BzA0xogzGMpsdsGNWXj+e2eWUhjXWmgf577Qhj5yQ4aauHgEAKBr0yiwAYbMGHEGR5nNLqyTnIqhlxcv1PH+OU9yWfExbgptD64AAABA/0yjwAYYMmPEGTRlNrug4OrvhQx1WKaMQv5Y8TG62AUAAID+mKQU2Oeu6QEGyRhxRkOZzS74oISXu0hykuRMFAAAAMAzbArseZI34gAYpM8pi6OuYqEhI6HMZhd8YMJuLFIKbU9MAwAAANtQYAMM301Kgb2MMeKMkDKbXbAyG3Zn1r6nXosCYLAXoD7jAQB4CQU2wPBtxogvk6zEwZgps9kFK7Nht++neXuCciQO2ImZk34q0kSZDQDA82wKbFuUAQyXMeLwFWU2u3Ido5H75lQE1Vq3F6d/igIAAABGbf7gx0PvAMNkjDj8gDKbXfGEEOzWKsnbJJeiAAAAgFFRYAMMnzHisCVlNruyjpW+sGvLlPHIxocBAADAsCmwAcbBGHF4ImU2u+JDF/ZjkWSS5I0oAAAAYFBO2uv+eZLX4gAYLGPE4QWU2ezKWgSwN4uUUTP2pQcYxjmTaTYAAOOlwAYYB2PEYUeU2eyKldn9NI0nwfry/pqnFCBGjcHTnbhowDkTAAAdX5MsosAGGIPrJBcxRhx2RpnNrliZ3U/TKLP7oknZP/uLKODJJiIAAAAObJrkPApsgDG4SSmvL+J+O+ycMptd8YQR7N86ydskl6IAAACA6kxTyutFbBUGMAa/p5TYV6KA/VFms0vXTtRh75btxfF7UQAAAEDnplFgA4yJMeJwYMpsdskHNxzGh/Zi+UwUAM6XAAA4uGkU2ABjYow4dEiZzS6tk5yKAQ7iPMmJi2aAXp4vAQDQP5PcF9jufwGMgzHiUAFlNrtkpVH/zJKsxNDb99sspRR5LQ74oakIAACAZ9gU2PMkb8QBMArGiENllNnskpVGcFi37QX1KsmROOC7piIAAAC2pMAGGB9jxKFiymx2yVNKcHjrlBFnf4gCAAAAnkWBDTBOxohDDyiz2SUrs6EbV0l+SfJRFAAAALC1+YMfE88AxuE6ybL9sUAPekCZzS754IfuXCQ5SXImCoCqNSIAAOiUAhtgfO5yX2BblAc9o8xm16wO7ZepCAZl0b6mp6IAqFYjAgCAg1NgA4zTp5QC2xhx6DFlNrtmdWi/TEUwyAv0VZJjUcB/TUQAAACjM0t56FuBDTAuxojDwCiz2YfzlEJbmQaHd9terK9crMN/+T4CAIBxOMl9gf1aHACjYYw4DJgym31QpkG31ilPoH8RBQAAAAOnwAYYL2PEYQSU2ezLOmWF9qUooLP34FvvQQAAAAZIgQ0wXsaIw8gos9mnZXtx8U4U4D0IwN8uvI2/BwB4mmlKgb2IAhtgbIwRhxH7f//5z3+kwL6t44Zt1Z8DIhi8qyRvxIDPOqjGKsmpGKjc55RtSwCgS9OU1deLuLcEMEbGiANWZnMQ85RC2/7Z0I1FSnHiwh8AAIDaTaPABhizmyQXMUYcaCmzOYSmvQj5UxTQiduUlVVNPFTCeM1SHuoAAADqM40CG2DM7lJWX1/EGHHgK8psDmWV5Nck70UBndgU2qsotAEAAOjeJKXAnsfWWABj9SmlxF6KAvgeZTaH9CGlTLNHJHRjneQ8yaUoADplTBoAMFYKbAA2Y8SvUiZJAvyQMptD2+yf/VoU1Zg6aRiVZcrNg4+iAOjMOm7eAgDjocAGwBhx4NmU2RzabXvx8kUU1ZhGmT02F0lOkpyJAgAAgD1ZRIENMHbGiAMvpsymC+skv8TKUOjSIqXQPhYFAAAAOzJ/8HMkDoBRMkYc2CllNl2xMhS6N4ux/4zHSZKVGAAAYOcU2AAYIw7sjTKbLp3HylDo0mbs/ypuODB8ExEAAMDOKLABSIwRBw5AmU2XblNGHa9c+EBn1ik3H/4UBcDBNCIAAHroJGVhggIbYNxuUsrrpetb4BBeiYCOrdsLIbozE8HorZK8FQPAwbjYBwD64iRlZGyT5EvKdnGKbIDxuUvye5L/SzJN8sG1LXAoVmZTg2V7cfROFNDp+3AW+9gDAACM3UnKJL15ktfiABi1zyn3Da9SJq0CHJwym1qcpxRp9s+G7ixS9hV+IwoAAIBRUWADsGGMOFAVZTY1maeMHTeuCrqzSBk77sEShmYqAgAA+Mc58jxlgYECG2Dc7lJWXy9T7g0CVEOZTU2a9iLqT1FAZ27jwRKGaSoCAAD4b4G9iIeYATBGHOgBZTa1WSX5NcnvsRsxAAAgAElEQVR7URz0QhYealLG/n8RBcBerEUAABz4ul+BDcCGMeJAryizqdGHlCLtVBQHu6iFr62TvE1yKQqAnfO0OwCwb5OU8noRBTYAxogDPabMplabMcf2bILuLFMedjApAQAAoH6TlPsp8yRvxAFAjBEHBkCZTa02+/Yacwzd+pBSaJ+JAgAAoDoKbAC+Zow4MCjKbGq2TvJLko+igE6dJzmJ0XT020QEAAAM6NxWgQ3A135PWYF9JQpgSJTZ1O4ipUSzKhS6c5uyj73R//SZhzEAAOi7ecoe2ApsADauU+6hGyMODNb/+89//iMFajdJsooiYq+fBSJgCyfte/FIFPisgxdbJTkVAxX7nPIwGwDdmj/4cS0GQFLGiF+llNiNOIChszKbPrhNefJ45cINOrVu34t/iAIAAGBvFNgAfIsx4sAovRIBPbFO2bcX6NZVyl72AAAA7M48yTLlgf4/UrZbU2QDcJ3kbZKfUhaZKLKB0bEymz5Zpow5ficK6JS97AEAAF7uJKWYWERxDcA9Y8QBHlBm0zfnKXv32T8burVIMo39XgEAAJ5iU2DPk7wWBwAPGCMO8A3GjNNH8yR3YtipiQh45nvxWgz0yEwEVKQRAQCMxknuV9d9SZk4p8gGIDFGHOBRymz6qEkp0djthTU81W17ku3hEoDnnc8AAMO+zlZgA/Atd0l+S/K/7ffFMuU+GwDfYMw4fbVK8muS96KATq1TVrt+EQUAADBy05SH7xexPRoA//Qppbi2+hrgCZTZ9NmHlBLNnr3QrXXKOKRLUQAAACMzjQIbgO+7Timwl7H6GuBZlNn03TylSDOqC7q1TBmL9E4UAADAwE2jwAbg++5yX2CvxQHwMsps+u62vYA04hi6d55yU+eNKAAAgIGZpNx/OI8CG4BvM0YcYA9eiYABWCf5RQwvciICdmSRMj4JfNbB4+cvAEDdJu01zlWSv1K2VlJkA/DQdcq96Z9SHnpSZAPsmJXZDMVFSklxJopnX6DDLtym7GXfJDkSBz7r4IeflwBAneeM8/bH1CkAvsUYcYADUmYzJOcphbanpKFbm0J7FYU2AABQPwU2ANswRhygA8pshuQ2ZfzXKgo06No65QGTS1EAAACV2hTYprwB8D3XuV+FbcIWQAeU2QyNAg3qsUxZ4fBRFAAAQCXmD348CA/At9ylrL6+iDHiAJ1TZjNEy5Rx4+9EsTX7yLIv9rMHAAC6psAGYBufUkrspSgA6qHMZqjOU/bstX/2dk5EwB4tYj976jAVARVZiQAA9kqBDcA2blIWY1wlacQBUB9lNkO/cF27aIUqzFKKG4U2XZqKAABg0E5SHqadJ3ktDgC+wxhxgB5RZjNkTXsB+6cooHO3KTeVVvGACQAAsDsKbAC2ZYw4QA8psxm6VZJfk7wXBXRuHQ+YAAAAL6fABmBbxogD9JwymzH4kDLi+FQU0LlVkrdJLkUBAAA8wTTJeRTYADzOGHGAAVFmMxab/bNd8H7biQg4oGXKAyZnogBG7i62XgCAH5m21/OLJMfiAOARxogDDJAym7G4bS+Av4jim9xI59AWSSZJ3oiCA5qIgMqsY3IMAHxtGgU2ANszRhxg4JTZjMk6yS9JPooCqrBIGTvuBhWH4m8NAKBO0yiwAdieMeIAI6LMZmwuUkZqG28M3dtMTFjHdAAAABibSe4LbJNKANjG55QR4lcp95UAGAFlNmN0nlJoe9obutek7J+9ikIbAACGblNgz2PLIQC2c5NSYC9jjDjAKCmzGaPb3I83Vp7dm8QTjXRjnfKQyaUoAABgkNeaCmwAnmIzRnyZcg8XgBF7JQJGalOece9EBHRomeRXMQAjPB8BgCGapDxEfpXkr5QHVxXZADzmc5K3Saa5X4wEwMhZmc2YLVMK3HeigCp8aC9W7GkPjIWJKAAMzfzBj0loAGzDGHEAfkiZzdidp+zXa/9sqOc9aU979mkWT3YDAOySAhuApzJGHICtKbOhXHCvXXRDFW5TysZ1ktfiAACAaq+jFdgAPNXnlAL7KiZVAbAlZTaU8TXzJH+KAqpw274nV3FjDAAAajFL2b9UgQ3AUxgjDsCLvBIBJCml2a8jz+DEnwEVWafcKAMAALq9TrxIKR/+THIWRTYA2/k9yf8lmSb5EEU2AM+kzIZ7H1JG3YzVxJ8AlblK8lYMwICtRABAhR4W2F+SvIstgADYznXKvZyfUhYpuOYB4MWMGYe/2+yf7UId6rBMGWd4JgoAANibk9yPEHc9DMBT3KQsSNg8CAUAO6XMhr/b7NX7RRRQjUXKSKpTUbADJ/FkOABA2nPsRfujwAbgqX5PKbGvRAHAPimz4Z/WSX5J8lEUUI15SgF5LApeyJYKAMCYTdtz64VzawCe4TplBfZVyqIgANg7ZTZ820XK6r0xjTZW8FCz29zvtXQkDgAA2No0CmwAns8YcQA6pcyG7ztPKbTHcrF/4iWncuuU/bNtAwAMhZUMAOzLNApsAF7GGHEAqqDMhu+zEhTqs07yNsmlKICBfKYBwK5MUgrseZI34gDgGYwRB6A6ymz4sXXKCm3FGdRjmTJJ4J0oAAAYOQU2AC9ljDgAVVNmw+OWUZxBbc5TbtydiYInmooAAOg5BTYAu2CMOAC9oMyG7Zyn7NVrrzGo63154n3JE01FAAD01CIKbABe5jpl4c4yxogD0BPKbNjePGXs+FD3zz7xEtMztykPmTSxrz0AAMO9Dt38OOcF4Dnucl9gr8UBQN8os2F7TcoNhD8H+u9zY4Q+2hTaK3/DQE9dx4QJAP5OgQ3ALnxKKbCNEQeg116JAJ5kleRXMUBV1ikjxwH6yGg/AJJSXC/b74U/kpxFkQ3A010n+SXJT+13iyIbgN6zMhue7kPKStBTUUA1lkkmST6KAgCAnjhJeSjTCmwAXsIYcQAGTZkNz7PZP/u1KKAaFyk3BM9EwQ9MRAAAdOgkyaK9pnQ9CcBLGCMOwCgos+F5blNuPnwZ2L9rEuNO6bdFyg1C+8/yPf42AIBDU2ADsCvXuV+F7R4eAKNgz2x4vnXKHjRDcuJlZQBm7cUdAAB0eW11kaRJeQj6XRTZADzPXZLfkvz84PtFkQ3AaFiZDS9jrDHU5zZl5csq9h4E6rdKcioGgEGYpqy+Po/iGoCXM0YcAKLMhl04j7HGUJt1yo3EP0UBAMAeTdvzzoVrQgB24CZl8cxVynQPABg9ZTa8nFWgUKdVkrdJLkUBAMAOTaPABmB37lLK64uUh/MBgAeU2bAb65QV2kozqMsyZQ9tWwEAAPASk5TyehEFNgC78SmlxF6KAgC+T5kNu7NMGTf+rsf/hpOU1awwJIuUm49vREFr5rMOANjCJGUF9ty5JAA7Yow4ADyRMht26zylJOnrk/oTLyEDtUgpL62iAWpzKwKA6q6JFNgA7JIx4gDwAsps2L15e2Jq/2yox633JlApN7MAuqfABmAfjBEHgB1QZsPuNSk3Qf4UBVT33pylrNBWaAMAME+Z4KPABmBXjBEHgB17JQLYi1WSX8UA1VmnbAcAAMA4zVNWyN0m+SOKbABe7i7J70l+TjJNKbMbsQDAbliZDfvzIWUV6GmPjtme2YzBsr24fC8KAIBRmD/4MaEHgF0xRhwADkCZDfu12aP3dU+O98RLxkh8SCm0z0QxSicpEzQAgGFfiymwAdi1m5TyehmrrwHgIJTZsF+3KTdPvogCqnOeUmoei2J0TKGgJo0IAHbmJGUP7EUU2ADszl3uV2CvxAEAh6XMhv1bJ/klyUdRQFVuU7YC6NP0BGB4GhEAvMimwJ47pwNgxz6nFNhXKfcQAIAOKLPhMC5SbrIYaQx12UxPWMXqHQCAvlBgA7AvxogDQGWU2XA4RhpDndYpN0P/EAUAQLUU2ADsizHiAFAxZTYczm3KzZdV6l0BeuJlYqSukrxNcikKAIBqTFPK60U8FAzA7hkjDgA9oMyGw1qnrNCutTAzZpkxW6bsoW07gOGbigAAqv6eVmADsC/GiANAzyiz4fCWKSug34kCqrNIuYF6KopBm4qAynz2uQP4blZgA7A3xogDQI8ps6Eb5ykrQN2ogfrM24tb708AgP2ZtOdd5867ANgTY8QBYACU2dCdecrYcaO9oS592N8eAKCPNgX2PMkbcQCwBzcp5fVFjBEHgEFQZkN3mpSbOH9WdlyTeFoV1inTE76IAgDgxdcXCmwA9u33lBL7ShQAMCyvRACdWiX5tbJjOvGyQJJSaL8VAwDAk01SJt1cJfkryWUU2QDs3nV73f7Tg+8dAGBgrMyG7n1IWQF6KgqozjLlAY93ohiUiQiojIkowFBsVmCfiQKAPTFGHABGRpkNddjsn/1aFFCd85Ty003Z4TgWAZVZx4pFoN/XMpufI3EAsCfGiAPASCmzoQ63KTd/7M8LdTpPWaGtBAUAUGADcBjXKSuwr2KaEQCMljIb6rFO8kuSj6KA6tymbAfQxA1bAGCcFNgAHIIx4gDA3yizoS4XKas/uxxnfJJk5aWAf9gU2qu4gQsAjMNJkkVKgW1LJAD2yRhxAOCblNlQn67HGU+8BPBd65Qbun+IAgAYKAU2AIdijDgA8ChlNtTnNuXm0SpWf0KNrmJLAGC3GhEAHVNgA3Aod0mW7c9aHADAY16JAKq0TlmhDdTpImUEGv01EwEVaUQAdGCa+/1IvyR5F0U2APvzKcm/UiYCnkeRDQBsycpsqNcyZYXEO1FAlRbpdksAAICnmqasvl44hwHgAK5zvwrbGHEA4FmU2VC385TVg4e80WTPbNjeLGVLADeDAYBaTaPABuBwjBEHAHZKmQ31m7cn/4faP/tE5LA1e9wDADWaRoENwGF9Simwr0QBAOySMhvq16TciPpTFFCltfcoAFCBSe4L7FNxAHAAxogDAHv3SgTQC6skv4oBqn6PvhUD8EzGLwLPNUkpr6+S/JXkMopsAPbrLslvSX5Ome53EUU2ALBHVmZDf3xI2Z/XzSmo07K9kH8nil44SXkIAWrg5h/wFJsV2PMkb8QBwIEYIw4AdEKZDf2y2T/7tSigSucpe1S6sVy/iQgA6Nn3lgIbgEMzRhwA6JwyG/rlNuUG1pc9/jdOxAwvskhZ8XssCgDgheYPfo7EAcAB3KWsvr6I7XAAgAoos6F/1kl+SfJxT//7bpLBy2weOll7PwEAz6DABqALn1JK7KUoAICaKLOhny5SVlCfiQKq1KTscb+Km9DAdu58XsCoKbAB6MJNyj2mq/Y6FgCgOq9EAL11nrJ3EVCndfs+Bdj2MwMYl1nu9yD9I+VBVUU2APt2l+T3JD8nmaaU2Y1YAIBaWZkN/XWb+7153fSCOi1Tbg68F0V1piIAoAMn7Tn8PMlrcQBwQMaIAwC9pMyGftus/Lzc8f/uJKUsB17uQ0pxaluAukxFAMCBKLAB6Iox4gBA7ymzof+WKTfI3u3wf/MkZcU3sBuL9n11LAoAGAUFNgBduUspry9iKxsAYACU2TAM5yl77inKoF6zlBsJbmgDwDBNUwrshe97ADpgjDgAMEjKbBiOeUpRZv9sqNNt+z5deZ8C39AkORUD9M60/X5fxIOlAByeMeIAwOAps2E4mpQbaX+KAqq1TrnZ/YcogG98jwP9MI0CG4DubMaIL2OLOABgBJTZMCyrJL8meS8KqNZVkrdJLkXRqYkIAHiCaRTYAHTrc0qBfZUy+QsAYBSU2TA8H1L25n3JqNKTeLoX9mnZvk/PRNEZRQQAj5mkFNjzJG/EAUAHbtrrx2VM8gEARkqZDcO02T/79TP/761YhP1bpKzyskcuANRDgQ1A14wRBwB4QJkNw3SbcgPuiyigavOUmxNWCQNAdxTYANTAGHEAgG9QZsNwrZP8kuSjKKBamwdP1kmOxAGj/94GDmsRBTYA3TJGHADgEcpsGLaLlP2v7csL9WpS9s82SQHGzeobOIz5gx8PkgHQBWPEAQCeQJkNw3eeUmg/ZYyxPbPhsNZJ3ia5FAUA7JwCG4AaGCMOAPAMymwYvtuUEYr/n727PW7kSrMEfGpj/4trgbgWiLKAlAVTbQFRFlTJAlVbILQFBC0QaUGBFhRgwQAWDGEB98cFl/VBAiCIj5s3nydC0RM9My3mi1bxIk++J8fZ/ObdmbHBwY2W/+x9NIqDuYhNCIBWCbABqIEacQCANxJmQz9MUja0bX1C3T6lNCN4NQAAvN7Z8nepABuAY7uOGnEAWOc0HvZiA8Js6I9RbH1CF2zzagCg+1RNwnbOUlqI3if51TgAOKJpkmHUiAPAKifL73CD5e/LCyNhHWE29Mun5S8HIRnU6/EQN4utMuiTiRHAxgTYANRinhJeD2OzDABWeb/8Hvdf3/x718bCJoTZ0M9fGpMIyaBmj4H22D+rAJBEgA1AXa5TQuwbowCAtd/jBnn+HufMiNiEMBv6Z5ZyE/DLml8ywHFNlge9f4wCgJ46XZ5bP0WADcDxqREHgPW+rRFf1xA7Ni428b+MAHppnOTfK/73NkGhDjdJ/jSGvfHgDkB9TlPC60mS/07ydwTZABzPPMl/kvzf5feHUQTZAPCc9yn3Mv9n+T1uk1edzoyNTdjMhv76nFJjfG4UULVhyk2TS6PYuRMjAKjCaZ7en/abcQBQATXiALDeuhrxdWZGyCaE2dBvj+/Ptu0CdRssD4du8EPb5n4n0yOnEWADUBc14gCw3mtqxFe5M0o2JcyGfrtPuYn41Sigehcprwhwwx/aNYswm7adLM+e75P8l3EAUIF5Sng9jO0wAFjl8WHkXX2X8+AYGxNmA5OUd/L+/cO/f+IXClTlfnlgHMd77QHoDgE2ADW6TXn/tRpxAHjZW2vEV5kYL5sSZgPJ8+/kPUsJzYB6TFLCgC9GAUDFBNgA1GiaEmCP4uF9AFj1fW6Q/b8SSpjNxoTZwKNP8U5e6IJxkg9JroxiJ4dzAHZn17VzAPBWizwF2G6aA0A93+dmRs6mhNnAIxXG0B2jlIdPPhrFm5wZAcCbvf/mL2dIAGqhRhwA1ttnjfg6HjJjY8Js4MdfIJ9i4xO64FOS09h+g9Z+D58bAx0gwAagRmrEAWC9Q9WIr/udDRsTZgM/GsW2InTFIKVNwesBoA1uulIzATYANVIjDgCbf6cbpI7FmJmPg9cQZgPPedz4BOp2vzyITiJYAGD3jlk5BwCrqBEHgO5+p/MAGq8izAZeMjMC6Mw/qxfxvnsAdus8yVdjAKAiasQBYL0aasTXmfmYeA1hNgB0n/fdAwAALVIjDgCbqalGfJ2Zj4vXEGYDQBtGKa8H+MsoNnZuBAAAUCU14gCwXldfDTX20fEa7x4eHkwBANoxSnJpDJufhYyAilwk+WIMAEBPzZMMUwLsmXEAwLO6UCO+7vf9qY+R17CZDQBtGaQ8lfmbUQAAAJVbpITXw6gRB4BVulQjvsrMR8lrCbMBoD0XKTeCfjUKAACgQrcpIfbIKADgRV2tEV9l7GPltYTZANCe+5SnNccNHXQBAIBuUyMOAOt1vUZ8HWcAXk2YDQBtmiwPvf8YBQAAcCRqxAFgM63UiK8z81HzWu8eHh5MAQDaNUhyZQwv+j1uqlGP0yT/bQwAQAPUiAPAei3WiK/zf1JaJWFjNrMBoG2jlHdoXxrFs06MgIrMjAAA6DA14gCwXus14qssIshmC8JsAGjfIGXj89woAACAHVIjDgCb6UuN+CrOCmxFmA0A/Tkwj9O/Jz4BAIDdu0tpgRoZBQC8qI814qsIs9mKMBsA+uE+JdCeODwDAABbmOcpwJ4ZBwA8q8814us4P7AVYTYA9OvAeJHkq1EAAAAbeKwRH6U0PQEAz1Mjvp7NbLYizAaA/h0aPyS5Mook5V3iUJNpPLkNABzfY434TUrLEwDwMzXirzMzArYhzAaA/hktD9sfjUKYTXXcLAYAjkWNOACsp0Z8e84XbEWYDQD99Gl5+L40CgAA6C014gCwGTXib3NnBGxLmA0A/fUpZUPbU6QAANAvasQBYD014rszMwK2JcwGgP66T3KxPEw6kAMAQNvUiAPAemrE98PZg60JswGg3x4D7XEE2gAA0Bo14gCwGTXi++UcwtaE2QDAZHlY/6eH137i46fCL3fnxgAAvJEacQBYT4344cyMgG0JswGApNzk+jPJ3z380gIAAC2YL8/1w7hhDAAvUSN+HM4mbE2YDQA8GqaEu5dGAQAAnXGdEmLfGAUAvEiN+PFMjYC3EGYDAN8aJDmNmmMAAKjZNOVhVDXiAPAyNeJ1mBkBbyHMBgB+9D7lvb2qlgAAoB5qxAFgPTXi9ZkYAW8hzAYAfnS/PPCP46lVOLSZEQAAP1AjDgDrqRGvlzCbNxFmAwAvHTLfJ/liFHBQMyMAAKJGHAA2oUa8G2ZGwFu8e3h4MAUA4CWDJFetn4d8zFTkIh4iAYC+UiMOAOupEe8e9954E5vZAMAqo5SnXD8aBQAA7IUacQBYT414N02NgLcSZgMA63xKcurLAgAA7IwacQBYT4149znn8GbCbABgE4Mk46hvAgCAbS1Smo9GSSbGAQDPUiPelrER8FbCbABgE/cp7/KdxZOwsE9ubANAe25TAmw14gDwMjXibZoZAW8lzAYANvUYaI8j0IZ9/nMGAHTfNE9b2H6/A8Dz1Ii3b2YEvNW7h4cHUwAAXmOQ5Kqh6/k9tmGpiwM6AHSTGnEAWE+NeL+8MwLeymY2APBaoySnSf5q6EsUAABsS404AKynRrx/5kbALgizAYBtfE4JtC+NAgCAHlIjDgDrqRHvt5kRsAvCbABgW4PllxKVUAAA9IEacQBYT404j5yX2AlhNgDwFhfLg+mvRgE7c5fk3BgAoBpqxAFgPTXi/GhmBOyCMBsAeIv75ZeVcdRFAQDQjnmSYdSIA8AqasRZxWY2OyHMBgB2cTB9n+RLR3/+Ux8hAAApNeI3KSG2m68A8Dw14mzKeYqdEGYDALswTvIhyVUHf/ZTHx8AQK/dpoTYI6MAgBepEec1FtFuw44IswGAXRmlvEP70igAAKjcY434TbzPEQBeokacbdnKZmeE2QDALg1SNp3PjQK25sllANgPNeIAsJ4acXbBWYudEWYDALv2PqV23Bce2P4Ln9o2ANgdNeIAsJ4acXbJg/rsjDAbANjHYfV9SiCnggoAgGNQIw4A66kRZ1/GRsCuCLMBgH2Ypbw/+2sHftYTHxcAQBPUiAPAemrEOYSZEbArwmwAYF8mST4kuar85zzzUQEAdJoacQBYT404hzQzAnZFmA0A7NMoyWmSv4wCAIAdUiMOAOupEecY7oyAXRJmAwD79jkl0L40CtiIWlQAeN5jjfgo3sMIAC9RI86xzYyAXRJmAwCH8CnlaWBfomC9eyMAgO/cpQTYN35PAsCL1IhTi5kRsEvCbADgEO6TXCwPs2qtAABYZ54SYI/ihigAvESNODUaGwG7JMwGAA7lMdAe+4IFAMAz1IgDwHpqxKmdJh126t3Dw4MpAACH9D7JP7WdiXwsVOQiyRdjAKBH1IgDwHpqxOkK99nYKZvZAMCh3ST5M8nfRgEA0FtqxAFgPTXidM3UCNg1YTYAcAzD5ReyS6OAn4yNAIBGqREHgPXUiNNlMyNg14TZAMCxDJKcJjk3CgCApqkRB4D11IjTgokRsGvCbADg2F/UxvGkMQBAa9SIA8B6asRpjTCbnRNmAwDHdL/8wjb2pQ0AoAnXKRvYN0YBAM9SI07LtPCwc+8eHh5MAQA4toskX4749/89nhylLg7pAHTJNMkwasQBYBU14vTBOyNg12xmAwA1GCf5kOTqSH//Ex8BlVlEWwEAdZunhNfDqBEHgJeoEadv50PYOWE2AFCL0fJL3kejgEySnBsDABVSIw4Aq6kRp69mRsA+CLMBgJp8SnIalVsAADVRIw4A66kRp+/GRsA+CLMBgNoMlodfTy8DAByPGnEAWE+NODxxZmQvhNkAQG3uk1wsD8C+CAIAHJYacQBYTY04PG9mBOyDMBsAqNFjoD3OYQLtUyMHAHpMjTgArKdGHFYbGwH7IMwGAGo1SXmH9tUB/l6nxk1lZknOjQGAPVIjDgDrqRGHzSyMgH0RZgMANRulBM1/GQU9MzMCAPbkdnnGUiMOAM9TIw6vNzEC9kWYDQDU7nNKoH1pFAAAW5mmBNijqBEHgJeoEYftCbPZG2E2ANAFg5RqL09EAwBsZpGnANvNRQB4nhpx2I2ZEbAvwmwAoCsuUm7E/moUAAAvUiMOAKupEYfd8/AkeyPMBgC64j6l8muc3T8tfWK8AECHqREHgPXUiMP+CLPZm3cPDw+mAAB0yUWSLzv+z7xb/udCy/89B6AtasQBYD014nCYc6lFEfbGZjYA0DXjJB+SXBkFANBDasQBYDU14nBYHqxkr4TZAEAXjVI2Vy+NAgDoATXiALCeGnE4jpkRsE/CbACgqwZJTpOcGwUA0CA14gCwnhpxOL6ZEbBPwmwAoMvep9SOqw0DAFpxm1IhPjIKAHiWGnGoy9gI2CdhNgDQZfcpgfYknsCmvf9uA9Af8yTDlBB7ZhwA8Cw14lAn51f26t3Dw4MpAABdd5bk61vPRcZIZRzUAdq2SAmvh1EjDgCrvu8PokYcauaeGntlMxsAaMEkyYckV0YBAFROjTgArKZGHLrjzgjYN2E2ANCKUZLTJH8ZBQBQGTXiALCeGnHoHmdb9k6YDQC05HNKoH1pFADAkakRB4D11IhDt82MgH0TZgMArfm0/DKsigwAOAY14gCwmhpxaIeHNtk7YTYA0Jr7JBfLw/SvxkGHzf13GKBTf2arEQeA1dSIQ3ucfdm7dw8PD6YAALToLMk4m9eU/R5Pk1KXcZJzYwColhpxANjsu/kgasShVe+MgH2zmQ0AtGqy/LL8z4b/9ydGBgBs4C6lQnxkFADw4vfrQdSIQ+umRsAhCLMBgDVtZ8AAACAASURBVJbdJPkzyd9GAQC8wTxPAfbMOADgWWrEoV+cizkIYTYA0LphSq3ZpVEAAK/wWCM+Snn1AwDwMzXi0F9etcNBCLMBgD4YJDmN9w8DAOs91ojfJLk3DgD4iRpxILGZzYEIswGAvnifslXlizZdMY4HMAAORY04AGz2vXoQNeJA4dzMQQizAYC+uF9+6R7n+eqzUyMCgF5RIw4A66kRB17iDM1BCLMBgD6ZJLlI8vWZ/92p8QBAL6gRB4DV1IgD68yNgEMRZgMAfTNJ8iHJlVEAQG+oEQeA9dSIA5typuZghNkAQB+NUqrSPhoFADRLjTgArKdGHNiG8zUHI8wGAPrqU0q1uCfOqZXqW4DtTJMMo0YcAF6iRhx4q5kRcCjCbACgzwYpT5L68k6NJkYAsLF5Sng9jBtrAPASNeLArjhzczDCbACgz+6TXCwP4CfGAQCdc50SYt8YBQA8S404sA8ewOdghNkAQN89BtqfjQIAOkGNOACspkYc2KeFcziHJMwGAChPk34yBgColhpxAFhPjThwCLayOShhNgBAMTMCAKiOGnEAWE2NOHAoizw9YAoHI8wGAIA6zYwA6Ck14gCwmhpx4JDmy/P5yPmcY3j38PBgCgAAUCeHdaAv1IgDwHpqxIFDuk4JsMdGwTHZzAYAAACORY04AKymRhw4JFvYVEeYDQAAABzSNOXm2ChukAHAc9SIA4dmC5tqCbMBAACAfVvkKcCeGAcAPEuNOHBI82/O6DPjoFbCbAAAAGBfblNujqkRB4DnqREHnNFhBWE2AADUaxq1gkA3/+waRY04ALxEjThwaLaw6SxhNgAA1EsIBHSFGnEAWE+NOHBod0mGsYVNhwmzAQAAgG2pKASA1dSIA4f2+KDpMLawaYAwGwAAAHgNNeIAsJoaceAY7r45p0MzhNkAAADAOmrEAWA9NeLAsc7ptrBpljAbAADqZeMRODY14gCwmhpx4BhsYdMbwmwAAKjXJLY6gMObp2x2jOKhGgB4jhpx4BgWKQ+ZDqMtiR4RZgMAAABujAHAemrEgWOYLs/pN/GwKT0kzAYAAID+uk25KTYyCgB4lhpx4Bg8bApLwmwAAADol8ca8ZskM+MAgJ+oEQeOeVb/HFvY8P8JswEAAKB9NjsAYD014sCxXKe0JY2NAr4nzAYAgHrNjAB4IzXiALCaGnHgWB4bk0axhQ0vEmYDAEC9ZkYAbEGNOACspkYcOCZb2PAKwmwAAADoPjXiALCeGnHgWGxhw5aE2QAAANBdasQBYDU14sCxz+uj5Zkd2IIwGwAAALplnnJDbBQ14gDwHDXigPM6NEKYDQAAAPV7rBEfxbv1AOAlasSBY7KFDXvw7uHhwRQAAKBOJ0n+xxig1+7ydEPMu/UA4GdqxIFjWuTpXdgz44DdE2YDAEDdHNihf9QSAsBqasSBY7v75swO7JGacQAAADg+NeIAsJ4aceDYZ/ZRyib2zDjgMITZAAAAcDxqxAFgNTXiQC1n9pFRwOEJswEAAOCw1IgDwGpqxIFje2xO+uzMDsclzAYAAID9UyMOAOupEQeObZpSI645CSohzAYAgLrdJTk3Buj0P8OjuBkGAC9RIw4c2+ODp8MkE+OAugizAQAAYLfUiAPAamrEgRrYwoYOEGYDAADAblyn3Ai7MQoAeJYacaCWc7stbOgIYTYAAABszzYHAKymRhyowXx5bh85t0O3CLMBAADgdeZ5eqfezDgA4CdqxIFaXKcE2GOjgG4SZgMAQN1mSc6NAaqgRhwAVlMjDtTAFjY0RJgNAAB1mxkBHJUacQBYTY04UIvb5dl9bBTQDmE2AAAAfE+NOACspkYcqOnsPlr+5ewODRJmAwAAQKFGHABWUyMO1OI2JcB2dofGCbMBAADoMzXiALCaGnGgFrawoYeE2QAAAPTNIuUGmBpxAHieGnGgJnd5egAV6BlhNgAA1G1iBLAzqggBYDU14kAtPIAKJBFmAwBA7dQew9tM81RF6J8nAPiZGnGgJnffnN8BhNkAAAA053GLYxTtBgDwHDXiQI3nd1vYwE+E2QAAALRCjTgArKZGHKjJNCXAHhkF8BJhNgAAAF2mRhwAVlMjDtRkkfLw6TBalIANCLMBAADoGjXiALCaGnGgNo9b2DfxECrwCu8eHh5MAQAA6ubQDoUacQBYTY04UBNb2MCb2cwGAACgZmrEAWA1NeJAbeZ5ehe2MzzwJsJsAAAAaqNGHABWUyMO1Oh6eYYfGwWwK8JsAAAAanGbUkM4MgoAeJYacaA2trCBvRJmAwAAcEyPN79uksyMAwB+okYcqJEtbOAghNkAAFC/eZJfjYGGLFLC62HUiAPAc9SIA7V+Nx0tz/G2sIGDEGYDAED9ZhFm0wY14gCwmhpxoNZz/Gh5lgc4KGE2AAAA+6RGHABWUyMO1HqOHy3/co4HjkaYDQAAwK6pEQeA1dSIA7WyhQ1URZgNAADArqgRB4DV1IgDNVrk6V3YM+MAaiLMBgAA4C3UiAPAamrEgVrd5alKHKBKwmwAAKjfJMm5MVARNeIAsJoacaDms/wotrCBjhBmAwBA/e6NgEo8bm7c+O8lADxLjThQ+1l+ZBRAlwizAQAAWGWep5teM+MAgJ+oEQdq9dio9NlZHugqYTYAAAA/erzpNUoyNg4A+IkacaBm05QacY1KQOcJswEAAHikRhwAVlMjDtTq8YHUYZKJcQCtEGYDAAD0mxpxAFhNjThQM1vYQNPePTw8mAIAANTtIskXY2CH1IgDwGpqxIHaXTvPA31gMxsAAKA/1IgDwGpqxIGazVO2sEfO80BfCLMBAADapkYcAFZTIw7UzhY20FvCbAAAgDa54QUAL1MjDtTOFjZAhNkAAAAtmabc8FIjDgDPUyMO1O42T68GAug9YTYAANRPKMkq85QbXcOoEQeA56gRB7pwph/Fq4EAfvLu4eHBFAAAoH4O7vzoOiXEtrEBAD9TIw50gS1sgDVsZgMAAHSHGnEAWE2NOFA7W9gAryDMBgAAqJsacQBYTY040AV3eQqxAdiQMBuALjtZ/qvNNABapEYcAFZ/HxxEjThQt0VKeO3BVIAtCbMB6LJvn74HgBaoEQeA1dSIA11gCxtgR4TZAHTZfZLL5b9+Mg6gcdPYOmqVGnEAWE2NONAFtrAB9kCYDUCXTZb/+nH5P4+MBGiYLd32qBEHgJepEQe6QrsSwB4JswFoxVXKU69jowCgYtM81Q260QUAP1MjDnTBIk/tShPjANgfYTYALblJcuFLBACVeawbHPkdBQDPUiMOdIUtbIADE2YD0JJfUoKCC18oAKjA7fL3khpxAPiZGnGgK2xhAxyRMBuAFr5QfPvk/m8pVeNnRgPAEagRB4DV1IgDXTFPCbCd7QGOSJgNQNdNkpz/8O/9tvyiMTAeoCHjZ/68ow5qxAFgNTXiQJdcL8/2Y6MAOD5hNgCtukwyS/LZKADYEzXiAPAyNeJAl9jCBqiUMBuAlv2VEmiPjAKAHVEjDgCrqREHusQWNkDlhNkAtG6YUvmq9hWAbakRB4DV1IgDXTL/5nw/Mw6AugmzAei6dVtxv6Q8XXvmCwoAr6RGHABepkYccL4HYO+E2QB03STr6+t+WX5RuYhKWKC7/Pl1GI/vyruJh6AA4DlqxIGune9HsYUN0FnCbAD64rc8BdoAXaTeen8Wy98RQ3MGgGepEQe65i5PD6kC0GHCbAD65DzlSdyBUQCQUjN4s/zdAAB8T4040DWL5dl+GFvYAM0QZgPQN5cp79AeGQVAL6kRB4DV1IgDXXOXpypxABojzAag67Z5h+zV8v9P1RRAP6gRB4DV1IgDXTzjj2ILG6B5wmwAum7bUGKU8v5soQZAu9SIA8DL1IgDXWQLG6BnhNkA9NUvKXXjp9luuxvg0Dx8sxk14gCwmhpxoGs0LQH0mDAbgD57DLQvItAG6ufPqZe5uQUAq6kRB7pomqcHVX0fAugpYTYAfffb8ovRwCgAOkeNOAC8TI040EUeVAXgO8JsALpuF0/mXi7/cz4ZJ0D15nl6R97MOADgJ2rEga6e8z/HFjYAP3j38PBgCgB03a5+mX2I7T6gH3/edc3jdsYo5fUQAMD31IgDXXXtnA/AKsJsAFqwy19mf/gCBfTkz7suuEu5sWU7AwB+pkYc6Kp5So34yDkfgHWE2QC0YJe/zBZJLuK9TECdxknOG79GNeIAsJoacaCrbGED8GremQ0A3/tl+cXqIp4OBjgUNeIAsJoacaCrbGED8CbCbABasMhub+j8lhKmnBktwF6pEQeAl6kRB7rs9puzPgBsTZgNQAsm2X3t7m/LL10D4wXYKTXiALCaGnHAWR8AloTZAPCyy+WXr89GAfAmasQBYDU14kCX2cIGYG+E2QCw2l8pgfbIKIAKdK2KW404ALxMjTjQZYs8vQt7ZhwA7IswGwDWG6ZUmU+MAjiySeqvHJ2nhNfDuKkFAM9RIw502eMDqyOjAOAQhNkAtGDf236/pNTinkUwA/CS65QQW7UgAPxMjTjQZYuU8NoDqwAcnDAbgBYcYlPxl5SA5iKqcgEeTVNuaKkRB4CfqREHus4WNgBHJ8wGgM39lqdAG6Cv1IgDwGpqxIEuWyzP+5+d9wGogTAbAF7nPOWJ5IFRAD2jRhwAXqZGHOg6rUsAVEmYDQCvd5nyDu2RUQAHNjvw388NLQB4mRpxoOset7CHKa9wA4DqCLMBaMExApar5d/XhiJwSLMD/D3UiAPAamrEga7z0CoAnSHMBqAFx3p6eJTy/mxPLwMtUCMOAC9TIw60cua3hQ1ApwizAWB7v6TUjZ/Gk8xAN9nIAICXqREHWjBfnvlHzvwAdJEwGwDe5jHQvvClEOiIRcqNLDXiAPA8NeJAC66X5/6xUQDQZcJsAHi731JCoYFRABW7TbmZpUYcAH6mRhxogS1sAJojzAagBTV8Qbtc/hyffBzAHo1f+X8/TbmRNYqbWQDwIzXiQCtuU0LssVEA0Jp3Dw8PpgBAC2r5hfYhJTQCONafd4814qMkE+MCgJ+oEQdaMP/m3D8zDgBaJcwGoBU1/UL7I56GBg7/550acQB4mRpxoBXO/QD0ijAbgFbU9AttkeQiNiKB/f95p0YcAF6mRhxohS1sAHpLmA1AK2r7hTZNCbSFS8Cu3UeNOACsokYcaMVdyruwbWED0FvCbABacZ/66gKnKXWGAADAfqkRB1qxSHlwdRhb2AAgzAagGeMk5xX+XNcpN9QAAIDdUiMOtOQuTw1MAMDS/zYCANiry5QnqT8bBQAA7IQacaAVtrABYA1hNgDs31/LL6UjowAAgK2oEQdaMk0JsEdGAQCrCbMB4DCGSSbLvwAAgPXUiAMtWSS5ydP9AQBgA8JsAFpxX/nP90vKe73PojoMAABWUSMOtORxC/sm9d+7AIDqCLMBaMUk9d/s+mX55fXCF1gAAPiOGnGgJbawAWBHhNkAcFi/5SnQBgCAPlMjDrRmnqd3YXuIHQB2QJgNAId3vvxiOzAKAAB6SI040Jrr5ff8sVEAwG4JswHgOC6XX3JHRgEAQA+oEQdaYwsbAA5AmA1AK7r4xfFq+XPf+PgAAGiQGnGgRbawAeCA3j08PJgCAC04S/K1gz/3IuX92RMfIQAAjVAjDrRmnhJgD2MLGwAOSpgNQEuGST528OdeJDn1hRgAgA5TIw606DYlxNaoBgBHIswGoDXjJOcd/LmnKRvaAm0AALpCjTjQosct7FGSmXEAwHEJswFozUlKZfevHfzZb1MqGQEAoGZqxIEW2cIGgAoJswFoUVffn50k/0nyyUcIAECFZ+xB1IgDbVnk6V3YM+MAgPoIswFo1SDJVUd/9g/LL9MAAHBMasSBVt3lqUocAKiYMBuAlo2SXHb0Z/8j5f3fAABwaGrEgRbZwgaADhJmA9C6Sbq5RbJIcrH8+QEAYN/UiAOtsoUNAB0mzAagdScpT1x38YbcPOWm4r2PEQCAPZ2VB1EjDrRnkeQmyefYwgaAThNmA9AHZ0m+dvRnny5/fgAA2BU14kCrpik14jfxYDgANEGYDUBfDJJcdfRnv17+/AAAsC014kCrHrewh/GqLgBojjAbgD4ZJbns6M/+75R6NAAA2JQacaBltrABoAeE2QD0yUmScbp7I+9DSiAPAACrqBEHWna9/G48NgoAaJ8wG4C+OU2pHetqteLvUZsGAMDP1IgDLZunbGGPYgsbAHpFmA1AH10k+dLRn32RcqNy5mMEAOg9NeJA62xhA0DPCbMB6KtPSf7u6M8+TQnkPY0OANBPasSBltnCBgD+P2E2AH02SnLZ0Z/9LiXQBgCgH9SIA627XX5PvzEKAOCRMBuAPjtJqSrraiXjdcrNTAAA2j2vDqJGHGjXPCXAHsXrtACAZwizAei7s5RAu6vbLX+m1K8BANAONeJA62xhAwAbEWYDQLlZ+E+Hf/5/uQEAANB5asSB1tnCBgBeTZgNAMXnJH919GdfpLw/e+JjBADoFDXiQB/c5SnEBgB4FWE2ADy5SXerHBdJTpPc+xgBAKqnRhxo3SIlvB7GFjYA8AbCbAB4cpLy/uyubsVMUza0BdoAAPVRIw70gS1sAGCnhNkA8L2zlEC7qzcYb1M2fQAAOD414kAf2MIGAPZGmA0APxskuerwz/+fJJ98jAAAR6NGHOiDaUqAfRMNYQDAngizAeB5wyQfO/zzf4haNwCAQ1IjDvTBIiW8HiaZGAcAsG/CbAB42TjJeYd//j+W1wAAwH6oEQf6whY2AHAUwmwAeNlJypPmv3b0518kuYin5QEAdk2NONAHtrABgKMTZgPAamcp281drYqcL6/Bk/MAAG8/Fw6iRhxo3zwlwB75LgkAHJswGwDWGyS56vDPP025+QoAwOuoEQf65DolwB4bBQBQC2E2AGxmmORjh3/+65SbsAAArKdGHOgLW9gAQNWE2QCwuUm6vZHz7ySffYwAAM9SIw70iS1sAKAThNkAsLmTJLN0++bmh5QbFgAAqBEH+mW+/D44Wn63BQConjAbAF7nLMnXjl/D7ylb5gAAfaVGHOiT25QA+8YoAICuEWYDwOsNklx1+OdfpITyMx8lANAjasSBPrGFDQA0QZgNANsZJbns8M8/TXKR5N5HCQA0TI040Dd3SYaxhQ0ANEKYDQDbm6TbN0XvUgJtAIDWqBEH+mSR8sD1MLawAYDGCLMBYHunKYF2l2sqr1Nu9AIAdJ0acaBv7vJUJQ4A0CRhNgC8zUWSLx2/hj9TnuAHAOgaNeJA39jCBgB6RZgNAG/3KcnfHb+Gf8U71QCA7lAjDvSNLWwAoJeE2QCwG6Mklx3++RcpW+YTHyUAUCk14kDfLFIeOh76rgYA9JUwGwB24yTJON2ut1ykvAf83scJAFR0xhpEjTjQL9OUAPvG9zMAoO+E2QCwO6cpT8t3eVNomrKh7YYJAHBMasSBvrGFDQDwDGE2AOzW+yT/dPwabpfXAQBwSGrEgT6aJ/kcW9gAAM8SZgPA7n1O8lfHr+E/ST75KAGAPVMjDvTVdZJRyuuqAAB4gTAbAPbjJt2vxfyQcnMFAGDX1IgDfTRPqREfxRY2AMBGhNkAsB8nKU/Yd33D6I/YFAAAdkONONBXtrABALYkzAaA/TlLuVnR5Zu1iyQXSSY+TgBgC2rEgb6yhQ0AsAPCbADYr/dJ/un4NcxTgnk3YACA15yBBlEjDvTPbUqAfWMUAABvJ8wGgP37nOSvjl/DNCXQBgB4iRpxoK/mKQH2KMnMOAAAdkeYDQCHMU5y3vFruE65OQ0A8EiNONBntrABAPZMmA0Ah3GS8t7pXzt+Hf9O2TQHAPpNjTjQV4s8vQt7ZhwAAPslzAaAwzlL2dDueu3mh5QbNwBA/84yg6gRB/rpLk9V4gAAHIgwGwAOa5DkqoHr+D1l0xwAaJsacaDPFinh9TC2sAEAjkKYDQCHN0zysePXsEjZzpr5OAGgSWrEgT6zhQ0AUAlhNgAcxzjJecevYZrkIsm9jxMAmqBGHOizRZKbJJ/joV0AgGoIswHgOE5SbpB0/UbxXUqgDQB090wyiBpxoL+mKe1ZN/GgLgBAdYTZAHA8Z0m+NnAd1yk3wAGA7lAjDvTZ4xb2MMnEOAAA6iXMBoDjGiS5auA6/ky5EQQA1EuNONB3trABADpGmA0AxzdKctnAdfwr5aYQAFAPNeIApU3KFjYAQAcJswGgDpN0/wbzIuX92W4QAcDxqREH+m6eEmCPYgsbAKCzhNkAUIeTJLN0v/JzkeQ0bhYBwDGoEQcoW9ijJGOjAADoPmE2ANTjLMnXBq5jmrKhLdAGgP1TIw5gCxsAoFnCbACoy6ckfzdwHbcp9aYAwH6oEQco3zuGsYUNANAsYTYA1GeU5LKB67hOuckOAOyGGnGAsoU9Wv41Mw4AgLYJswGgPicpmwUtVIV+SLnJBABsfy4YRI04wO3yu8WNUQAA9IcwGwDqdJpkkja2rv6I2j8AeC014gC2sAEAek+YDQD1ukjypYHrWCyvZeIjBYCV1IgDFHcp78K2hQ0A0HPCbACo26ckfzdwHfOUG/T3PlIA+I4acYBikbKBPYwtbAAAloTZAFC/m7RRMTpN2dAWaAOAGnGAR3d5qhIHAIDvCLMBoH4nKe+cbmFb6zrlxj0A9JEacYDCFjYAABsRZgNAN5ylBNot3Pj+d5LPPlIAekKNOMCTaUqAPTIKAAA2IcwGgO54n+SfRq7lQ9zAAqD939uDqBEHWKS8OmmYZGIcAAC8hjAbALrlc5K/GrmW3+NmFgBtUSMO8ORxC/smyb1xAACwDWE2AHTPTdrY8lokuYhAG4BuUyMO8P0Z3xY2AAA7I8wGgO45Sbkx9GsD1zJNCbRtagDQNWrEAZ7M8/QubGd7AAB2RpgNAN10lmScNipM71ICbQDowu/fQdSIAzy6Tgmwx0YBAMA+CLMBoLsGSa4auZbr5fUAQG3UiAN8zxY2AAAHI8wGgG4bJvnYyLX8ubweAKiBGnGA79nCBgDg4ITZANB94yTnjVzLh5QbZABwDGrEAb43X57Ph7GFDQDAEQizAaD7TpJMkvzawLUsUt6fPfGxAnDA36ODqBEH+NZtSoh9YxQAAByTMBsA2nCWsqHdwhbZIslpbH4AsF9qxAG+97iFPUoyMw4AAGogzAaAdgySXDVyLdOUDW2BNgC7pEYc4Ge2sAEAqJYwGwDaMkpy2ci13KZszQHAW6gRB/jZIk/vwp4ZBwAAtRJmA0B7JmnnZv11SvgAAK+lRhzgZ3d5qhIHAIDqCbMBoD0nKdsVrdSnfoibbQBsRo04wM9sYQMA0FnCbABo01mSrw1dzx9Jxj5WAJ6hRhzgebawAQDoPGE2ALRrkOSqkWtZJLlIqVAHgESNOMBL5+abJJ9jCxsAgAYIswGgbaMkl41cyzxl4/zexwrQW2rEAZ43TakRv3FeBgCgJcJsAGjbSUo9dyu1q9OUDW036AD69btsEDXiAD963MIeRoMRAACNEmYDQPtOU25utbLBdp0SaADQNjXiAM+zhQ0AQG8IswGgHy6SfGnoev6d8h5AANqiRhzgZdcprxEaGwUAAH0hzAaA/viU5O+GrudDys08ALpNjTjAy+YpW9ij2MIGAKCHhNkA0C+jJJcNXc/v8X5AgK5SIw7wMlvYAAAQYTYA9M1Jyg2xVjbfFikV6gJtgG5QIw7wMlvYAADwA2E2APTPWUqg3UqIME0JtN3wA6iTGnGA1W5TAuwbowAAgO8JswGgn94n+aeh67lLCbQBqOt3zSBqxAGeM08JsEdJZsYBAADPE2YDQH99TvJXQ9dznRKaAHA8asQBVrOFDQAAryDMBoB+u0lbG3N/prxnEIDDUSMOsJotbAAA2JIwGwD67STl/dkthQ8fUm4UArBfasQBVrvLU4gNAABsQZgNAJylBNqt1MEuUt6fPfHRAuzld8YgasQBVp1FRyltQTPjAACAtxFmAwBJ2a77p6HrWSQ5TXLvowV4MzXiAOvZwgYAgD0QZgMAj4ZJPjZ0PdOUDW2BNsB21IgDrGYLGwAA9kyYDQB8a5zkvKHruU0JYwDYjBpxgPWmKQH2TTw4CQAAeyXMBgC+dZLyrulfG7qm65RQBoCX/+wfRI04wCqLlPB6uDwvAwAAByDMBgB+dJayod3SRt6HeH8hwI/UiAOsZwsbAACOSJgNADxnkOSqsWv6IyWkB+gzNeIA69nCBgCASgizAYCXDJN8bOh6Fkku4oYk0D9qxAE2M1+egUexhQ0AAFUQZgMAq0zSVvAxT9lKdHMS6AM14gCbuU4JsMdGAQAAdRFmAwCrnCSZpa0q2mnKhrZAG2iRGnGAzdjCBgCADhBmAwDrnCX52tg1XacEPQAtUCMO8Lpz4Ci2sAEAoBOE2QDAJgZJrhq7pn8n+eyjBTpMjTjAZuYpAfYopXUIAADoCGE2ALCpUZLLxq7pw/K6ALpCjTjA5m6XZ70bowAAgG4SZgMArzFJexW2vy+vC6BWasQBNmcLGwAAGiLMBgBe4zQl+G1pG3CR5CICbaA+asQBNneXZBhb2AAA0BRhNgDwWhdJvjR2TdPldd37eIEjUyMOsLlFygb2MLawAQCgScJsAGAbn5L83dg13aUE2gCHpkYc4PXnttHyLwAAoGHCbABgW6Mkl41d03VKmARwCGrEATZnCxsAAHpImA0AbOskyTjtbRH+mXKTFGAf1IgDvI4tbAAA6DFhNgDwFqdJJmkvkPkQN0yB3VEjDvA6iyQ3KQ8YTowDAAD6S5gNALzVRZIvjV3TYnldbp4Cb6FGHOB1pikB9k2Se+MAAACE2QDALnxO8ldj17RIqQOe+XiBV1AjDvD6M5ctbAAA4FnCbABgV27S3vbhNGVD22YQsIoacYDXm6c8EGkLGwAAeJEwGwDYlZMk47QX5NymsHvB4AAAFSJJREFUVAUD/EiNOMDrXScZLc+NAAAAKwmzAYBdOku5Mdlate51SmAFoEYc4PXmKTXio9jCBgAAXkGYDQDs2vsk/zR4XR9SbsAC/aNGHGA7trABAIA3EWYDAPvwOclfDV7Xv1Le6wj0gxpxgNezhQ0AAOyMMBsA2JdxkvPGrmmR5CLJxMcLzVIjDrCd25QA24N/AADAzgizAYB9OUkJfX9t7LrmKWGXTSNo68+rQdSIA2xzLhot/5oZBwAAsGvCbABgn85SNrRb226cpmxoC7Sh29SIA2zHFjYAAHAQwmwAYN8GSa4avK7r5bUB3aJGHGA7izy9C3tmHAAAwCEIswGAQxgm+djgdf0nyScfL1RPjTjA9u7yVCUOAABwUMJsAOBQxknOG7yuD3FzF2qlRhxgO4vl+WYYW9gAAMARCbMBgEM5SbkZ2mKt7+9JJj5iqIIacYDt2cIGAACqIswGAA7pLMnXBq9rkeQiAm04FjXiAG87x9wk+Rxb2AAAQGWE2QDAoQ2SXDV4XdOUQPveRwwHo0Yc4G1nl2FKkO38AgAAVEmYDQAcwyjJZYPXNU3ZPgf2R404wPYet7CH0SgDAAB0gDAbADiWSdqsA75OCdmA3VEjDvA2trABAIBOEmYDAMdykvJexhY3K/9MuWEMvI0acYC3uY4tbAAAoMOE2QDAMZ0l+drotX1IqVMHXv/nwiBqxAG2NU8JsEexhQ0AAHScMBsAOLZPSf5u8LoWSS5iEwo2oUYc4O2uUwLssVEAAACtEGYDADUYJbls8LoWKVumMx8xPEuNOMDb2MIGAACaJswGAGpwkrJF1OJG5jRlQ9sNZijUiAO83W1KiD02CgAAoGXCbACgFqcpldwthlu3KRuo0FdqxAHebp6ygT2K1hcAAKAnhNkAQE0uknxp9NquU4I86BM14gBvd5sSYN8YBQAA0DfCbACgNp+S/N3otX1IuRkNLVMjDvy/9u73vIkz7wLwuWjA6gDeCqxUgN8KQiqwqACoAG8FUSrwqALkCpArQOrA6sDqYD88NkqyBvxnRpp55r4/7XVtssscQZzLx+c3vJwVNgAAQJTZAEA/LVPvkvOPWFZRH2fEAdpxnfIubP+uAAAAEGU2ANBPkySr1FmK7VLOqa99zFTAGXGAdv7doEkpsW/EAQAAsKfMBgD6appSaNd4pnh793y3PmYG+mdzFmfEAV7qOvtT4gAAADxAmQ0A9Nm7JF8qfbZNykJboc0QOCMO0A4rbAAAgCdQZgMAfXeR5HOlz7ZIKQehr5wRB2jHJqXAbkQBAADweMpsAGAIlqm3TPsryUcfMT3ijDhAO3Z3/w4zT7IWBwAAwNMpswGAIZikfBP4daXP9z6WWhz/z9gszogDtOF+hb2M14kAAAC8iDIbABiKaZJV6l2K/harLQ7PGXGAdlhhAwAAdECZDQAMySzJZaXPtktyFt8Ap3vOiAO0Z5v9u7CtsAEAAFqmzAYAhmae5EOlz7ZJKbR9M5y2OSMO0K5FSoG9EgUAAEB3lNkAwBCtkryt9Nk2KctZaIMz4gDtscIGAAA4MGU2ADBEk5Rz3K8rfb5FSgEJz+GMOED7X5ebWGEDAAAcnDIbABiqaco3lWst6z6lrL/gMZwRB2jXNqXAnscKGwAA4GiU2QDAkM2SXFb8fO9TvpEOP+KMOEC7ru6+9i5FAQAAcHzKbABg6Jok55U+2y7JWcpJdbjnjDhAu+5X2E2SG3EAAAD0hzIbAKjBOvWeVt6llJc3PuZRc0YcoH1W2AAAAD2nzAYAajBJKXtrXaluUhba3tk5Ps6IA7Rrl/27sG/EAQAA0G/KbACgFtMk3yp+vquUYpNx/F6exRlxgDZdZ39KHAAAgIFQZgMANZkluaz4+RZ3z0h9nBEHaJ8VNgAAwMApswGA2jRJzit+vvexKquJM+IA7bPCBgAAqIQyGwCozSTJKnWvW/9IsvRRD5Yz4gDt2919bbyIFTYAAEA1lNkAQI3eJFmn3qJwl+Ts7hkZBmfEAbqxSTkjvkxyKw4AAIC6KLMBgFqdJfla8fNtUxa+vnHfb86IA7TvfoU9jx/sAgAAqJoyGwCo2cckf1b8fJuU0l6h3S/OiAN093XPChsAAGBElNkAQO2aJOcVP98ipTTluJwRB+j2a12TZCUKAACAcVFmAwC1m6R887vmgvGvlBU6h+eMOEA3tikr7CZW2AAAAKOlzAYAxmCaUmjXfPL5fco3/DnM76dZnBEH6IIVNgAAAN8pswGAsXiX5Evlz/hbkrWPuhPOiAN0xwobAACABymzAYAxuUjyueLn2yU5i0K7Tc6IA3TnKqXAXooCAACAhyizAYCxWabuYnKTUmhbtj2fM+IA3dmmFNhNkhtxAAAA8DPKbABgbCYp7+Gs+VT0JqWQ5Wm/L2ZxRhygK1bYAAAAPJkyGwAYo2lKoV3z6naRUszyc86IA3THChsAAIAXUWYDAGP1LsmXyp/xU5K5j/p/OCMO0K3r7EtsAAAAeDZlNgAwZvMkHyp/xvdRJiTOiAN0bXf39WYeK2wAAABaoswGAMZuleRtxc+3S3KWZD3Sz9cZcYBuWWEDAADQGWU2ADB2k5Si93XFz7hLOa19M5LP1BlxgO6/rjSxwgYAAKBjymwAgFJ+rlJ38blJWWjfVvp8zogDHOZryTzJsuKvJwAAAPSIMhsAoJgluaz8Ga9TCu2aOCMO0K1dSnk9z3hfWQEAAMCRKLMBAPbmST5U/oyLlPJ3yJwRB+ieFTYAAABHp8wGAPindeo/U/0+5V2nQ+KMOED3rLABAADoFWU2AMA/TZLcpP7F7x8phUXfOSMO0L1tSoHdxAobAACAHlFmAwD8r2mSb5U/4y7l/dnrnuY/izPiAF1bpBTYK1EAAADQR8psAICHzZJcVv6MuyRv0o8VnjPiAIdhhQ0AAMBgKLMBAH6sSXJe+TNuUhbaxyo0nBEHOAwrbAAAAAZHmQ0A8HPr1L8UXqQUyofijDjAYWxTCuwmyY04AAAAGBplNgDAz01SCoDaS9e/knzsOMdZnBEHOISrlAJ7KQoAAACGTJkNAPBrZ0m+juA536eUH21yRhzgMKywAQAAqI4yGwDgcT4m+XMEz/n/efn7VJ0RBzic6yTzWGEDAABQIWU2AMDjNUnOK3/GXcoSff3Ev88ZcYDD/rO6SSmxb8QBAABArZTZAACPN0lZLdde1m5SCu3bR/y1zogDHM519qfEAQAAoHrKbACAp3mTslqu/Xz2JuVc+EOcEQc4HCtsAAAARkuZDQDwdGdJvo7gORcphXXijDjAoVlhAwAAMHrKbACA57lI8nkEz7lIKbKdEQfo3i7JMmWFvRYHAAAAY6fMBgB4vmWUvAC83CalwF4muRUHAAAAFMpsAIDnmyRZxdltAJ7OChsAAAB+QZkNAPAy05RC+0QUADzCNuVVFVbYAAAA8AvKbACAl3uX5IsYAPiJRZIm5QegAAAAgEdQZgMAtOMiyWcxAPA325Qz4k2ssAEAAODJlNkAAO1ZJXkrBoDRs8IGAACAFiizAQDaM0myTvJaFACjY4UNAAAALVNmAwC0a5qyxDsRBcAoXKUU2EtRAAAAQLuU2QAA7ZsluRQDQLW2KQV2k+RGHAAAANANZTYAQDfmST6IAaAqVtgAAABwQMpsAIDurJK8FQPAoO2yfxf2jTgAAADgcJTZAADdmSRZJ3ktCoDBuc7+lDgAAABwBMpsAIBuTZN8EwPAIOxSyut5rLABAADg6JTZAADdmyW5FANAb1lhAwAAQA8pswEADqNJci4GgN7YJVkmuYgVNgAAAPSSMhsA4HDWSU7FAHBUm5Qz4sskt+IAAACA/lJmAwAcziRl/XciCoCDul9hz1N+sAgAAAAYAGU2AMBhTZN8EwPAQVhhAwAAwIC9EgEAwEGtk3wSA0CnFkl+S/kBoiaKbAAAABgky2wAgONokpyLAaA125QVdhPlNQAAAFRBmQ0AcByTJKskp6IAeJFFSoG9EgUAAADURZkNAHA8b1LOjp+IAuBJrLABAABgBJTZAADHdZbkqxgAHuUqpcReiQIAAADqp8wGADi+j0n+FAPAg7YpC+wmyY04AAAAYDyU2QAA/bBM8rsYAL67Simwl6IAAACAcVJmAwD0wyTlbO6pKIARs8IGAAAAvlNmAwD0xzSl0D4RBTAy1ynvwrbCBgAAAL5TZgMA9Mu7JF/EAIzALmWBPY8VNgAAAPAAZTYAQP9cJPksBqBS19mfEgcAAAD4IWU2AEA/LZP8LgagElbYAAAAwJMpswEA+mmS8v7sU1EAA7ZJKbAbUQAAAABPpcwGAOivaUqhfSIKYEB2Kdcl5knW4gAAAACeS5kNANBvsySXYgAG4H6FvUxyKw4AAADgpZTZAAD9N0/yQQxAD1lhAwAAAJ1RZgMADMMqyVsxAD2xzf5d2FbYAAAAQCeU2QAAwzBJWT2+FgVwRIuUAnslCgAAAKBrymwAgOGYphRIJ6IADsgKGwAAADgKZTYAwLDMklyKATgAK2wAAADgqJTZAADD0yQ5FwPQge3dP2PmscIGAAAAjkyZDQAwTOskp2IAWnKVUmIvRQEAAAD0hTIbAGCYJklu4v3ZwPPdr7Cbu3+eAAAAAPSKMhsAYLimSb6JAXgiK2wAAABgEJTZAADDNktyKQbgF3bZvwv7RhwAAADAECizAQCGr0lyLgbgAdfZnxIHAAAAGBRlNgDA8E2SrJKcigKIFTYAAABQCWU2AEAd3iRZJzkRBYyWFTYAAABQFWU2AEA9zpJ8FQOMyi7JMslFrLABAACAyrwSAQBANVZJPokBRmGT5H3KVYZZFNkAAABAhSyzAQDq0yQ5FwNU536FPU95rQAAAABA1ZTZAAD1maSstE9FAVXYpBTYyyS34gAAAADGQpkNAFCnNynLzRNRwGAtUi4trEQBAAAAjJEyGwCgXu+SfBEDDMo2ZYXdxAobAAAAGDllNgBA3S6SfBYD9J4VNgAAAMC/KLMBAOq3TPK7GKB3rLABAAAAfkKZDQBQv0nK2vNUFNALVykF9lIUAAAAAD+mzAYAGIdpSqF9Igo4im1Kgd0kuREHAAAAwK8pswEAxuNdki9igIOywgYAAAB4JmU2AMC4zJN8EAN0ygobAAAAoAXKbACA8VkleSsGaN119iU2AAAAAC+kzAYAGJ9JknWS16KAF9ullNfzWGEDAAAAtEqZDQAwTtOUhfaJKOBZrLABAAAAOqbMBgAYr1mSSzHAo1lhAwAAAByQMhsAYNzmST6IAX5qc/dnZZnkVhwAAAAAh6HMBgBgneRUDPAPu5Tyen73ZwQAAACAA1NmAwAwSTmZ7P3ZYIUNAAAA0BvKbAAAkmSa5JsYGCkrbAAAAIAeUmYDAHBvluRSDIzINqXAbmKFDQAAANA7ymwAAP6uSXIuBiq3uPu9vhIFAAAAQH8pswEA+Ld1klMxUBkrbAAAAICBUWYDAPBvkyQ3SU5EQQWssAEAAAAGSpkNAMBDzpJ8FQMDtU0psJuUH8wAAAAAYICU2QAA/MjHJH+KgQG5Simwl6IAAAAAGD5lNgAAP9MkORcDPWaFDQAAAFApZTYAAD8zSXnX8Kko6JnrJPNYYQMAAABUS5kNAMCvvEmyTnIiCo5sl7LAnscKGwAAAKB6ymwAAB7jLMlXMXAk19mfEgcAAABgJF6JAACAR1gl+Y8YOKBdkr+S/F/KD1M0IgEAAAAYF8tsAACeYpnkdzHQIStsAAAAAJIoswEAeJpJykr7VBS0aJfygxLzlPezAwAAAIAyGwCAJ5umFNonouCFNikF9jLJrTgAAAAA+DtlNgAAz/EuyRcx8AxW2AAAAAA8yisRAADwDMsk/xEDT7BN8j7JmySzKLIBAAAA+AXLbAAAXmKV5K0Y+IlFkubu9woAAAAAPJoyGwCAl5ikLGxfi4K/2aacEW/iXdgAAAAAPJMyGwCAl5qmrG5PRDF6VtgAAAAAtEaZDQBAG2ZJLsUwSlbYAAAAAHRCmQ0AQFvmST6IYTSuUgrspSgAAAAA6IIyGwCANq2SvBVDtbYpBXaT5EYcAAAAAHRJmQ0AQJsmSdZJXouiKlbYAAAAABycMhsAgLZNk3wTw+Dtsn8X9o04AAAAADg0ZTYAAF2YJbkUwyBdZ39KHAAAAACORpkNAEBXmiTnYhiE3d3nNY8VNgAAAAA9ocwGAKBL6ySnYugtK2wAAAAAekuZDQBAlyYpS98TUfTGLskyyUWssAEAAADoMWU2AABdmyb5Joaj26ScEV8muRUHAAAAAH33SgQAAHRsneSTGI5il2SR5LeUHypoosgGAAAAYCAsswEAOJQmybkYDsIKGwAAAIDBU2YDAHAokySrJKei6MwipcReiwIAAACAoVNmAwBwSG9SitYTUbRmm1JgN7HCBgAAAKAiymwAAA7tLMlXMbzYIqXAXokCAAAAgBopswEAOIaPSf4Uw5NZYQMAAAAwGspsAACOpUlyLoZHuUopsVeiAAAAAGAslNkAABzLJKWcPRXFg7YphX+T5EYcAAAAAIyNMhsAgGOaphTaJ6L47iqlwF6KAgAAAIAxU2YDAHBs75J8GXkGVtgAAAAA8C/KbAAA+uAiyecRPvd1yruwrbABAAAA4F+U2QAA9MUyye8jeM5dygJ7HitsAAAAAPghZTYAAH0xSXl/9mmlz3ed/SlxAAAAAOAXlNkAAPTJNKXQPqnkeaywAQAAAOCZlNkAAPTNLMnlwJ9hk1JgNz5OAAAAAHgeZTYAAH00T/JhYL/mXcp7v+dJ1j5CAAAAAHgZZTYAAH21SvJ2AL/O+xX2Msmtjw0AAAAA2qHMBgCgryYpC+fXPfy1WWEDAAAAQMeU2QAA9Nk0ZaF90pNfzzb7d2FbYQMAAABAh5TZAAD03SzJ5ZF/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  109503. /***/ }),
  109504. /* 44 */
  109505. /***/ (function(module, exports) {
  109506. module.exports = "HELP";
  109507. /***/ }),
  109508. /* 45 */
  109509. /***/ (function(module, exports) {
  109510. module.exports = "SHARE";
  109511. /***/ }),
  109512. /* 46 */
  109513. /***/ (function(module, exports, __webpack_require__) {
  109514. "use strict";
  109515. Object.defineProperty(exports, "__esModule", { value: true });
  109516. var babylonjs_1 = __webpack_require__(0);
  109517. /**
  109518. * The viewer's "extended" configuration.
  109519. * This configuration defines specific obejcts and parameters that we think make any model look good.
  109520. */
  109521. exports.extendedConfiguration = {
  109522. version: "3.2.0",
  109523. extends: "default",
  109524. camera: {
  109525. exposure: 3.034578,
  109526. fov: 0.7853981633974483,
  109527. contrast: 1.6,
  109528. toneMappingEnabled: true,
  109529. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  109530. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  109531. behaviors: {
  109532. framing: {
  109533. type: 2,
  109534. mode: 0,
  109535. positionScale: 0.5,
  109536. defaultElevation: 0.2617993877991494,
  109537. elevationReturnWaitTime: 3000,
  109538. elevationReturnTime: 2000,
  109539. framingTime: 500,
  109540. zoomStopsAnimation: false,
  109541. radiusScale: 0.866
  109542. },
  109543. autoRotate: {
  109544. type: 0,
  109545. idleRotationWaitTime: 4000,
  109546. idleRotationSpeed: 0.17453292519943295,
  109547. idleRotationSpinupTime: 2500,
  109548. zoomStopsAnimation: false
  109549. },
  109550. bouncing: {
  109551. type: 1,
  109552. lowerRadiusTransitionRange: 0.05,
  109553. upperRadiusTransitionRange: -0.2
  109554. }
  109555. },
  109556. upperRadiusLimit: 5,
  109557. lowerRadiusLimit: 0.5,
  109558. frameOnModelLoad: true,
  109559. framingElevation: 0.2617993877991494,
  109560. framingRotation: 1.5707963267948966,
  109561. radius: 2,
  109562. alpha: 1.5708,
  109563. beta: Math.PI * 0.5 - 0.2618,
  109564. wheelPrecision: 300,
  109565. minZ: 0.1,
  109566. maxZ: 50,
  109567. fovMode: 0,
  109568. pinchPrecision: 1500,
  109569. panningSensibility: 3000
  109570. },
  109571. lights: {
  109572. light0: {
  109573. type: 0,
  109574. frustumEdgeFalloff: 0,
  109575. intensity: 7,
  109576. intensityMode: 0,
  109577. radius: 0.6,
  109578. range: 0.6,
  109579. spotAngle: 60,
  109580. diffuse: {
  109581. r: 1,
  109582. g: 1,
  109583. b: 1
  109584. },
  109585. position: {
  109586. x: -2,
  109587. y: 2.5,
  109588. z: 2
  109589. },
  109590. target: {
  109591. x: 0,
  109592. y: 0,
  109593. z: 0
  109594. },
  109595. enabled: true,
  109596. shadowEnabled: true,
  109597. shadowBufferSize: 512,
  109598. shadowMinZ: 1,
  109599. shadowMaxZ: 10,
  109600. shadowFieldOfView: 60,
  109601. shadowFrustumSize: 2,
  109602. shadowConfig: {
  109603. useBlurCloseExponentialShadowMap: true,
  109604. useKernelBlur: true,
  109605. blurScale: 1.0,
  109606. bias: 0.001,
  109607. depthScale: 50 * (10 - 1),
  109608. frustumEdgeFalloff: 0
  109609. }
  109610. },
  109611. light1: {
  109612. type: 0,
  109613. frustumEdgeFalloff: 0,
  109614. intensity: 7,
  109615. intensityMode: 0,
  109616. radius: 0.4,
  109617. range: 0.4,
  109618. spotAngle: 57,
  109619. diffuse: {
  109620. r: 1,
  109621. g: 1,
  109622. b: 1
  109623. },
  109624. position: {
  109625. x: 4,
  109626. y: 3,
  109627. z: -0.5
  109628. },
  109629. target: {
  109630. x: 0,
  109631. y: 0,
  109632. z: 0
  109633. },
  109634. enabled: true,
  109635. shadowEnabled: false,
  109636. shadowBufferSize: 512,
  109637. shadowMinZ: 0.2,
  109638. shadowMaxZ: 10,
  109639. shadowFieldOfView: 28,
  109640. shadowFrustumSize: 2
  109641. },
  109642. light2: {
  109643. type: 0,
  109644. frustumEdgeFalloff: 0,
  109645. intensity: 1,
  109646. intensityMode: 0,
  109647. radius: 0.5,
  109648. range: 0.5,
  109649. spotAngle: 42.85,
  109650. diffuse: {
  109651. r: 0.8,
  109652. g: 0.8,
  109653. b: 0.8
  109654. },
  109655. position: {
  109656. x: -1,
  109657. y: 3,
  109658. z: -3
  109659. },
  109660. target: {
  109661. x: 0,
  109662. y: 0,
  109663. z: 0
  109664. },
  109665. enabled: true,
  109666. shadowEnabled: false,
  109667. shadowBufferSize: 512,
  109668. shadowMinZ: 0.2,
  109669. shadowMaxZ: 10,
  109670. shadowFieldOfView: 45,
  109671. shadowFrustumSize: 2
  109672. }
  109673. },
  109674. ground: {
  109675. shadowLevel: 0.9,
  109676. texture: "Ground_2.0-1024.png",
  109677. material: {
  109678. primaryColorHighlightLevel: 0.035,
  109679. primaryColorShadowLevel: 0,
  109680. enableNoise: true,
  109681. useRGBColor: false,
  109682. maxSimultaneousLights: 1,
  109683. diffuseTexture: {
  109684. gammaSpace: true
  109685. }
  109686. },
  109687. opacity: 1,
  109688. mirror: false,
  109689. receiveShadows: true,
  109690. size: 5
  109691. },
  109692. skybox: {
  109693. scale: 11,
  109694. cubeTexture: {
  109695. url: "Skybox_2.0-256.dds"
  109696. },
  109697. material: {
  109698. primaryColorHighlightLevel: 0.03,
  109699. primaryColorShadowLevel: 0.03,
  109700. enableNoise: true,
  109701. useRGBColor: false,
  109702. reflectionTexture: {
  109703. gammaSpace: true
  109704. }
  109705. }
  109706. },
  109707. engine: {
  109708. renderInBackground: true
  109709. },
  109710. scene: {
  109711. flags: {
  109712. shadowsEnabled: true,
  109713. particlesEnabled: false,
  109714. collisionsEnabled: false,
  109715. lightsEnabled: true,
  109716. texturesEnabled: true,
  109717. lensFlaresEnabled: false,
  109718. proceduralTexturesEnabled: false,
  109719. renderTargetsEnabled: true,
  109720. spritesEnabled: false,
  109721. skeletonsEnabled: true,
  109722. audioEnabled: false,
  109723. },
  109724. defaultMaterial: {
  109725. materialType: 'pbr',
  109726. reflectivityColor: {
  109727. r: 0.1,
  109728. g: 0.1,
  109729. b: 0.1
  109730. },
  109731. microSurface: 0.6
  109732. },
  109733. clearColor: {
  109734. r: 0.9,
  109735. g: 0.9,
  109736. b: 0.9,
  109737. a: 1.0
  109738. },
  109739. imageProcessingConfiguration: {
  109740. vignetteCentreX: 0,
  109741. vignetteCentreY: 0,
  109742. vignetteColor: {
  109743. r: 0.086,
  109744. g: 0.184,
  109745. b: 0.259,
  109746. a: 1
  109747. },
  109748. vignetteWeight: 0.855,
  109749. vignetteStretch: 0.5,
  109750. vignetteBlendMode: 0,
  109751. vignetteCameraFov: 0.7853981633974483,
  109752. isEnabled: true,
  109753. colorCurves: {
  109754. shadowsHue: 0,
  109755. shadowsDensity: 0,
  109756. shadowsSaturation: 0,
  109757. shadowsExposure: 0,
  109758. midtonesHue: 0,
  109759. midtonesDensity: 0,
  109760. midtonesExposure: 0,
  109761. midtonesSaturation: 0,
  109762. highlightsHue: 0,
  109763. highlightsDensity: 0,
  109764. highlightsExposure: 0,
  109765. highlightsSaturation: 0
  109766. }
  109767. },
  109768. mainColor: {
  109769. r: 0.8823529411764706,
  109770. g: 0.8823529411764706,
  109771. b: 0.8823529411764706
  109772. }
  109773. },
  109774. loaderPlugins: {
  109775. extendedMaterial: true,
  109776. applyMaterialConfig: true,
  109777. msftLod: true,
  109778. telemetry: true
  109779. },
  109780. model: {
  109781. rotationOffsetAxis: {
  109782. x: 0,
  109783. y: -1,
  109784. z: 0
  109785. },
  109786. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  109787. material: {
  109788. directEnabled: true,
  109789. directIntensity: 0.884,
  109790. emissiveIntensity: 1.04,
  109791. environmentIntensity: 0.6
  109792. },
  109793. entryAnimation: {
  109794. scaling: {
  109795. x: 0,
  109796. y: 0,
  109797. z: 0
  109798. },
  109799. time: 0.5,
  109800. easingFunction: 4,
  109801. easingMode: 1
  109802. },
  109803. exitAnimation: {
  109804. scaling: {
  109805. x: 0,
  109806. y: 0,
  109807. z: 0
  109808. },
  109809. time: 0.5,
  109810. easingFunction: 4,
  109811. easingMode: 1
  109812. },
  109813. normalize: true,
  109814. castShadow: true,
  109815. receiveShadows: true
  109816. },
  109817. lab: {
  109818. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  109819. environmentMap: {
  109820. texture: "EnvMap_2.0-256.env",
  109821. rotationY: 3,
  109822. tintLevel: 0.4
  109823. },
  109824. defaultRenderingPipelines: {
  109825. bloomEnabled: true,
  109826. bloomThreshold: 1.0,
  109827. fxaaEnabled: true,
  109828. bloomWeight: 0.05
  109829. }
  109830. }
  109831. };
  109832. /***/ }),
  109833. /* 47 */
  109834. /***/ (function(module, exports, __webpack_require__) {
  109835. "use strict";
  109836. Object.defineProperty(exports, "__esModule", { value: true });
  109837. /**
  109838. * Defines a default directional shadow light for normalized objects (!)
  109839. */
  109840. exports.shadowDirectionalLightConfiguration = {
  109841. model: {
  109842. receiveShadows: true,
  109843. castShadow: true
  109844. },
  109845. ground: {
  109846. receiveShadows: true
  109847. },
  109848. lights: {
  109849. shadowDirectionalLight: {
  109850. type: 1,
  109851. shadowEnabled: true,
  109852. target: { x: 0, y: 0, z: 0.5 },
  109853. position: { x: 1.49, y: 2.39, z: -1.33 },
  109854. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  109855. intensity: 4.887,
  109856. intensityMode: 0,
  109857. shadowBufferSize: 1024,
  109858. shadowFrustumSize: 6.0,
  109859. shadowFieldOfView: 50.977,
  109860. shadowMinZ: 0.1,
  109861. shadowMaxZ: 10.0,
  109862. shadowConfig: {
  109863. blurKernel: 32,
  109864. useBlurCloseExponentialShadowMap: true
  109865. }
  109866. }
  109867. }
  109868. };
  109869. /**
  109870. * Defines a default shadow-enabled spot light for normalized objects.
  109871. */
  109872. exports.shadowSpotlLightConfiguration = {
  109873. model: {
  109874. receiveShadows: true,
  109875. castShadow: true
  109876. },
  109877. ground: {
  109878. receiveShadows: true
  109879. },
  109880. lights: {
  109881. shadowSpotLight: {
  109882. type: 2,
  109883. intensity: 2,
  109884. shadowEnabled: true,
  109885. target: { x: 0, y: 0, z: 0.5 },
  109886. position: { x: 0, y: 3.5, z: 3.7 },
  109887. angle: 1,
  109888. shadowOrthoScale: 0.5,
  109889. shadowBufferSize: 1024,
  109890. shadowMinZ: 0.1,
  109891. shadowMaxZ: 50.0,
  109892. shadowConfig: {
  109893. frustumEdgeFalloff: 0.5,
  109894. blurKernel: 32,
  109895. useBlurExponentialShadowMap: true
  109896. }
  109897. }
  109898. }
  109899. };
  109900. /***/ }),
  109901. /* 48 */
  109902. /***/ (function(module, exports, __webpack_require__) {
  109903. "use strict";
  109904. Object.defineProperty(exports, "__esModule", { value: true });
  109905. /**
  109906. * Lab-oriented default .env support
  109907. */
  109908. exports.environmentMapConfiguration = {
  109909. lab: {
  109910. assetsRootURL: '/assets/environment/',
  109911. environmentMap: {
  109912. texture: 'EnvMap_2.0-256.env',
  109913. rotationY: 0,
  109914. tintLevel: 0.4
  109915. }
  109916. }
  109917. };
  109918. /***/ }),
  109919. /* 49 */
  109920. /***/ (function(module, exports, __webpack_require__) {
  109921. "use strict";
  109922. Object.defineProperty(exports, "__esModule", { value: true });
  109923. var telemetryLoaderPlugin_1 = __webpack_require__(50);
  109924. var msftLodLoaderPlugin_1 = __webpack_require__(51);
  109925. var extendedMaterialLoaderPlugin_1 = __webpack_require__(52);
  109926. var pluginCache = {};
  109927. /**
  109928. * Get a loader plugin according to its name.
  109929. * The plugin will be cached and will be reused if called for again.
  109930. *
  109931. * @param name the name of the plugin
  109932. */
  109933. function getLoaderPluginByName(name) {
  109934. if (!pluginCache[name]) {
  109935. switch (name) {
  109936. case 'telemetry':
  109937. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  109938. break;
  109939. case 'msftLod':
  109940. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  109941. break;
  109942. case 'applyMaterialConfig':
  109943. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  109944. break;
  109945. case 'extendedMaterial':
  109946. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  109947. break;
  109948. }
  109949. }
  109950. return pluginCache[name];
  109951. }
  109952. exports.getLoaderPluginByName = getLoaderPluginByName;
  109953. /***/ }),
  109954. /* 50 */
  109955. /***/ (function(module, exports, __webpack_require__) {
  109956. "use strict";
  109957. Object.defineProperty(exports, "__esModule", { value: true });
  109958. var telemetryManager_1 = __webpack_require__(5);
  109959. var babylonjs_1 = __webpack_require__(0);
  109960. var TelemetryLoaderPlugin = /** @class */ (function () {
  109961. function TelemetryLoaderPlugin() {
  109962. }
  109963. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  109964. this._model = model;
  109965. this._loadStart = babylonjs_1.Tools.Now;
  109966. };
  109967. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  109968. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewer(), {
  109969. model: model,
  109970. loadTime: babylonjs_1.Tools.Now - this._loadStart
  109971. });
  109972. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  109973. };
  109974. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  109975. this._loadEnd = babylonjs_1.Tools.Now;
  109976. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewer(), {
  109977. model: this._model,
  109978. loadTime: this._loadEnd - this._loadStart
  109979. });
  109980. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  109981. };
  109982. TelemetryLoaderPlugin.prototype.onComplete = function () {
  109983. this._loadEnd = babylonjs_1.Tools.Now;
  109984. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewer(), {
  109985. model: this._model,
  109986. loadTime: this._loadEnd - this._loadStart
  109987. });
  109988. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  109989. };
  109990. return TelemetryLoaderPlugin;
  109991. }());
  109992. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  109993. /***/ }),
  109994. /* 51 */
  109995. /***/ (function(module, exports, __webpack_require__) {
  109996. "use strict";
  109997. Object.defineProperty(exports, "__esModule", { value: true });
  109998. /**
  109999. * A loder plugin to use MSFT_lod extension correctly (glTF)
  110000. */
  110001. var MSFTLodLoaderPlugin = /** @class */ (function () {
  110002. function MSFTLodLoaderPlugin() {
  110003. }
  110004. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  110005. this._model = model;
  110006. };
  110007. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  110008. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  110009. var MSFT_lod = extension;
  110010. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  110011. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  110012. }
  110013. };
  110014. return MSFTLodLoaderPlugin;
  110015. }());
  110016. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  110017. /***/ }),
  110018. /* 52 */
  110019. /***/ (function(module, exports, __webpack_require__) {
  110020. "use strict";
  110021. Object.defineProperty(exports, "__esModule", { value: true });
  110022. var babylonjs_1 = __webpack_require__(0);
  110023. /**
  110024. * A (PBR) material will be extended using this function.
  110025. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  110026. */
  110027. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  110028. function ExtendedMaterialLoaderPlugin() {
  110029. }
  110030. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  110031. var material = baseMaterial;
  110032. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  110033. };
  110034. return ExtendedMaterialLoaderPlugin;
  110035. }());
  110036. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  110037. /***/ }),
  110038. /* 53 */
  110039. /***/ (function(module, exports, __webpack_require__) {
  110040. /*!
  110041. * PEP v0.4.3 | https://github.com/jquery/PEP
  110042. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  110043. */
  110044. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  110045. // define inherited MouseEvent properties
  110046. // skip bubbles and cancelable since they're set above in initEvent()
  110047. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  110048. // Spec requires that pointers without pressure specified use 0.5 for down
  110049. // state and 0 for up state.
  110050. var f=0;
  110051. // add x/y properties aliased to clientX/Y
  110052. // define the properties of the PointerEvent interface
  110053. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  110054. // only activate if this platform does not have pointer events
  110055. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  110056. * This is the constructor for new PointerEvents.
  110057. *
  110058. * New Pointer Events must be given a type, and an optional dictionary of
  110059. * initialization properties.
  110060. *
  110061. * Due to certain platform requirements, events returned from the constructor
  110062. * identify as MouseEvents.
  110063. *
  110064. * @constructor
  110065. * @param {String} inType The type of the event to create.
  110066. * @param {Object} [inDict] An optional dictionary of initial event properties.
  110067. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  110068. */
  110069. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  110070. // return value, key, map
  110071. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  110072. // MouseEvent
  110073. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  110074. // DOM Level 3
  110075. "buttons",
  110076. // PointerEvent
  110077. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  110078. // event instance
  110079. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  110080. // MouseEvent
  110081. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  110082. // DOM Level 3
  110083. 0,
  110084. // PointerEvent
  110085. 0,0,0,0,0,0,"",0,!1,
  110086. // event instance
  110087. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  110088. // Scope objects for native events.
  110089. // This exists for ease of testing.
  110090. eventSources:Object.create(null),eventSourceList:[],/**
  110091. * Add a new event source that will generate pointer events.
  110092. *
  110093. * `inSource` must contain an array of event names named `events`, and
  110094. * functions with the names specified in the `events` array.
  110095. * @param {string} name A name for the event source
  110096. * @param {Object} source A new source of platform events.
  110097. */
  110098. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110099. // call eventsource register
  110100. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110101. // call eventsource register
  110102. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  110103. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  110104. return!1}},
  110105. // EVENTS
  110106. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  110107. // LISTENER LOGIC
  110108. eventHandler:function(a){
  110109. // This is used to prevent multiple dispatch of pointerevents from
  110110. // platform events. This can happen when two elements in different scopes
  110111. // are set up to create pointer events, which is relevant to Shadow DOM.
  110112. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  110113. // set up event listeners
  110114. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  110115. // remove event listeners
  110116. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  110117. // EVENT CREATION AND TRACKING
  110118. /**
  110119. * Creates a new Event of type `inType`, based on the information in
  110120. * `inEvent`.
  110121. *
  110122. * @param {string} inType A string representing the type of event to create
  110123. * @param {Event} inEvent A platform event with a target
  110124. * @return {Event} A PointerEvent of type `inType`
  110125. */
  110126. makeEvent:function(b,c){
  110127. // relatedTarget must be null if pointer is captured
  110128. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  110129. // make and dispatch an event in one call
  110130. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  110131. * Returns a snapshot of inEvent, with writable properties.
  110132. *
  110133. * @param {Event} inEvent An event that contains properties to copy.
  110134. * @return {Object} An object containing shallow copies of `inEvent`'s
  110135. * properties.
  110136. */
  110137. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  110138. // Work around SVGInstanceElement shadow tree
  110139. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  110140. // This is the behavior implemented by Firefox.
  110141. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  110142. // keep the semantics of preventDefault
  110143. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  110144. // Order of conditions due to document.contains() missing in IE.
  110145. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  110146. // Touch: Do not propagate if node is detached.
  110147. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  110148. * Dispatches the event to its target.
  110149. *
  110150. * @param {Event} inEvent The event to be dispatched.
  110151. * @return {Boolean} True if an event handler returns true, false otherwise.
  110152. */
  110153. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  110154. // is element a shadow host?
  110155. e=this.targetingShadow(f);e;){if(
  110156. // find the the element inside the shadow root
  110157. d=e.elementFromPoint(b,c)){
  110158. // shadowed element may contain a shadow root
  110159. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  110160. // check for older shadows
  110161. e=this.olderShadow(e)}
  110162. // light dom element is the target
  110163. return f}},owner:function(a){
  110164. // walk up until you hit the shadow root or document
  110165. for(var b=a;b.parentNode;)b=b.parentNode;
  110166. // the owner element is expected to be a Document or ShadowRoot
  110167. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  110168. // if x, y is not in this root, fall back to document search
  110169. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  110170. // Only watch scopes that can target find, as these are top-level.
  110171. // Otherwise we can see duplicate additions and removals that add noise.
  110172. //
  110173. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  110174. // a removal without an insertion when a node is redistributed among
  110175. // shadows. Since it all ends up correct in the document, watching only
  110176. // the document will yield the correct mutations to watch.
  110177. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  110178. // register all touch-action = none nodes on document load
  110179. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  110180. // find children with touch-action
  110181. var b=x(a,this.findElements,this);
  110182. // flatten the list
  110183. // make sure the added nodes are accounted for
  110184. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  110185. // handler block for native mouse events
  110186. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  110187. // collide with the global mouse listener
  110188. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  110189. // simulated mouse events will be swallowed near a primary touchend
  110190. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  110191. // Update buttons state after possible out-of-document mouseup.
  110192. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  110193. // Produces wrong state of buttons in Browsers without `buttons` support
  110194. // when a mouse button that was pressed outside the document is released
  110195. // inside and other buttons are still pressed down.
  110196. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  110197. // Support: Firefox <=44 only
  110198. // FF Ubuntu includes the lifted button in the `buttons` property on
  110199. // mouseup.
  110200. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  110201. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  110202. // set touch-action on shadows as well
  110203. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  110204. // remove touch-action from shadow
  110205. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  110206. // simply update scrollType if listeners are already established
  110207. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  110208. // set primary touch if there no pointers, or the only pointer is the mouse
  110209. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  110210. // forward modifier keys
  110211. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110212. // forward touch preventDefaults
  110213. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  110214. // For single axis scrollers, determines whether the element should emit
  110215. // pointer events or behave as a scroller
  110216. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  110217. // this element is a touch-action: none, should never scroll
  110218. b=!1;else if("XY"===c)
  110219. // this element should always scroll
  110220. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  110221. // if delta in the scroll axis > delta other axis, scroll instead of
  110222. // making events
  110223. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  110224. // In some instances, a touchstart can happen without a touchend. This
  110225. // leaves the pointermap in a broken state.
  110226. // Therefore, on every touchstart, we remove the touches that did not fire a
  110227. // touchend event.
  110228. // To keep state globally consistent, we fire a
  110229. // pointercancel for this "abandoned" touch
  110230. vacuumTouches:function(a){var b=a.touches;
  110231. // pointermap.size should be < tl.length here, as the touchstart has not
  110232. // been processed yet.
  110233. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  110234. // Never remove pointerId == 1, which is mouse.
  110235. // Touch identifiers are 2 smaller than their pointerId, which is the
  110236. // index in pointermap.
  110237. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  110238. // a finger drifted off the screen, ignore it
  110239. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  110240. // recover from retargeting by shadow
  110241. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  110242. // clean up case when finger leaves the screen
  110243. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  110244. // prevent synth mouse events from creating pointer events
  110245. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  110246. // only the primary finger will synth mouse events
  110247. if(this.isPrimaryTouch(c)){
  110248. // remember x/y of last touch
  110249. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  110250. /***/ }),
  110251. /* 54 */
  110252. /***/ (function(module, exports, __webpack_require__) {
  110253. "use strict";
  110254. Object.defineProperty(exports, "__esModule", { value: true });
  110255. var defaultViewer_1 = __webpack_require__(9);
  110256. var mappers_1 = __webpack_require__(3);
  110257. var _1 = __webpack_require__(6);
  110258. /**
  110259. * Will attach an init function the the DOMContentLoaded event.
  110260. * The init function will be removed automatically after the event was triggered.
  110261. */
  110262. function initListeners() {
  110263. document.addEventListener("DOMContentLoaded", init);
  110264. function init(event) {
  110265. document.removeEventListener("DOMContentLoaded", init);
  110266. if (_1.viewerGlobals.disableInit || _1.disableInit)
  110267. return;
  110268. InitTags();
  110269. }
  110270. }
  110271. exports.initListeners = initListeners;
  110272. /**
  110273. * Select all HTML tags on the page that match the selector and initialize a viewer
  110274. *
  110275. * @param selector the selector to initialize the viewer on (default is 'babylon')
  110276. */
  110277. function InitTags(selector) {
  110278. if (selector === void 0) { selector = 'babylon'; }
  110279. var elements = document.querySelectorAll(selector);
  110280. for (var i = 0; i < elements.length; ++i) {
  110281. var element = elements.item(i);
  110282. // get the html configuration
  110283. var configMapper = mappers_1.mapperManager.getMapper('dom');
  110284. var config = configMapper.map(element);
  110285. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  110286. }
  110287. }
  110288. exports.InitTags = InitTags;
  110289. /***/ })
  110290. /******/ ]);
  110291. return BabylonViewer;
  110292. });